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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,7 +40,9 @@ Cowork), or in Claude Code:
40
40
  claude mcp add --transport http diya-submit https://submit.diyaccounting.co.uk/mcp
41
41
  ```
42
42
 
43
- The client finds the sign-in through `/.well-known/oauth-protected-resource/mcp`, registers itself, and
43
+ The endpoint answers `initialize`, `ping` and `tools/list` without a token, so a client or a catalogue
44
+ can read the tools first. The first tool call without a token gets 401 with a `WWW-Authenticate`
45
+ challenge. The client finds the sign-in through `/.well-known/oauth-protected-resource/mcp`, registers itself, and
44
46
  the user signs in with their Submit account. The ci form of the URL is
45
47
  `https://ci-submit.diyaccounting.co.uk/mcp`. The hosted tool set is `HOSTED_TOOL_NAMES` in
46
48
  `lib/hosted-tools.js`: `open_book` reads the DIYA cloud only. The sign-in pair, the filesystem tools,
@@ -64,7 +66,7 @@ HMRC requires data about the device behind each request. The two surfaces send d
64
66
  | `request_hmrc_authorisation` | HMRC's sign-in link for this session. `services` is `vat` (the default) and `itsa`; `hmrcAccount` is `live` (the default) or `synthetic`. Answers `url`, `expiresAt`, `scope`, `hmrcAccount`. The user grants access on HMRC's pages; Submit keeps HMRC's tokens and renews the access token for the rest of the session. No token reaches the chat. |
65
67
  | `list_vat_obligations` | VAT obligations for `vrn` (or `clientId`), filtered by `from`, `to`, `status`. Uses the session's HMRC authorisation; optional `hmrcAccount` (the authorisation's own by default), `govTestScenario`. |
66
68
  | `submit_vat_return` | Files the seven confirmed boxes (`vatDueSales`, `vatDueAcquisitions`, `vatReclaimedCurrPeriod`, `totalValueSalesExVAT`, `totalValuePurchasesExVAT`, `totalValueGoodsSuppliedExVAT`, `totalAcquisitionsExVAT`) for `periodStart` to `periodEnd`, for `vatNumber` or `clientId`. Uses the session's HMRC authorisation. Answers `receipt`, `periodKey`, `receiptId`. |
67
- | `get_vat_receipt` | A stored receipt by `name` (`<receiptId>.json`); optional `clientId`. |
69
+ | `get_vat_receipt` | A stored VAT return receipt by `name` (`<receiptId>.json`); optional `clientId`. Answers HMRC's `processingDate`, `formBundleNumber`, `paymentIndicator` and `chargeRefNumber`. |
68
70
  | `render_micro_entity_accounts_sandbox` | The rendered micro-entity iXBRL for confirmed figures, without reaching the Companies House gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `balanceSheet`, `averageEmployees`, `director`, `statementsAccepted`. |
69
71
  | `render_small_company_accounts_sandbox` | The rendered small-company (FRS 102 section 1A) iXBRL for confirmed figures, without reaching the gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `averageEmployees`, `director`, `statementsAccepted` (four small-company statements) and `smallCompany` (`filleted`, `principalActivity`, `accountingPolicies`, `directors`, `balanceSheet`, `profitAndLoss`, `fixedAssetNote`). |
70
72
  | `request_companies_house_codes` | A link where the user types the Companies House codes instead of the chat. `kind` is `accounts`, `confirmation-statement` (with `directors` in filing order) or `confirmation-statement-data`; answers `entryId`, `url`, `expiresAt`. The entry lasts ten minutes and one filing call uses it up. With `clientIds` (no `companyNumber`) the page asks for one code per practice client and each client's filing call, including through `run_for_clients`, takes only its own. |
package/lib/book-tools.js CHANGED
@@ -107,13 +107,11 @@ async function bookChecksFor(book, lines) {
107
107
  * The summary open_book answers: what the book is, whose it is, which period
108
108
  * it covers, how many lines it holds, and the check and warning counts.
109
109
  */
110
- function summarise(session, kind, bookChecks) {
111
- const { book, lines, product, sourcePath } = session;
110
+ function summarise(session, bookChecks) {
111
+ const { book, lines, product } = session;
112
112
  const info = book.documentInfo ?? {};
113
113
  const entity = book.entityInformation ?? {};
114
114
  return {
115
- kind,
116
- sourcePath,
117
115
  product,
118
116
  entity: entity.organizationIdentifier ?? null,
119
117
  period: { start: isoDate(info.periodCoveredStart), end: isoDate(info.periodCoveredEnd) },
@@ -124,14 +122,15 @@ function summarise(session, kind, bookChecks) {
124
122
  }
125
123
 
126
124
  /**
127
- * list_books: the books saved in the DIYA cloud, most recently updated first, over the route the
128
- * spreadsheets site's DIYA-GL pages list (GET /api/v1/books). Each row is a book's metadata, whose
129
- * bookId open_book takes. clientId lists a practice client's book set instead of the practice's own.
125
+ * The metadata of each book saved in the DIYA cloud, most recently updated first, over the route
126
+ * the spreadsheets site's DIYA-GL pages list (GET /api/v1/books): every field the route stores,
127
+ * the etag a replacing save sends among them. clientId lists a practice client's book set instead
128
+ * of the practice's own.
130
129
  * @param {Object} session
131
130
  * @param {{clientId?: string}} params
132
- * @returns {Promise<{entitlement: Object, books: Object[]}>}
131
+ * @returns {Promise<Object[]>}
133
132
  */
134
- export async function listBooks(session, { clientId } = {}) {
133
+ export async function listBookMetadata(session, { clientId } = {}) {
135
134
  const query = clientId ? `?clientId=${encodeURIComponent(clientId)}` : "";
136
135
  const response = await fetch(`${baseUrl()}/api/v1/books${query}`, {
137
136
  headers: { Authorization: `Bearer ${await session.credentials.accessToken()}` },
@@ -140,7 +139,29 @@ export async function listBooks(session, { clientId } = {}) {
140
139
  if (!response.ok) {
141
140
  throw new Error(body?.message || `list_books failed with HTTP ${response.status}`);
142
141
  }
143
- return { entitlement: body.entitlement, books: body.books ?? [] };
142
+ return body.books ?? [];
143
+ }
144
+
145
+ /**
146
+ * list_books: the saved books, most recently updated first, each as the bookId open_book takes,
147
+ * the title, the product and the period the book covers. The route's other fields (its versions,
148
+ * etags, sizes, times, retention and the account's entitlement) answer no question a person asks
149
+ * about their books, so the tool leaves them out.
150
+ * @param {Object} session
151
+ * @param {{clientId?: string}} params
152
+ * @returns {Promise<{books: Array<{bookId: string, title: string|null, product: string|null,
153
+ * period: {start: string|null, end: string|null}}>}>}
154
+ */
155
+ export async function listBooks(session, { clientId } = {}) {
156
+ const books = await listBookMetadata(session, { clientId });
157
+ return {
158
+ books: books.map((book) => ({
159
+ bookId: book.bookId,
160
+ title: book.title ?? null,
161
+ product: book.product ?? null,
162
+ period: { start: isoDate(book.periodCoveredStart), end: isoDate(book.periodCoveredEnd) },
163
+ })),
164
+ };
144
165
  }
145
166
 
146
167
  /**
@@ -169,7 +190,7 @@ async function openCloudBook(session, { bookId, clientId } = {}) {
169
190
  session.sourcePath = null;
170
191
  session.cloud = { bookId, clientId: clientId ?? null, etag: body.metadata.latestETag };
171
192
 
172
- return summarise(session, "cloud", await bookChecksFor(book, lines));
193
+ return summarise(session, await bookChecksFor(book, lines));
173
194
  }
174
195
 
175
196
  /**
@@ -220,7 +241,7 @@ export async function openBook(session, { path, cloud, bookId, clientId } = {})
220
241
  session.product = product;
221
242
  session.sourcePath = resolved;
222
243
 
223
- return summarise(session, kind, await bookChecksFor(book, lines));
244
+ return { kind, sourcePath: resolved, ...summarise(session, await bookChecksFor(book, lines)) };
224
245
  }
225
246
 
226
247
  function refuseUnlessValid(book, lines) {
@@ -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,85 @@
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
+ // The link goes to a person, so it carries the public address of the environment, the one the
38
+ // customer signs in on. DIYA_SUBMIT_BASE_URL is the deployment's own host, which the tools call.
39
+ function publicBaseUrl() {
40
+ const value = process.env.DIY_SUBMIT_BASE_URL;
41
+ if (!value) throw new Error("DIY_SUBMIT_BASE_URL is not set");
42
+ return value.replace(/\/$/, "");
43
+ }
44
+
45
+ /**
46
+ * The link to the VAT form that carries a handoff in its fragment.
47
+ * @param {{kind: string, sourceFileName: string, packageVersion: string, period: Object, figures: Object}} handoff
48
+ * @returns {string}
49
+ */
50
+ export function vatHandoffLink(handoff) {
51
+ const encoded = Buffer.from(JSON.stringify(handoff), "utf8").toString("base64url");
52
+ return `${publicBaseUrl()}${VAT_FORM_PATH}#books=${encoded}`;
53
+ }
54
+
55
+ /**
56
+ * prepare_vat_return: derives the return for the quarter ending on periodEnd from the session's
57
+ * loaded book, the way derive_vat_return does, and answers the link that opens the VAT form with
58
+ * those figures. Deriving here, in place of taking figures as arguments, means the link can only
59
+ * carry what derive_vat_return answers for the same period.
60
+ * @param {Object} session
61
+ * @param {{periodEnd: string, periodStart?: string, periodKey?: string}} params
62
+ */
63
+ export async function prepareVatReturn(session, params = {}) {
64
+ const derived = await deriveVatReturn(session, params);
65
+ const figures = {};
66
+ for (const name of VAT_FIGURE_NAMES) {
67
+ const value = derived.hmrc?.[name];
68
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`The derived return carries no number for ${name}`);
69
+ figures[name] = value;
70
+ }
71
+ const period = { periodStart: derived.periodStart, periodEnd: derived.periodEnd };
72
+ const link = vatHandoffLink({
73
+ kind: "vat",
74
+ sourceFileName: session.sourcePath ? basename(session.sourcePath) : session.book.entityInformation?.organizationDescription || "book",
75
+ packageVersion: await packageVersion(),
76
+ period,
77
+ figures,
78
+ });
79
+ return {
80
+ link,
81
+ period,
82
+ figures,
83
+ instruction: "Open this link, check the figures on the page, tick the declaration and file the return there. Nothing has been filed.",
84
+ };
85
+ }
@@ -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 " +