@diy-accounting-uk/diya-submit 0.1.0 → 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,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-07 File VAT returns and accounts via API
5
+ // - **Use when:** confirmed VAT or accounts figures must be filed, fetched or polled against the deployed API.
6
+ // - **Does:** callSubmitApi in mcp/lib/submit-tools.js is the shared HTTP layer behind list_vat_obligations, submit_vat_return, get_vat_receipt, render_micro_entity_accounts_sandbox, submit_micro_entity_accounts, render_small_company_accounts_sandbox, submit_small_company_accounts_sandbox and poll_submission. The small-company tools post to the same companies-house/accounts routes with a smallCompany section, so poll_submission kind accounts polls both. It carries the session bearer token, the HMRC and custom-authoriser headers, and polls a 202 response to a terminal status. list_vat_obligations and submit_vat_return take no HMRC token argument: hmrcGrantFor names the session's HMRC grant (MCP-21) to Submit in the x-mcp-hmrc-grant header on each call, so the token stays inside Submit, and fails with a message naming request_hmrc_authorisation when the session holds none.
7
+ // - **Run:** no command; see Does and Entry
8
+ // - **Entry:** `mcp/lib/submit-tools.js:callSubmitApi`; `mcp/lib/submit-tools.js:hmrcGrantFor`; `mcp/lib/submit-tools.js:submitVatReturn`; `mcp/lib/submit-tools.js:submitMicroEntityAccounts`
9
+ // - **Files:** mcp/lib/submit-tools.js, mcp/test/submit-tools.test.js
10
+ // - **Keywords:** submit_vat_return, list_vat_obligations, get_vat_receipt, companies house accounts, callSubmitApi, 202 poll, hmrc access token, hmrc grant
11
+ // - **Related:** MCP-05, MCP-04, MCP-08, MCP-21
12
+ // @end-capability
13
+
4
14
  // submit-tools.js -- the Submit-facing tools over the deployed REST API: the figures
5
15
  // derive_vat_return and derive_micro_entity_accounts answered, filed or fetched through this
6
16
  // service's own HMRC and Companies House routes. Like practice-tools.js, these reach DIY
@@ -12,16 +22,17 @@
12
22
  // claim names the MCP client -- ApiStack.java's main and custom authorisers
13
23
  // both accept it, the same way they accept the Submit web client's). Two routes here
14
24
  // (list_vat_obligations, submit_vat_return) sit behind the API's custom Lambda authoriser, whose
15
- // identity source is the X-Authorization header (ApiStack.java), which frees the plain
16
- // Authorization header for the HMRC access token those two routes read directly
17
- // (hmrcVatObligationGet.js reads it from the header; hmrcVatReturnPost.js takes it as the body's
18
- // accessToken field). Those two routes also carry X-Id-Token (the session credentials' idToken(), when it answers one), so the
25
+ // identity source is the X-Authorization header (ApiStack.java). The HMRC handlers open the
26
+ // session's HMRC grant from the x-mcp-hmrc-grant header, so no HMRC token travels with a call. Those two routes also carry X-Id-Token (the session credentials' idToken(), when it answers one), so the
19
27
  // custom authoriser can build Gov-Client-Multi-Factor from a verified claim rather than finding
20
28
  // none (see app/functions/auth/customAuthorizer.js's extractMfaContext). Every other route here
21
29
  // sits behind the standard Cognito JWT authoriser, so the session bearer goes in the plain
22
30
  // Authorization header, as practice-tools.js sends it.
23
31
  //
24
- // Obtaining the HMRC access token remains outside this tool's scope.
32
+ // The HMRC access token comes from the session's HMRC grant, which request_hmrc_authorisation
33
+ // starts: the user grants access in the browser, Submit's callback stores HMRC's tokens server
34
+ // side, and the tools that call HMRC read the access token back by the grant id for each call.
35
+ // No tool takes the token as an argument, and none answers the grant id or a token to the chat.
25
36
 
26
37
  function baseUrl() {
27
38
  const value = process.env.DIYA_SUBMIT_BASE_URL;
@@ -78,22 +89,25 @@ async function pollUntilSettled(session, url, requestInit, firstResponse) {
78
89
  * set, or the standard Authorization header otherwise; extra headers (an HMRC access token,
79
90
  * Gov-Test-Scenario, hmrcAccount) merge in on top and are never overwritten by the session
80
91
  * header. A customAuthorizer call also carries X-Id-Token when the session's credentials answer an
81
- * id token, which customAuthorizer.js reads to build Gov-Client-Multi-Factor server-side. A 202 response is
92
+ * id token, which customAuthorizer.js reads to build Gov-Client-Multi-Factor server-side, and the
93
+ * session's clientHeaders, which buildFraudHeaders.js reads for HMRC's fraud prevention data. A 202 response is
82
94
  * polled to a terminal status before this returns (see pollUntilSettled); a poll that never
83
95
  * settles, or outlasts the session's pollBudgetMs, throws with the poll URL in the message rather than returning a partial result.
84
96
  * Exported so practice-tools.js's client tools (list_clients, add_client, invite_client,
85
97
  * client_authorisation_status) call the same routes over the same HTTP layer rather than a
86
98
  * second one of their own.
87
- * @param {{credentials: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>}, pollBudgetMs: number|null}} session
99
+ * @param {{credentials: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>}, pollBudgetMs: number|null, clientHeaders: () => Promise<Object>}} session
88
100
  * @param {string} path - the route, e.g. "/api/v1/hmrc/vat/obligation?vrn=..."
89
101
  * @param {{method?: string, body?: Object, headers?: Object, customAuthorizer?: boolean}} [options]
90
102
  */
91
103
  export async function callSubmitApi(session, path, { method = "GET", body, headers = {}, customAuthorizer = false } = {}) {
92
104
  const sessionHeaderName = customAuthorizer ? "X-Authorization" : "Authorization";
93
105
  const idToken = customAuthorizer ? await session.credentials.idToken() : null;
106
+ const clientHeaders = customAuthorizer ? await session.clientHeaders() : {};
94
107
  const finalHeaders = {
95
108
  [sessionHeaderName]: `Bearer ${await session.credentials.accessToken()}`,
96
109
  ...(idToken ? { "X-Id-Token": idToken } : {}),
110
+ ...clientHeaders,
97
111
  "x-initial-request": "true",
98
112
  ...headers,
99
113
  };
@@ -111,20 +125,79 @@ export async function callSubmitApi(session, path, { method = "GET", body, heade
111
125
  return responseBody;
112
126
  }
113
127
 
128
+ export const HMRC_SERVICES = ["vat", "itsa", "agent"];
129
+ export const HMRC_ACCOUNTS = ["synthetic", "live"];
130
+
131
+ const NO_GRANT_MESSAGE =
132
+ "No HMRC authorisation is held for this session. Call request_hmrc_authorisation, show the user its link, " +
133
+ "and call this tool again once they have granted access.";
134
+
135
+ /**
136
+ * request_hmrc_authorisation: a new HMRC grant for this session, replacing any earlier one.
137
+ * @param {Object} session
138
+ * @param {{services?: string[], hmrcAccount?: string}} params
139
+ * @returns {Promise<{url: string, expiresAt: string, scope: string, hmrcAccount: string}>}
140
+ */
141
+ export async function requestHmrcAuthorisation(session, params = {}) {
142
+ const services = params.services ?? ["vat"];
143
+ const hmrcAccount = params.hmrcAccount ?? "live";
144
+ if (!Array.isArray(services) || services.length === 0 || !services.every((service) => HMRC_SERVICES.includes(service))) {
145
+ throw new Error(`request_hmrc_authorisation services must list one or more of ${HMRC_SERVICES.join(", ")}`);
146
+ }
147
+ if (!HMRC_ACCOUNTS.includes(hmrcAccount)) {
148
+ throw new Error(`request_hmrc_authorisation hmrcAccount must be one of ${HMRC_ACCOUNTS.join(", ")}`);
149
+ }
150
+ const granted = await callSubmitApi(session, "/api/v1/mcp/hmrc-grants", { method: "POST", body: { services, hmrcAccount } });
151
+ session.hmrcGrant = { grantId: granted.grantId, hmrcAccount: granted.hmrcAccount };
152
+ return { url: granted.url, expiresAt: granted.expiresAt, scope: granted.scope, hmrcAccount: granted.hmrcAccount };
153
+ }
154
+
155
+ export const HMRC_GRANT_HEADER = "x-mcp-hmrc-grant";
156
+
157
+ /**
158
+ * The session's HMRC grant for one tool call: the headers that name it to Submit's API, and the
159
+ * HMRC account it belongs to. Submit opens the grant's tokens itself; the token never reaches this
160
+ * process. Throws a message naming request_hmrc_authorisation when the session holds no grant, when
161
+ * the user has not finished the HMRC page, and when the call names the other HMRC account.
162
+ * @param {Object} session
163
+ * @param {string} toolName - named in the error messages
164
+ * @param {string} [hmrcAccount] - the account the call asks for; the grant's own when omitted
165
+ * @returns {Promise<{grantHeaders: Object, hmrcAccount: string}>}
166
+ */
167
+ export async function hmrcGrantFor(session, toolName, hmrcAccount) {
168
+ const grantId = session?.hmrcGrant?.grantId;
169
+ if (!grantId) throw new Error(`${toolName}: ${NO_GRANT_MESSAGE}`);
170
+ const grant = await callSubmitApi(session, `/api/v1/mcp/hmrc-grants/${encodeURIComponent(grantId)}`);
171
+ if (grant.status !== "granted") {
172
+ throw new Error(
173
+ `${toolName}: the user has not finished granting HMRC access yet. Ask them to complete the page at the ` +
174
+ "request_hmrc_authorisation link, then call this tool again.",
175
+ );
176
+ }
177
+ if (hmrcAccount && hmrcAccount !== grant.hmrcAccount) {
178
+ throw new Error(
179
+ `${toolName}: the session's HMRC authorisation is for the ${grant.hmrcAccount} account, not ${hmrcAccount}. ` +
180
+ `Call request_hmrc_authorisation with hmrcAccount ${hmrcAccount} first.`,
181
+ );
182
+ }
183
+ return { grantHeaders: { [HMRC_GRANT_HEADER]: grantId, hmrcAccount: grant.hmrcAccount }, hmrcAccount: grant.hmrcAccount };
184
+ }
185
+
114
186
  /**
115
187
  * list_vat_obligations: the open and fulfilled obligations for one VRN, or for one practice
116
188
  * client's VRN when clientId is given instead (hmrcVatObligationGet.js resolves it from the
117
- * client row; a client that is not this practice's own answers 403 client-not-found).
189
+ * client row; a client that is not this practice's own answers 403 client-not-found). The HMRC
190
+ * access token is the session's HMRC grant's.
118
191
  * @param {Object} session
119
192
  * @param {{vrn?: string, clientId?: string, from?: string, to?: string, status?: string,
120
- * hmrcAccessToken: string, hmrcAccount?: string, govTestScenario?: string}} params
193
+ * hmrcAccount?: string, govTestScenario?: string}} params
121
194
  */
122
195
  export async function listVatObligations(session, params = {}) {
123
- const { vrn, clientId, from, to, status, hmrcAccount, govTestScenario } = params;
196
+ const { vrn, clientId, from, to, status, govTestScenario } = params;
124
197
  if (!vrn && !clientId) {
125
198
  throw new Error("list_vat_obligations requires vrn, or clientId to resolve it from the client row");
126
199
  }
127
- const hmrcAccessToken = requireField("list_vat_obligations", params, "hmrcAccessToken");
200
+ const { grantHeaders } = await hmrcGrantFor(session, "list_vat_obligations", params.hmrcAccount);
128
201
 
129
202
  const query = new URLSearchParams();
130
203
  if (vrn) query.set("vrn", vrn);
@@ -134,10 +207,62 @@ export async function listVatObligations(session, params = {}) {
134
207
  if (status) query.set("status", status);
135
208
  if (govTestScenario) query.set("Gov-Test-Scenario", govTestScenario);
136
209
 
137
- const headers = { Authorization: `Bearer ${hmrcAccessToken}` };
138
- if (hmrcAccount) headers.hmrcAccount = hmrcAccount;
210
+ return callSubmitApi(session, `/api/v1/hmrc/vat/obligation?${query.toString()}`, { customAuthorizer: true, headers: grantHeaders });
211
+ }
212
+
213
+ // The VAT enquiry reads other than obligations: HMRC's liabilities, payments and penalties for one
214
+ // VRN over a date range, and one past return by its period key. They use the session's HMRC grant
215
+ // and the custom authoriser exactly as list_vat_obligations does.
216
+ async function vatEnquiry(session, toolName, route, params, extraQuery = {}) {
217
+ const { vrn, from, to, govTestScenario } = params;
218
+ if (!vrn) throw new Error(`${toolName} requires vrn`);
219
+ const { grantHeaders } = await hmrcGrantFor(session, toolName, params.hmrcAccount);
220
+ const query = new URLSearchParams({ vrn });
221
+ for (const [key, value] of Object.entries({ from, to, ...extraQuery })) {
222
+ if (value) query.set(key, value);
223
+ }
224
+ if (govTestScenario) query.set("Gov-Test-Scenario", govTestScenario);
225
+ return callSubmitApi(session, `${route}?${query.toString()}`, {
226
+ customAuthorizer: true,
227
+ headers: grantHeaders,
228
+ });
229
+ }
230
+
231
+ /**
232
+ * list_vat_liabilities: what HMRC says the business owes for VAT, by period.
233
+ * @param {Object} session
234
+ * @param {{vrn: string, from?: string, to?: string, hmrcAccount?: string, govTestScenario?: string}} params
235
+ */
236
+ export function listVatLiabilities(session, params = {}) {
237
+ return vatEnquiry(session, "list_vat_liabilities", "/api/v1/hmrc/vat/liability", params);
238
+ }
239
+
240
+ /**
241
+ * list_vat_payments: the VAT payments HMRC has received, by date.
242
+ * @param {Object} session
243
+ * @param {{vrn: string, from?: string, to?: string, hmrcAccount?: string, govTestScenario?: string}} params
244
+ */
245
+ export function listVatPayments(session, params = {}) {
246
+ return vatEnquiry(session, "list_vat_payments", "/api/v1/hmrc/vat/payment", params);
247
+ }
248
+
249
+ /**
250
+ * list_vat_penalties: the VAT penalties and late-submission points HMRC holds.
251
+ * @param {Object} session
252
+ * @param {{vrn: string, from?: string, to?: string, hmrcAccount?: string, govTestScenario?: string}} params
253
+ */
254
+ export function listVatPenalties(session, params = {}) {
255
+ return vatEnquiry(session, "list_vat_penalties", "/api/v1/hmrc/vat/penalty", params);
256
+ }
139
257
 
140
- return callSubmitApi(session, `/api/v1/hmrc/vat/obligation?${query.toString()}`, { customAuthorizer: true, headers });
258
+ /**
259
+ * get_vat_return: one past return as HMRC holds it, by its period key.
260
+ * @param {Object} session
261
+ * @param {{vrn: string, periodKey: string, hmrcAccount?: string, govTestScenario?: string}} params
262
+ */
263
+ export async function getVatReturn(session, params = {}) {
264
+ const periodKey = requireField("get_vat_return", params, "periodKey");
265
+ return vatEnquiry(session, "get_vat_return", "/api/v1/hmrc/vat/return", params, { periodKey });
141
266
  }
142
267
 
143
268
  const VAT_RETURN_BOX_FIELDS = [
@@ -158,10 +283,11 @@ const VAT_RETURN_BOX_FIELDS = [
158
283
  * client-not-authorised). Returns {receipt, hmrcResponse, hmrcResponseBody, periodKey, receiptId}
159
284
  * — the filed receipt sits under `receipt` (also duplicated at `hmrcResponseBody`), `periodKey` is
160
285
  * the obligation period this route resolved from periodStart/periodEnd, and `receiptId` is the
161
- * receipt's file name without its .json suffix (get_vat_receipt takes `${receiptId}.json`).
286
+ * receipt's file name without its .json suffix (get_vat_receipt takes `${receiptId}.json`). The
287
+ * HMRC access token is the session's HMRC grant's.
162
288
  * @param {Object} session
163
289
  * @param {{vatNumber?: string, clientId?: string, periodStart: string, periodEnd: string,
164
- * hmrcAccessToken: string, vatDueSales: number, vatDueAcquisitions: number,
290
+ * vatDueSales: number, vatDueAcquisitions: number,
165
291
  * vatReclaimedCurrPeriod: number, totalValueSalesExVAT: number, totalValuePurchasesExVAT: number,
166
292
  * totalValueGoodsSuppliedExVAT: number, totalAcquisitionsExVAT: number,
167
293
  * hmrcAccount?: string, govTestScenario?: string, runFraudPreventionHeaderValidation?: boolean,
@@ -174,15 +300,14 @@ export async function submitVatReturn(session, params = {}) {
174
300
  }
175
301
  const periodStart = requireField("submit_vat_return", params, "periodStart");
176
302
  const periodEnd = requireField("submit_vat_return", params, "periodEnd");
177
- const hmrcAccessToken = requireField("submit_vat_return", params, "hmrcAccessToken");
178
303
  const boxes = {};
179
304
  for (const field of VAT_RETURN_BOX_FIELDS) {
180
305
  boxes[field] = requireField("submit_vat_return", params, field);
181
306
  }
182
- const { hmrcAccount, govTestScenario, runFraudPreventionHeaderValidation, allowSyntheticObligations } = params;
307
+ const { govTestScenario, runFraudPreventionHeaderValidation, allowSyntheticObligations } = params;
308
+ const { grantHeaders } = await hmrcGrantFor(session, "submit_vat_return", params.hmrcAccount);
183
309
 
184
- const headers = {};
185
- if (hmrcAccount) headers.hmrcAccount = hmrcAccount;
310
+ const headers = { ...grantHeaders };
186
311
  if (govTestScenario) headers["Gov-Test-Scenario"] = govTestScenario;
187
312
 
188
313
  return callSubmitApi(session, "/api/v1/hmrc/vat/return", {
@@ -194,7 +319,6 @@ export async function submitVatReturn(session, params = {}) {
194
319
  ...(clientId ? { clientId } : {}),
195
320
  periodStart,
196
321
  periodEnd,
197
- accessToken: hmrcAccessToken,
198
322
  ...boxes,
199
323
  ...(runFraudPreventionHeaderValidation !== undefined ? { runFraudPreventionHeaderValidation } : {}),
200
324
  ...(allowSyntheticObligations !== undefined ? { allowSyntheticObligations } : {}),
@@ -217,12 +341,27 @@ export async function getVatReceipt(session, params = {}) {
217
341
  return callSubmitApi(session, `/api/v1/hmrc/receipt/${encodeURIComponent(name)}${query}`);
218
342
  }
219
343
 
344
+ /**
345
+ * list_vat_receipts: the stored receipts the account page lists, newest first as the route
346
+ * answers them, each with the name get_vat_receipt takes. clientId narrows the list to one of the
347
+ * practice's clients (hmrcReceiptGet.js answers 403 client-not-found for a client that is not this
348
+ * practice's own).
349
+ * @param {Object} session
350
+ * @param {{clientId?: string}} params
351
+ * @returns {Promise<{receipts: Object[]}>}
352
+ */
353
+ export async function listVatReceipts(session, params = {}) {
354
+ const { clientId } = params;
355
+ const query = clientId ? `?clientId=${encodeURIComponent(clientId)}` : "";
356
+ return callSubmitApi(session, `/api/v1/hmrc/receipt${query}`);
357
+ }
358
+
220
359
  const ACCOUNTS_STATEMENT_FIELDS = ["section477Exemption", "membersNotRequiredAudit", "directorsResponsibilities", "microEntityProvisions"];
221
360
 
222
361
  /**
223
- * The body both companies-house/accounts routes take, common to the preview and the submit
362
+ * The body both companies-house/accounts routes take, common to the render and the submit
224
363
  * calls; the submit call adds companyAuthCode on top. Only the submit route resolves companyNumber
225
- * from a practice client's row (companiesHouseAccountsPost.js); the preview route never reads
364
+ * from a practice client's row (companiesHouseAccountsPost.js); the render route never reads
226
365
  * clientId at all, so allowClientId stays false there and companyNumber stays required.
227
366
  */
228
367
  function accountsFilingBody(toolName, params, { allowClientId = false } = {}) {
@@ -257,74 +396,136 @@ function accountsFilingBody(toolName, params, { allowClientId = false } = {}) {
257
396
  }
258
397
 
259
398
  /**
260
- * preview_micro_entity_accounts: the rendered iXBRL for confirmed figures, without reaching the
261
- * Companies House XML Gateway. The preview route never resolves a company from a practice
399
+ * render_micro_entity_accounts_sandbox: the rendered iXBRL for confirmed figures, without reaching the
400
+ * Companies House XML Gateway. The render route never resolves a company from a practice
262
401
  * client's row, so this tool takes companyNumber only, not clientId.
263
402
  * @param {Object} session
264
403
  * @param {{companyNumber: string, companyName: string, periodStart: string, periodEnd: string,
265
404
  * balanceSheet: {currentYear: Object, priorYear: Object}, averageEmployees: number,
266
405
  * director: {name: string, dateApproved: string}, statementsAccepted: Object}} params
267
406
  */
268
- export async function previewMicroEntityAccounts(session, params = {}) {
269
- const body = accountsFilingBody("preview_micro_entity_accounts", params);
270
- return callSubmitApi(session, "/api/v1/companies-house/accounts/preview", { method: "POST", body });
407
+ export async function renderMicroEntityAccounts(session, params = {}) {
408
+ const body = accountsFilingBody("render_micro_entity_accounts_sandbox", params);
409
+ return callSubmitApi(session, "/api/v1/companies-house/accounts/render", { method: "POST", body });
271
410
  }
272
411
 
273
412
  /**
274
- * submit_micro_entity_accounts: files confirmed figures with the company authentication code
275
- * (6 to 8 characters — Companies House's own format, checked by the route, not by this tool), for
413
+ * submit_micro_entity_accounts_sandbox: files confirmed figures with the company authentication code
414
+ * the user typed on the page request_companies_house_codes linked to (the call carries the entry's
415
+ * id, never the code; the route takes the entry once), for
276
416
  * companyNumber or, when clientId is given instead, for that practice client's own company number
277
417
  * (companiesHouseAccountsPost.js resolves it from the client row; a client that is not this
278
418
  * practice's own, or not yet authorised for Companies House filing, answers 403). Returns
279
- * {submissionNumber, gatewayTimestamp, pollInterval}; poll_accounts_submission takes the
419
+ * {submissionNumber, gatewayTimestamp, pollInterval}; poll_submission with kind accounts takes the
280
420
  * submissionNumber to reach the filing's outcome. This route answers synchronously (200/201),
281
421
  * unlike list_vat_obligations and submit_vat_return.
282
422
  * @param {Object} session
283
- * @param {Object} params - as previewMicroEntityAccounts, but companyNumber is optional when
284
- * clientId is given, plus companyAuthCode
423
+ * @param {Object} params - as renderMicroEntityAccounts, but companyNumber is optional when
424
+ * clientId is given, plus codesEntryId
285
425
  */
286
426
  export async function submitMicroEntityAccounts(session, params = {}) {
287
- const companyAuthCode = requireField("submit_micro_entity_accounts", params, "companyAuthCode");
288
- const body = accountsFilingBody("submit_micro_entity_accounts", params, { allowClientId: true });
289
- return callSubmitApi(session, "/api/v1/companies-house/accounts", { method: "POST", body: { ...body, companyAuthCode } });
427
+ const codesEntryId = requireField("submit_micro_entity_accounts_sandbox", params, "codesEntryId");
428
+ const body = accountsFilingBody("submit_micro_entity_accounts_sandbox", params, { allowClientId: true });
429
+ return callSubmitApi(session, "/api/v1/companies-house/accounts", { method: "POST", body: { ...body, codesEntryId } });
430
+ }
431
+
432
+ const SMALL_COMPANY_STATEMENT_FIELDS = [
433
+ "section477Exemption",
434
+ "membersNotRequiredAudit",
435
+ "directorsResponsibilities",
436
+ "smallCompaniesRegime",
437
+ ];
438
+
439
+ /**
440
+ * The body both small-company accounts calls take. The routes are the micro-entity ones
441
+ * (companies-house/accounts and companies-house/accounts/render); a smallCompany section in the
442
+ * body selects the FRS 102 section 1A regime, so the figures live there and not in a top-level
443
+ * balanceSheet.
444
+ */
445
+ function smallCompanyFilingBody(toolName, params, { allowClientId = false } = {}) {
446
+ const clientId = allowClientId ? params?.clientId : undefined;
447
+ if (!params?.companyNumber && !clientId) {
448
+ requireField(toolName, params, "companyNumber");
449
+ }
450
+ const companyName = requireField(toolName, params, "companyName");
451
+ const periodStart = requireField(toolName, params, "periodStart");
452
+ const periodEnd = requireField(toolName, params, "periodEnd");
453
+ const averageEmployees = requireField(toolName, params, "averageEmployees");
454
+ const director = requireField(toolName, params, "director");
455
+ const statementsAccepted = requireField(toolName, params, "statementsAccepted");
456
+ const smallCompany = requireField(toolName, params, "smallCompany");
457
+ if (!smallCompany.balanceSheet?.currentYear) throw new Error(`${toolName} requires smallCompany.balanceSheet.currentYear`);
458
+ if (!smallCompany.profitAndLoss?.currentYear) throw new Error(`${toolName} requires smallCompany.profitAndLoss.currentYear`);
459
+ for (const field of SMALL_COMPANY_STATEMENT_FIELDS) {
460
+ if (statementsAccepted?.[field] !== true) throw new Error(`${toolName} requires statementsAccepted.${field} to be accepted`);
461
+ }
462
+ return {
463
+ ...(params.companyNumber ? { companyNumber: params.companyNumber } : {}),
464
+ ...(clientId ? { clientId } : {}),
465
+ companyName,
466
+ periodStart,
467
+ periodEnd,
468
+ averageEmployees: Number(averageEmployees),
469
+ director,
470
+ statementsAccepted,
471
+ smallCompany,
472
+ };
290
473
  }
291
474
 
292
475
  /**
293
- * poll_accounts_submission: the filing's outcome — {submissionNumber, statusCode, companyNumber,
294
- * rejections}, where statusCode is "PENDING" while Companies House has not answered yet, "ACCEPT"
295
- * once filed (with a receiptId added), or "REJECT" with rejections carrying the reasons.
476
+ * render_small_company_accounts_sandbox: the rendered FRS 102 section 1A iXBRL for confirmed
477
+ * figures (derive_small_company_accounts' answer), without reaching the Companies House XML
478
+ * Gateway. Like the micro-entity render, it takes companyNumber only, not clientId.
296
479
  * @param {Object} session
297
- * @param {{submissionNumber: string}} params
480
+ * @param {Object} params - companyNumber, companyName, periodStart, periodEnd, averageEmployees,
481
+ * director, statementsAccepted and the smallCompany section
298
482
  */
299
- export async function pollAccountsSubmission(session, params = {}) {
300
- const submissionNumber = requireField("poll_accounts_submission", params, "submissionNumber");
301
- return callSubmitApi(session, `/api/v1/companies-house/accounts/${encodeURIComponent(submissionNumber)}`);
483
+ export async function renderSmallCompanyAccounts(session, params = {}) {
484
+ const body = smallCompanyFilingBody("render_small_company_accounts_sandbox", params);
485
+ return callSubmitApi(session, "/api/v1/companies-house/accounts/render", { method: "POST", body });
302
486
  }
303
487
 
304
488
  /**
305
- * get_confirmation_statement_data: the register data a confirmation statement form is built
489
+ * submit_small_company_accounts_sandbox: files confirmed small-company figures with the company
490
+ * authentication code the user typed on the page request_companies_house_codes linked to (the
491
+ * call carries the entry's id, never the code), for companyNumber or, when clientId is given
492
+ * instead, for that practice client's own company number. Returns
493
+ * {submissionNumber, gatewayTimestamp, pollInterval}; poll_submission with kind accounts takes
494
+ * the submissionNumber to reach the filing's outcome.
495
+ * @param {Object} session
496
+ * @param {Object} params - as renderSmallCompanyAccounts, but companyNumber is optional when
497
+ * clientId is given, plus codesEntryId
498
+ */
499
+ export async function submitSmallCompanyAccounts(session, params = {}) {
500
+ const codesEntryId = requireField("submit_small_company_accounts_sandbox", params, "codesEntryId");
501
+ const body = smallCompanyFilingBody("submit_small_company_accounts_sandbox", params, { allowClientId: true });
502
+ return callSubmitApi(session, "/api/v1/companies-house/accounts", { method: "POST", body: { ...body, codesEntryId } });
503
+ }
504
+
505
+ /**
506
+ * get_confirmation_statement_data_sandbox: the register data a confirmation statement form is built
306
507
  * from — MadeUpDate, NextDueDate, SIC codes, RegisteredEmailAddress, officers, PSCs,
307
508
  * StatementOfCapital, Shareholdings, TradingOnMarket, DTR5Applies, the PSC exemption flags, and
308
509
  * paymentPeriods/paymentPeriodPaid — over the deployed API. Confirmation statement routes never
309
510
  * resolve a company from a practice client's row, so this tool takes companyNumber only, not
310
511
  * clientId. Takes the company authentication code on this one call only; it is not stored.
311
512
  * @param {Object} session
312
- * @param {{companyNumber: string, companyAuthCode: string, madeUpDate: string, companyType?: string}} params
513
+ * @param {{companyNumber: string, codesEntryId: string, madeUpDate: string, companyType?: string}} params
313
514
  */
314
515
  export async function getConfirmationStatementData(session, params = {}) {
315
- const companyNumber = requireField("get_confirmation_statement_data", params, "companyNumber");
316
- const companyAuthCode = requireField("get_confirmation_statement_data", params, "companyAuthCode");
317
- const madeUpDate = requireField("get_confirmation_statement_data", params, "madeUpDate");
516
+ const companyNumber = requireField("get_confirmation_statement_data_sandbox", params, "companyNumber");
517
+ const codesEntryId = requireField("get_confirmation_statement_data_sandbox", params, "codesEntryId");
518
+ const madeUpDate = requireField("get_confirmation_statement_data_sandbox", params, "madeUpDate");
318
519
  const { companyType } = params;
319
520
 
320
521
  return callSubmitApi(session, `/api/v1/companies-house/company/${encodeURIComponent(companyNumber)}/filing-data`, {
321
522
  method: "POST",
322
- body: { companyAuthCode, madeUpDate, ...(companyType !== undefined ? { companyType } : {}) },
523
+ body: { codesEntryId, madeUpDate, ...(companyType !== undefined ? { companyType } : {}) },
323
524
  });
324
525
  }
325
526
 
326
527
  /**
327
- * The body both companies-house/confirmation-statement routes take, common to the preview and the
528
+ * The body both companies-house/confirmation-statement routes take, common to the render and the
328
529
  * submit calls; the submit call adds companyAuthCode on top. Confirmation statement routes never
329
530
  * resolve a company from a practice client's row, unlike the accounts routes, so companyNumber is
330
531
  * always required.
@@ -360,46 +561,100 @@ function confirmationStatementFilingBody(toolName, params) {
360
561
  };
361
562
  }
362
563
 
564
+ const RENDER_PLACEHOLDER_PERSONAL_CODE = "AAAAAA00000";
565
+
363
566
  /**
364
- * preview_confirmation_statement: the rendered ConfirmationAndVerificationStatement body for
567
+ * render_confirmation_statement_sandbox: the rendered ConfirmationAndVerificationStatement body for
365
568
  * confirmed answers, without reaching the Companies House XML Gateway. Every director's personal
366
569
  * code is masked in the rendered body before it leaves the route.
367
570
  * @param {Object} session
368
571
  * @param {{companyNumber: string, companyName: string, dateSigned: string, reviewDate: string,
369
572
  * sicCodes?: string[], statementOfCapital?: Object, shareholdings?: Object[],
370
573
  * registeredEmailAddress?: string, lawfulPurposeStatementAccepted: true, stateConfirmationAccepted: true,
371
- * directors: {forename: string, surname: string, dob: string, personalCode: string}[]}} params
574
+ * directors: {forename: string, surname: string, dob: string}[]}} params
372
575
  */
373
- export async function previewConfirmationStatement(session, params = {}) {
374
- const body = confirmationStatementFilingBody("preview_confirmation_statement", params);
375
- return callSubmitApi(session, "/api/v1/companies-house/confirmation-statement/preview", { method: "POST", body });
576
+ export async function renderConfirmationStatement(session, params = {}) {
577
+ const body = confirmationStatementFilingBody("render_confirmation_statement_sandbox", params);
578
+ // The route validates a personal code on every director and masks it in the rendered body, so a
579
+ // preview sends a code-shaped placeholder and the user never types a real one into the chat.
580
+ body.directors = body.directors.map((director) => ({ ...director, personalCode: RENDER_PLACEHOLDER_PERSONAL_CODE }));
581
+ return callSubmitApi(session, "/api/v1/companies-house/confirmation-statement/render", { method: "POST", body });
376
582
  }
377
583
 
378
584
  /**
379
- * submit_confirmation_statement: files confirmed answers with the company authentication code
380
- * (6 to 8 characters — Companies House's own format, checked by the route, not by this tool) and
381
- * every director's personal code (11 characters each, carried on the directors array). Returns
382
- * {submissionNumber, gatewayTimestamp, pollInterval}; poll_confirmation_statement takes the
585
+ * submit_confirmation_statement_sandbox: files confirmed answers with the company authentication code
586
+ * and every director's personal code, which the user typed on the page request_companies_house_codes
587
+ * linked to; the directors array must list the directors that link was minted for, in the same
588
+ * order, and the route puts each personal code on its director. Returns
589
+ * {submissionNumber, gatewayTimestamp, pollInterval}; poll_submission with kind confirmation-statement takes the
383
590
  * submissionNumber to reach the filing's outcome. This route answers synchronously (200/201),
384
591
  * unlike list_vat_obligations and submit_vat_return.
385
592
  * @param {Object} session
386
- * @param {Object} params - as previewConfirmationStatement, plus companyAuthCode
593
+ * @param {Object} params - as renderConfirmationStatement without the personal codes, plus codesEntryId
387
594
  */
388
595
  export async function submitConfirmationStatement(session, params = {}) {
389
- const companyAuthCode = requireField("submit_confirmation_statement", params, "companyAuthCode");
390
- const body = confirmationStatementFilingBody("submit_confirmation_statement", params);
391
- return callSubmitApi(session, "/api/v1/companies-house/confirmation-statement", { method: "POST", body: { ...body, companyAuthCode } });
596
+ const codesEntryId = requireField("submit_confirmation_statement_sandbox", params, "codesEntryId");
597
+ const body = confirmationStatementFilingBody("submit_confirmation_statement_sandbox", params);
598
+ return callSubmitApi(session, "/api/v1/companies-house/confirmation-statement", { method: "POST", body: { ...body, codesEntryId } });
392
599
  }
393
600
 
601
+ const SUBMISSION_ROUTES = {
602
+ "accounts": "/api/v1/companies-house/accounts",
603
+ "confirmation-statement": "/api/v1/companies-house/confirmation-statement",
604
+ };
605
+
606
+ export const SUBMISSION_KINDS = Object.keys(SUBMISSION_ROUTES);
607
+
608
+ /**
609
+ * poll_submission: the outcome of a Companies House filing of one kind (micro-entity or small-company
610
+ * accounts, or a confirmation statement) — {submissionNumber, statusCode, companyNumber, rejections}, where
611
+ * statusCode is "PENDING" while Companies House has not answered yet, "ACCEPT" once filed (with a
612
+ * receiptId added), or "REJECT" with rejections carrying the reasons.
613
+ * @param {Object} session
614
+ * @param {{kind: "accounts"|"confirmation-statement", submissionNumber: string}} params
615
+ */
616
+ export async function pollSubmission(session, params = {}) {
617
+ const kind = requireField("poll_submission", params, "kind");
618
+ const route = SUBMISSION_ROUTES[kind];
619
+ if (!route) throw new Error(`poll_submission kind must be one of ${SUBMISSION_KINDS.join(", ")}`);
620
+ const submissionNumber = requireField("poll_submission", params, "submissionNumber");
621
+ return callSubmitApi(session, `${route}/${encodeURIComponent(submissionNumber)}`);
622
+ }
623
+
624
+ const CODES_KINDS = ["accounts", "confirmation-statement", "confirmation-statement-data"];
625
+
394
626
  /**
395
- * poll_confirmation_statement: the filing's outcome — {submissionNumber, statusCode,
396
- * companyNumber, rejections}, where statusCode is "PENDING" while Companies House has not
397
- * answered yet, "ACCEPT" once filed (with a receiptId added), or "REJECT" with rejections
398
- * carrying the reasons.
627
+ * request_companies_house_codes: mints a codes entry and answers the link where the user types the
628
+ * Companies House codes. The entry expires in ten minutes. A single entry is used up by the first
629
+ * filing call that names it. With clientIds the entry is a batch entry: the page asks for one
630
+ * company authentication code per practice client, and each filing call takes its own client's
631
+ * codes, so run_for_clients can pass the one entryId. Answers {entryId, url, expiresAt}; the
632
+ * filing tool takes entryId as codesEntryId.
399
633
  * @param {Object} session
400
- * @param {{submissionNumber: string}} params
634
+ * @param {{kind: "accounts"|"confirmation-statement"|"confirmation-statement-data", companyNumber?: string,
635
+ * directors?: {forename: string, surname: string}[], clientIds?: string[]}} params - directors are the
636
+ * confirmation statement's directors, in the order the filing lists them; companyNumber is required
637
+ * unless clientIds is given
401
638
  */
402
- export async function pollConfirmationStatement(session, params = {}) {
403
- const submissionNumber = requireField("poll_confirmation_statement", params, "submissionNumber");
404
- return callSubmitApi(session, `/api/v1/companies-house/confirmation-statement/${encodeURIComponent(submissionNumber)}`);
639
+ export async function requestCompaniesHouseCodes(session, params = {}) {
640
+ const kind = requireField("request_companies_house_codes", params, "kind");
641
+ if (!CODES_KINDS.includes(kind)) throw new Error(`request_companies_house_codes kind must be one of ${CODES_KINDS.join(", ")}`);
642
+ if (params.clientIds !== undefined) {
643
+ if (!Array.isArray(params.clientIds) || params.clientIds.length === 0) {
644
+ throw new Error("request_companies_house_codes clientIds must list at least one client id");
645
+ }
646
+ const { clients: practiceClients } = await callSubmitApi(session, "/api/v1/practice/clients");
647
+ const clients = params.clientIds.map((clientId) => {
648
+ const found = practiceClients.find((client) => client.clientId === clientId);
649
+ if (!found) throw new Error(`request_companies_house_codes clientIds names ${clientId}, which is not in the practice's client list`);
650
+ return { clientId };
651
+ });
652
+ return callSubmitApi(session, "/api/v1/mcp/codes-entries", { method: "POST", body: { kind, clients } });
653
+ }
654
+ const companyNumber = requireField("request_companies_house_codes", params, "companyNumber");
655
+ const directors = kind === "confirmation-statement" ? requireField("request_companies_house_codes", params, "directors") : undefined;
656
+ return callSubmitApi(session, "/api/v1/mcp/codes-entries", {
657
+ method: "POST",
658
+ body: { kind, companyNumber, ...(directors ? { directors } : {}) },
659
+ });
405
660
  }
package/lib/vat-tools.js CHANGED
@@ -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-05 Derive VAT figures via MCP tools
5
+ // - **Use when:** a VAT return's nine HMRC boxes must be computed from a loaded book before filing or review.
6
+ // - **Does:** deriveVatReturn in mcp/lib/vat-tools.js reads the engine's Vatreturns.xlsx Vatinterface sheet for one obligation quarter. It cross-checks the sheet totals against the sales and purchases journal lines and throws on disagreement. It returns every line behind boxes 1, 4, 6 and 7.
7
+ // - **Run:** no command; see Does and Entry
8
+ // - **Entry:** `mcp/lib/vat-tools.js:deriveVatReturn`; `mcp/lib/vat-tools.js:interfaceRows`
9
+ // - **Files:** mcp/lib/vat-tools.js, mcp/test/vat-tools.test.js
10
+ // - **Keywords:** derive_vat_return, vat boxes, vatinterface, hmrc vat, vat return, reconcile, mtd vat
11
+ // - **Related:** MCP-03, MCP-07
12
+ // @end-capability
13
+
4
14
  // vat-tools.js -- derive_vat_return: the nine VAT boxes for one obligation
5
15
  // period from the session's loaded book. The derivation is the diya-gl
6
16
  // package's own; this module adds only the session's "no book loaded" check.