@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.
- package/README.md +30 -9
- package/lib/accounts-tools.js +46 -2
- package/lib/auth.js +11 -1
- package/lib/batch-tools.js +19 -2
- package/lib/book-tools.js +47 -4
- package/lib/client-headers.js +263 -0
- package/lib/finance/bank-lines.js +10 -0
- package/lib/finance/book-from-workbook.js +10 -0
- package/lib/finance/mail-invoices.js +45 -7
- package/lib/finance/paypal-statement-lines.js +11 -1
- package/lib/finance/stripe-lines.js +20 -0
- package/lib/harness.js +58 -0
- package/lib/hosted-tools.js +82 -12
- package/lib/itsa-tools.js +173 -1
- package/lib/practice-tools.js +22 -12
- package/lib/server.js +348 -45
- package/lib/submit-tools.js +326 -71
- package/lib/vat-tools.js +10 -0
- package/lib/vendored/app/services/ct600Figures.js +1175 -0
- package/lib/vendored/app/services/microEntityAccounts.js +47 -197
- package/lib/vendored/app/services/microEntityAccountsFromResults.js +264 -0
- package/lib/vendored/app/services/smallCompanyAccounts.js +7 -240
- package/lib/vendored/app/services/smallCompanyAccountsFromResults.js +333 -0
- package/package.json +12 -7
- package/lib/vendored/app/lib/xmlDom.js +0 -73
- package/lib/vendored/app/services/accountsIxbrlCommon.js +0 -414
- package/lib/vendored/app/services/smallCompanyAccountsIxbrl.js +0 -426
package/README.md
CHANGED
|
@@ -1,9 +1,19 @@
|
|
|
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-14 Document the submission MCP's plan and tool reference
|
|
5
|
+
- **Use when:** starting work on the submission MCP: what is built, planned, and how to run it.
|
|
6
|
+
- **Does:** ../private.diyaccounting.co.uk/engineering/submit/archive/PLAN_SUBMISSION_MCP.md is the plan of record for the submission MCP: milestones, book-to-filing field mappings and open rows. mcp/README.md is the package's short reference: how to run it, test it, and its tools at time of writing.
|
|
7
|
+
- **Run:** `npm --prefix mcp install`; `npm --prefix mcp test`
|
|
8
|
+
- **Entry:** `../private.diyaccounting.co.uk/engineering/submit/archive/PLAN_SUBMISSION_MCP.md`; `mcp/README.md`
|
|
9
|
+
- **Files:** ../private.diyaccounting.co.uk/engineering/submit/archive/PLAN_SUBMISSION_MCP.md, mcp/README.md
|
|
10
|
+
- **Keywords:** plan submission mcp, mcp readme, milestones, field mappings, plan of record
|
|
11
|
+
- **Related:** MCP-01
|
|
12
|
+
@end-capability -->
|
|
13
|
+
|
|
4
14
|
# @diy-accounting-uk/diya-submit
|
|
5
15
|
|
|
6
|
-
The submission MCP for DIY Accounting Submit (
|
|
16
|
+
The submission MCP for DIY Accounting Submit (`../private.diyaccounting.co.uk/engineering/submit/archive/PLAN_SUBMISSION_MCP.md`). It opens a customer's
|
|
7
17
|
books with the published `@diy-accounting-uk/diya-gl` engine, derives the figures a filing
|
|
8
18
|
needs, and drives the VAT return and the micro-entity accounts through this service's
|
|
9
19
|
endpoints. This package is the skeleton: the server, the stdio transport and the two book
|
|
@@ -33,8 +43,15 @@ claude mcp add --transport http diya-submit https://submit.diyaccounting.co.uk/m
|
|
|
33
43
|
The client finds the sign-in through `/.well-known/oauth-protected-resource/mcp`, registers itself, and
|
|
34
44
|
the user signs in with their Submit account. The ci form of the URL is
|
|
35
45
|
`https://ci-submit.diyaccounting.co.uk/mcp`. The hosted tool set is `HOSTED_TOOL_NAMES` in
|
|
36
|
-
`lib/hosted-tools.js`: `open_book` reads the DIYA cloud only
|
|
37
|
-
tools are not registered.
|
|
46
|
+
`lib/hosted-tools.js`: `open_book` reads the DIYA cloud only. The sign-in pair, the filesystem tools,
|
|
47
|
+
the practice tools that still take an HMRC token, and `run_for_clients` are not registered.
|
|
48
|
+
|
|
49
|
+
## HMRC fraud prevention data
|
|
50
|
+
|
|
51
|
+
HMRC requires data about the device behind each request. The two surfaces send different data.
|
|
52
|
+
|
|
53
|
+
- The stdio server is `DESKTOP_APP_VIA_SERVER`. On each call to an HMRC route it reads a device id (kept in `~/.config/diya-submit/device-id`), the local IP addresses, the MAC addresses, the operating system user, the timezone, the operating system and device model, and the screens. It has no window, so it sends no `Gov-Client-Window-Size`.
|
|
54
|
+
- The hosted endpoint is `OTHER_VIA_SERVER`. It passes the public address of the caller at `/mcp`, signed so that Submit can trust it. An AI client gives no device data.
|
|
38
55
|
|
|
39
56
|
## Tools
|
|
40
57
|
|
|
@@ -44,12 +61,16 @@ tools are not registered.
|
|
|
44
61
|
| `save_book` | Writes the session's book to a path as `diya-gl-dir`, `diya-gl-zip`, `json`, `xlsx` or `zip`. The last two compose the product's workbook from the site's templates. |
|
|
45
62
|
| `derive_itsa_quarterly_update` | One period of HMRC's Self Employment Business API from a self-employed book: the period's own figures in a tax year filed as dated period summaries, the running total from 6 April in a year filed as cumulative period summaries (2025-26 on). `periodEndDate` picks the period; `quarterlyPeriodType` is `standard` or `calendar`. A field the book cannot source is omitted, never sent as zero. |
|
|
46
63
|
| `derive_itsa_annual_submission` | The year's allowances and adjustments for the annual submission, restricted to the fields HMRC accepts for that tax year (`sa103-mtd-mapping.json`'s `api.years`). With `path`, also written as the JSON file the site's annual submission page imports. |
|
|
47
|
-
| `
|
|
48
|
-
| `
|
|
64
|
+
| `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
|
+
| `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
|
+
| `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`. |
|
|
49
67
|
| `get_vat_receipt` | A stored receipt by `name` (`<receiptId>.json`); optional `clientId`. |
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
| `
|
|
68
|
+
| `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
|
+
| `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
|
+
| `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. |
|
|
71
|
+
| `submit_micro_entity_accounts_sandbox` | Files the same figures with the codes the user typed on that link, named by `codesEntryId`; answers `submissionNumber`. |
|
|
72
|
+
| `submit_small_company_accounts_sandbox` | Files the small-company figures with the codes named by `codesEntryId`, for `companyNumber` or `clientId`; answers `submissionNumber`. Poll it with `poll_submission` kind `accounts`. |
|
|
73
|
+
| `poll_submission` | The outcome of a Companies House filing, `kind` `accounts` or `confirmation-statement`, for a `submissionNumber`: `PENDING`, `ACCEPT` (with `receiptId`) or `REJECT` (with `rejections`). |
|
|
53
74
|
|
|
54
75
|
The filing tools call the deployed REST API at `DIYA_SUBMIT_BASE_URL` with the MCP's own sign-in bearer (`sign_in`), and poll a 202 answer to its terminal status. They validate required inputs before any request.
|
|
55
76
|
|
|
@@ -63,7 +84,7 @@ npm --prefix mcp test
|
|
|
63
84
|
npm --prefix mcp run test:system
|
|
64
85
|
```
|
|
65
86
|
|
|
66
|
-
`test:system` starts `npm run start:simulator` from the repository root, grants a bundle, then runs `list_vat_obligations`, `submit_vat_return` and `get_vat_receipt` against it, using whichever open obligation the simulator answers.
|
|
87
|
+
`test:system` starts `npm run start:simulator` from the repository root, grants a bundle, starts an HMRC grant with `request_hmrc_authorisation` and completes it as the callback page would, then runs `list_vat_obligations`, `submit_vat_return` and `get_vat_receipt` against it, using whichever open obligation the simulator answers. `npm run test:mcpHmrcGrantBehaviour-simulator` (from the repository root) walks the same grant through HMRC's consent pages in a browser. The design is in `../../private.diyaccounting.co.uk/engineering/submit/archive/PLAN_MCP.md`.
|
|
67
88
|
|
|
68
89
|
The tests open the BrickWork Pro Ltd and Precision Code Ltd example books under `test/fixtures/`
|
|
69
90
|
(copies of the spreadsheets repository's `examples/`) and round-trip each through the three
|
package/lib/accounts-tools.js
CHANGED
|
@@ -5,6 +5,17 @@
|
|
|
5
5
|
// balance-sheet lines the accounts filing takes. The derivation lives in
|
|
6
6
|
// app/services/microEntityAccounts.js, shared with the nightly company
|
|
7
7
|
// book pull; this file re-exports it for the MCP tool registration.
|
|
8
|
+
// derive_company_tax_return: the Company Tax Return figures from the loaded
|
|
9
|
+
// Company book, the file the web "Fill from your books" card reads.
|
|
10
|
+
|
|
11
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { basename, dirname, resolve as resolvePath } from "node:path";
|
|
13
|
+
|
|
14
|
+
import { calculatedResultsFor } from "@diy-accounting-uk/diya-gl/dist/app/bin/export.js";
|
|
15
|
+
import { packageVersion } from "@diy-accounting-uk/diya-gl/dist/app/lib/package-version.js";
|
|
16
|
+
import { loadTaxDataForBook } from "@diy-accounting-uk/diya-gl/dist/app/lib/product-workbook.js";
|
|
17
|
+
|
|
18
|
+
import { ct600FiguresFromResults, smallCompanyProfitAndLossFromPublishedAccount } from "./vendored/app/services/ct600Figures.js";
|
|
8
19
|
|
|
9
20
|
export {
|
|
10
21
|
BALANCE_SHEET_LINES,
|
|
@@ -12,7 +23,40 @@ export {
|
|
|
12
23
|
linesFromOpeningBalance,
|
|
13
24
|
roundForFiling,
|
|
14
25
|
profitAndLossFromPublishedAccount,
|
|
15
|
-
|
|
16
|
-
|
|
26
|
+
} from "./vendored/app/services/microEntityAccountsFromResults.js";
|
|
27
|
+
|
|
28
|
+
export { deriveMicroEntityAccounts } from "./vendored/app/services/microEntityAccounts.js";
|
|
17
29
|
|
|
18
30
|
export { deriveSmallCompanyAccounts } from "./vendored/app/services/smallCompanyAccounts.js";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* derive_company_tax_return: the figures the Company Tax Return form takes, from the session's
|
|
34
|
+
* loaded Company book, wrapped as the file the web card's Company Tax Return kind reads:
|
|
35
|
+
* { kind: "ct600", sourceFileName, packageVersion, period, figures }. The profit and loss account
|
|
36
|
+
* is the book's published one; the balance sheet and the rest of the accounts stay with the form.
|
|
37
|
+
* With a path, the answer is also written there as JSON.
|
|
38
|
+
* @param {Object} session
|
|
39
|
+
* @param {{path?: string}} params
|
|
40
|
+
*/
|
|
41
|
+
export async function deriveCompanyTaxReturn(session, { path } = {}) {
|
|
42
|
+
if (!session.book || !session.lines) throw new Error("No book is loaded. Call open_book first.");
|
|
43
|
+
const { book, lines } = session;
|
|
44
|
+
const taxData = await loadTaxDataForBook(book);
|
|
45
|
+
const results = calculatedResultsFor(book, lines, taxData);
|
|
46
|
+
const profitAndLoss = { currentYear: smallCompanyProfitAndLossFromPublishedAccount(results["PubP&L"]) };
|
|
47
|
+
const figures = ct600FiguresFromResults(results, { profitAndLoss });
|
|
48
|
+
const answer = {
|
|
49
|
+
kind: "ct600",
|
|
50
|
+
sourceFileName: session.sourcePath ? basename(session.sourcePath) : book.entityInformation?.organizationDescription || "book",
|
|
51
|
+
packageVersion: await packageVersion(),
|
|
52
|
+
period: { periodStart: figures.periodStart, periodEnd: figures.periodEnd },
|
|
53
|
+
figures,
|
|
54
|
+
};
|
|
55
|
+
if (path) {
|
|
56
|
+
const resolved = resolvePath(path);
|
|
57
|
+
mkdirSync(dirname(resolved), { recursive: true });
|
|
58
|
+
writeFileSync(resolved, JSON.stringify(answer, null, 2) + "\n");
|
|
59
|
+
answer.path = resolved;
|
|
60
|
+
}
|
|
61
|
+
return answer;
|
|
62
|
+
}
|
package/lib/auth.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-02 Authenticate MCP sessions via Cognito
|
|
5
|
+
// - **Use when:** the MCP's own tools (cloud book open/save) need a signed-in DIY Accounting Submit session.
|
|
6
|
+
// - **Does:** signIn in mcp/lib/auth.js opens the Cognito hosted UI and catches the redirect on a loopback listener, ports 49152 to 49159. It exchanges the code at the token endpoint and caches the refresh and id tokens under ~/.config/diya-submit/credentials.json, mode 600. accessToken refreshes the cached id token silently once it nears expiry.
|
|
7
|
+
// - **Run:** no command; see Does and Entry
|
|
8
|
+
// - **Entry:** `mcp/lib/auth.js:signIn`; `mcp/lib/auth.js:accessToken`
|
|
9
|
+
// - **Files:** mcp/lib/auth.js, mcp/test/auth.test.js
|
|
10
|
+
// - **Keywords:** mcp auth, cognito, pkce, oauth, loopback, credentials.json, sign in, access token
|
|
11
|
+
// - **Related:** MCP-01, MCP-03
|
|
12
|
+
// @end-capability
|
|
13
|
+
|
|
4
14
|
// auth.js -- the submission MCP's own stdio sign-in: authorization code with PKCE on a loopback
|
|
5
15
|
// redirect, the flow every CLI uses. signIn() opens the pool's hosted UI with a code challenge,
|
|
6
16
|
// catches the code on the first free port of the loopback listener's range (IdentityStack.java's
|
|
@@ -51,7 +61,7 @@ function baseUrl() {
|
|
|
51
61
|
|
|
52
62
|
// Overridable for tests only; production never sets DIYA_SUBMIT_CONFIG_DIR and always keeps the
|
|
53
63
|
// credentials under the user's own config directory.
|
|
54
|
-
function credentialsDir() {
|
|
64
|
+
export function credentialsDir() {
|
|
55
65
|
return process.env.DIYA_SUBMIT_CONFIG_DIR || join(homedir(), ".config", "diya-submit");
|
|
56
66
|
}
|
|
57
67
|
|
package/lib/batch-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-09 Run a client-scoped tool across every practice client
|
|
5
|
+
// - **Use when:** one submission or book tool must run once per client in a practice's list.
|
|
6
|
+
// - **Does:** runForClients in mcp/lib/batch-tools.js runs one allow-listed, client-scoped tool for every client in the practice's list. It merges each client's id into the call arguments and records each client's result or error in its own row. It backs the run_for_clients tool and the CLI's --all-clients mode.
|
|
7
|
+
// - **Run:** `node mcp/bin/diya-submit-mcp.js --all-clients <tool> [--arg key=value ...]`
|
|
8
|
+
// - **Entry:** `mcp/lib/batch-tools.js:runForClients`
|
|
9
|
+
// - **Files:** mcp/lib/batch-tools.js, mcp/test/batch-tools.test.js
|
|
10
|
+
// - **Keywords:** run_for_clients, batch tools, all-clients, per-client loop, practice batch run
|
|
11
|
+
// - **Related:** MCP-01, MCP-08
|
|
12
|
+
// @end-capability
|
|
13
|
+
|
|
4
14
|
// batch-tools.js -- run_for_clients: one client-scoped tool, run once per client in the
|
|
5
15
|
// practice's own list (practice-tools.js's listClients), collecting one result row per client.
|
|
6
16
|
// The allow-list is exactly the tools that take a clientId to act on one client at a time --
|
|
@@ -15,13 +25,20 @@
|
|
|
15
25
|
|
|
16
26
|
import { openBook, saveBook } from "./book-tools.js";
|
|
17
27
|
import { listClients } from "./practice-tools.js";
|
|
18
|
-
import {
|
|
28
|
+
import {
|
|
29
|
+
listVatObligations,
|
|
30
|
+
submitVatReturn,
|
|
31
|
+
getVatReceipt,
|
|
32
|
+
submitMicroEntityAccounts,
|
|
33
|
+
submitSmallCompanyAccounts,
|
|
34
|
+
} from "./submit-tools.js";
|
|
19
35
|
|
|
20
36
|
const HANDLERS = {
|
|
21
37
|
list_vat_obligations: listVatObligations,
|
|
22
38
|
submit_vat_return: submitVatReturn,
|
|
23
39
|
get_vat_receipt: getVatReceipt,
|
|
24
|
-
|
|
40
|
+
submit_micro_entity_accounts_sandbox: submitMicroEntityAccounts,
|
|
41
|
+
submit_small_company_accounts_sandbox: submitSmallCompanyAccounts,
|
|
25
42
|
open_book: openBook,
|
|
26
43
|
save_book: saveBook,
|
|
27
44
|
};
|
package/lib/book-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-03 Load and save diya-gl books via MCP
|
|
5
|
+
// - **Use when:** an MCP session needs to open or save a diya-gl book, locally or in the cloud.
|
|
6
|
+
// - **Does:** The two open_book and save_book tools in mcp/lib/book-tools.js back this server's session. open_book reads a book.toml plus lines.jsonl directory, any file the engine reads, or a cloud book. save_book writes the session's book in one of five formats, locally or to the cloud.
|
|
7
|
+
// - **Run:** no command; see Does and Entry
|
|
8
|
+
// - **Entry:** `mcp/lib/book-tools.js:openBook`; `mcp/lib/book-tools.js:saveBook`; `mcp/lib/book-tools.js:createSession`
|
|
9
|
+
// - **Files:** mcp/lib/book-tools.js, mcp/test/book-tools.test.js, mcp/test/fixtures/brickwork-pro-ltd-vat/book.toml, mcp/test/fixtures/precision-code-ltd-full/book.toml
|
|
10
|
+
// - **Keywords:** open_book, save_book, diya-gl, book.toml, lines.jsonl, cloud book, mcp book tools, xlsx export
|
|
11
|
+
// - **Related:** MCP-02, MCP-04, MCP-05, MCP-06, SS-03, SS-06
|
|
12
|
+
// @end-capability
|
|
13
|
+
|
|
4
14
|
// book-tools.js -- the two book tools over the filesystem: open_book loads a
|
|
5
15
|
// diya-gl book from a directory (book.toml + lines.jsonl) or from any file
|
|
6
16
|
// the diya-gl engine reads (a workbook, a package zip, a diya-gl zip, a
|
|
@@ -25,6 +35,7 @@ import { PRODUCTS, productModule } from "@diy-accounting-uk/diya-gl/dist/app/lib
|
|
|
25
35
|
import { stampBook } from "@diy-accounting-uk/diya-gl/dist/app/lib/provenance.js";
|
|
26
36
|
|
|
27
37
|
import { storedCredentials } from "./auth.js";
|
|
38
|
+
import { desktopClientHeaders } from "./client-headers.js";
|
|
28
39
|
|
|
29
40
|
export const SAVE_FORMATS = ["diya-gl-dir", "diya-gl-zip", "json", "xlsx", "zip"];
|
|
30
41
|
|
|
@@ -44,15 +55,27 @@ function baseUrl() {
|
|
|
44
55
|
* supplies the bearer every API call sends (the stdio server's is auth.js's file-backed pair; the
|
|
45
56
|
* hosted Lambda passes the request's bearer and an idToken that answers null). pollBudgetMs caps
|
|
46
57
|
* how long one tool call polls an asynchronous route, null for the route's own attempt limit.
|
|
58
|
+
* clientHeaders answers the headers a call to an HMRC route carries for HMRC's fraud prevention
|
|
59
|
+
* data (the stdio server reads its own machine; the hosted Lambda passes what the caller gives).
|
|
47
60
|
* @param {{credentials?: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>},
|
|
48
|
-
* pollBudgetMs?: number|null}} [options]
|
|
61
|
+
* pollBudgetMs?: number|null, clientHeaders?: () => Promise<Object>}} [options]
|
|
49
62
|
* @returns {{book: Object|null, lines: Array|null, product: string|null, sourcePath: string|null,
|
|
50
63
|
* cloud: {bookId: string, clientId: string|null, etag: string}|null,
|
|
51
64
|
* credentials: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>},
|
|
52
|
-
* pollBudgetMs: number|null}}
|
|
65
|
+
* pollBudgetMs: number|null, clientHeaders: () => Promise<Object>}}
|
|
53
66
|
*/
|
|
54
|
-
export function createSession({ credentials = storedCredentials, pollBudgetMs = null } = {}) {
|
|
55
|
-
return {
|
|
67
|
+
export function createSession({ credentials = storedCredentials, pollBudgetMs = null, clientHeaders = desktopClientHeaders } = {}) {
|
|
68
|
+
return {
|
|
69
|
+
book: null,
|
|
70
|
+
lines: null,
|
|
71
|
+
product: null,
|
|
72
|
+
sourcePath: null,
|
|
73
|
+
cloud: null,
|
|
74
|
+
hmrcGrant: null,
|
|
75
|
+
credentials,
|
|
76
|
+
pollBudgetMs,
|
|
77
|
+
clientHeaders,
|
|
78
|
+
};
|
|
56
79
|
}
|
|
57
80
|
|
|
58
81
|
function requireLoaded(session) {
|
|
@@ -100,6 +123,26 @@ function summarise(session, kind, bookChecks) {
|
|
|
100
123
|
};
|
|
101
124
|
}
|
|
102
125
|
|
|
126
|
+
/**
|
|
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.
|
|
130
|
+
* @param {Object} session
|
|
131
|
+
* @param {{clientId?: string}} params
|
|
132
|
+
* @returns {Promise<{entitlement: Object, books: Object[]}>}
|
|
133
|
+
*/
|
|
134
|
+
export async function listBooks(session, { clientId } = {}) {
|
|
135
|
+
const query = clientId ? `?clientId=${encodeURIComponent(clientId)}` : "";
|
|
136
|
+
const response = await fetch(`${baseUrl()}/api/v1/books${query}`, {
|
|
137
|
+
headers: { Authorization: `Bearer ${await session.credentials.accessToken()}` },
|
|
138
|
+
});
|
|
139
|
+
const body = await response.json().catch(() => ({}));
|
|
140
|
+
if (!response.ok) {
|
|
141
|
+
throw new Error(body?.message || `list_books failed with HTTP ${response.status}`);
|
|
142
|
+
}
|
|
143
|
+
return { entitlement: body.entitlement, books: body.books ?? [] };
|
|
144
|
+
}
|
|
145
|
+
|
|
103
146
|
/**
|
|
104
147
|
* The session's loaded book from the DIYA cloud by book id, over the same route the spreadsheets
|
|
105
148
|
* site's DIYA-GL pages read (GET /api/v1/books/{bookId}/versions/latest). Replaces the session's
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
2
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
3
|
+
|
|
4
|
+
// @capability MCP-22 Read the machine for HMRC fraud prevention headers
|
|
5
|
+
// - **Use when:** a stdio MCP call to an HMRC route needs the device data of HMRC's desktop connection method, or a new device header must be added.
|
|
6
|
+
// - **Does:** desktopClientHeaders in mcp/lib/client-headers.js reads the machine that runs the stdio MCP server: a persistent device id, local IP addresses and their timestamp, MAC addresses, the operating system user, the timezone, the operating system and device model, and the screens. callSubmitApi sends the result on every route behind the custom authoriser, and app/lib/buildFraudHeaders.js passes it to HMRC under DESKTOP_APP_VIA_SERVER. The process has no window, so it sends no Gov-Client-Window-Size. The hosted Lambda passes its own headers instead.
|
|
7
|
+
// - **Run:** no command; see Does and Entry
|
|
8
|
+
// - **Entry:** `mcp/lib/client-headers.js:desktopClientHeaders`
|
|
9
|
+
// - **Files:** mcp/lib/client-headers.js, mcp/test/client-headers.test.js
|
|
10
|
+
// - **Keywords:** fraud prevention headers, desktop app via server, device id, mac addresses, local ips, gov-client-screens, stdio mcp
|
|
11
|
+
// - **Related:** HMRC-25, MCP-07
|
|
12
|
+
// @end-capability
|
|
13
|
+
|
|
14
|
+
// client-headers.js -- what the stdio MCP server tells Submit about the machine it runs on, so
|
|
15
|
+
// that Submit can send HMRC the DESKTOP_APP_VIA_SERVER headers. HMRC asks for values collected
|
|
16
|
+
// immediately before each request, so the addresses and their timestamp are read per call. The
|
|
17
|
+
// device model and the screens take a child process each, so they are read once per process. A
|
|
18
|
+
// value this machine cannot give is left out, and Submit's send check counts the missing header.
|
|
19
|
+
|
|
20
|
+
import { execFileSync } from "node:child_process";
|
|
21
|
+
import { randomUUID } from "node:crypto";
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
23
|
+
import { networkInterfaces, release, type, userInfo } from "node:os";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
|
|
26
|
+
import { credentialsDir } from "./auth.js";
|
|
27
|
+
|
|
28
|
+
const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
29
|
+
|
|
30
|
+
export const MCP_VENDOR_VERSION = `diya-submit-mcp=${encodeURIComponent(version)}`;
|
|
31
|
+
|
|
32
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
33
|
+
const EMPTY_MAC = "00:00:00:00:00:00";
|
|
34
|
+
const CHILD_TIMEOUT_MS = 5000;
|
|
35
|
+
const OS_FAMILIES = { darwin: "macOS", win32: "Windows", linux: "Linux" };
|
|
36
|
+
const MAC_COLOUR_DEPTHS = { CGSEightBitColor: 8, CGSSixteenBitColor: 16, CGSThirtyBitColor: 30, CGSThirtytwoBitColor: 32 };
|
|
37
|
+
|
|
38
|
+
function run(command, args) {
|
|
39
|
+
try {
|
|
40
|
+
return execFileSync(command, args, { encoding: "utf8", timeout: CHILD_TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function readTrimmed(path) {
|
|
47
|
+
try {
|
|
48
|
+
return readFileSync(path, "utf8").trim();
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parseJson(text) {
|
|
55
|
+
try {
|
|
56
|
+
return text ? JSON.parse(text) : null;
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The device id, generated once and kept in the same directory as the credentials. HMRC asks for
|
|
64
|
+
* an identifier that stays on the device and does not expire. A deleted file gives a new id.
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export function deviceId() {
|
|
68
|
+
const path = join(credentialsDir(), "device-id");
|
|
69
|
+
const stored = existsSync(path) ? readFileSync(path, "utf8").trim() : "";
|
|
70
|
+
if (UUID.test(stored)) return stored;
|
|
71
|
+
const created = randomUUID();
|
|
72
|
+
mkdirSync(credentialsDir(), { recursive: true, mode: 0o700 });
|
|
73
|
+
writeFileSync(path, created, { mode: 0o600 });
|
|
74
|
+
return created;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function externalInterfaces(interfaces) {
|
|
78
|
+
return Object.values(interfaces)
|
|
79
|
+
.flat()
|
|
80
|
+
.filter((entry) => !entry.internal);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The Gov-Client-Local-IPs value. Answers null when the machine has no external interface.
|
|
85
|
+
* @param {Object} interfaces - the shape of os.networkInterfaces()
|
|
86
|
+
* @returns {string|null}
|
|
87
|
+
*/
|
|
88
|
+
export function localIpsHeader(interfaces) {
|
|
89
|
+
const addresses = [...new Set(externalInterfaces(interfaces).map((entry) => entry.address))];
|
|
90
|
+
return addresses.length > 0 ? addresses.map(encodeURIComponent).join(",") : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The Gov-Client-MAC-Addresses value. Answers null when no interface has a MAC address.
|
|
95
|
+
* @param {Object} interfaces - the shape of os.networkInterfaces()
|
|
96
|
+
* @returns {string|null}
|
|
97
|
+
*/
|
|
98
|
+
export function macAddressesHeader(interfaces) {
|
|
99
|
+
const addresses = [...new Set(externalInterfaces(interfaces).map((entry) => entry.mac))].filter((mac) => mac && mac !== EMPTY_MAC);
|
|
100
|
+
return addresses.length > 0 ? addresses.map(encodeURIComponent).join(",") : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The Gov-Client-Timezone value for a getTimezoneOffset() result, which counts minutes behind UTC.
|
|
105
|
+
* @param {number} offsetMinutes
|
|
106
|
+
* @returns {string}
|
|
107
|
+
*/
|
|
108
|
+
export function timezoneHeader(offsetMinutes) {
|
|
109
|
+
const ahead = -offsetMinutes;
|
|
110
|
+
const absolute = Math.abs(ahead);
|
|
111
|
+
const hours = String(Math.floor(absolute / 60)).padStart(2, "0");
|
|
112
|
+
const minutes = String(absolute % 60).padStart(2, "0");
|
|
113
|
+
return `UTC${ahead < 0 ? "-" : "+"}${hours}:${minutes}`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The Gov-Client-User-Agent value. HMRC allows a pair with no value to be left out.
|
|
118
|
+
* @param {{osFamily?: string|null, osVersion?: string|null, manufacturer?: string|null, model?: string|null}} device
|
|
119
|
+
* @returns {string}
|
|
120
|
+
*/
|
|
121
|
+
export function userAgentHeader({ osFamily, osVersion, manufacturer, model }) {
|
|
122
|
+
return Object.entries({ "os-family": osFamily, "os-version": osVersion, "device-manufacturer": manufacturer, "device-model": model })
|
|
123
|
+
.filter(([, value]) => value)
|
|
124
|
+
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
|
|
125
|
+
.join("&");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function readDevice() {
|
|
129
|
+
const device = { osFamily: OS_FAMILIES[process.platform] ?? type(), osVersion: release() };
|
|
130
|
+
if (process.platform === "darwin") {
|
|
131
|
+
return {
|
|
132
|
+
...device,
|
|
133
|
+
osVersion: run("sw_vers", ["-productVersion"]) ?? release(),
|
|
134
|
+
manufacturer: "Apple",
|
|
135
|
+
model: run("sysctl", ["-n", "hw.model"]),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
if (process.platform === "linux") {
|
|
139
|
+
return { ...device, manufacturer: readTrimmed("/sys/class/dmi/id/sys_vendor"), model: readTrimmed("/sys/class/dmi/id/product_name") };
|
|
140
|
+
}
|
|
141
|
+
if (process.platform === "win32") {
|
|
142
|
+
const system = parseJson(
|
|
143
|
+
run("powershell", [
|
|
144
|
+
"-NoProfile",
|
|
145
|
+
"-Command",
|
|
146
|
+
"Get-CimInstance Win32_ComputerSystem | Select-Object Manufacturer,Model | ConvertTo-Json",
|
|
147
|
+
]),
|
|
148
|
+
);
|
|
149
|
+
return { ...device, manufacturer: system?.Manufacturer, model: system?.Model };
|
|
150
|
+
}
|
|
151
|
+
return device;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function firstNumberPair(text) {
|
|
155
|
+
const match = /^(\d+) x (\d+)/.exec(text ?? "");
|
|
156
|
+
return match ? [Number(match[1]), Number(match[2])] : null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The screens in `system_profiler SPDisplaysDataType -json` output. Width and height are in points
|
|
161
|
+
* and the scaling factor is pixels per point, the same terms a browser reports.
|
|
162
|
+
* @param {string|null} text
|
|
163
|
+
* @returns {Array<{width: number, height: number, scalingFactor: number, colourDepth: number}>}
|
|
164
|
+
*/
|
|
165
|
+
export function parseMacDisplays(text) {
|
|
166
|
+
const displays = (parseJson(text)?.SPDisplaysDataType ?? []).flatMap((card) => card.spdisplays_ndrvs ?? []);
|
|
167
|
+
return displays.flatMap((display) => {
|
|
168
|
+
const points = firstNumberPair(display._spdisplays_resolution);
|
|
169
|
+
const pixels = firstNumberPair(display._spdisplays_pixels);
|
|
170
|
+
const colourDepth = MAC_COLOUR_DEPTHS[display.spdisplays_depth];
|
|
171
|
+
if (!points || !pixels || !colourDepth) return [];
|
|
172
|
+
return [{ width: points[0], height: points[1], scalingFactor: pixels[0] / points[0], colourDepth }];
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The screens in `xdpyinfo` output. X reports physical pixels, so the scaling factor is 1.
|
|
178
|
+
* @param {string|null} text
|
|
179
|
+
* @returns {Array<{width: number, height: number, scalingFactor: number, colourDepth: number}>}
|
|
180
|
+
*/
|
|
181
|
+
export function parseXdpyinfoDisplays(text) {
|
|
182
|
+
const sizes = [...(text ?? "").matchAll(/dimensions:\s+(\d+)x(\d+) pixels/g)];
|
|
183
|
+
const depths = [...(text ?? "").matchAll(/depth of root window:\s+(\d+) planes/g)];
|
|
184
|
+
return sizes.flatMap((size, index) =>
|
|
185
|
+
depths[index] ? [{ width: Number(size[1]), height: Number(size[2]), scalingFactor: 1, colourDepth: Number(depths[index][1]) }] : [],
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The screens in the JSON of Win32_VideoController. Windows reports physical pixels here, so the
|
|
191
|
+
* scaling factor is 1. ConvertTo-Json answers an object for one controller and a list for several.
|
|
192
|
+
* @param {string|null} text
|
|
193
|
+
* @returns {Array<{width: number, height: number, scalingFactor: number, colourDepth: number}>}
|
|
194
|
+
*/
|
|
195
|
+
export function parseWindowsDisplays(text) {
|
|
196
|
+
const parsed = parseJson(text);
|
|
197
|
+
const controllers = [parsed].flat().filter(Boolean);
|
|
198
|
+
return controllers
|
|
199
|
+
.filter(
|
|
200
|
+
(controller) => controller.CurrentHorizontalResolution && controller.CurrentVerticalResolution && controller.CurrentBitsPerPixel,
|
|
201
|
+
)
|
|
202
|
+
.map((controller) => ({
|
|
203
|
+
width: controller.CurrentHorizontalResolution,
|
|
204
|
+
height: controller.CurrentVerticalResolution,
|
|
205
|
+
scalingFactor: 1,
|
|
206
|
+
colourDepth: controller.CurrentBitsPerPixel,
|
|
207
|
+
}));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function readDisplays() {
|
|
211
|
+
if (process.platform === "darwin") return parseMacDisplays(run("system_profiler", ["SPDisplaysDataType", "-json"]));
|
|
212
|
+
if (process.platform === "linux") return parseXdpyinfoDisplays(run("xdpyinfo", []));
|
|
213
|
+
if (process.platform === "win32") {
|
|
214
|
+
const query =
|
|
215
|
+
"Get-CimInstance Win32_VideoController | Select-Object CurrentHorizontalResolution,CurrentVerticalResolution,CurrentBitsPerPixel | ConvertTo-Json";
|
|
216
|
+
return parseWindowsDisplays(run("powershell", ["-NoProfile", "-Command", query]));
|
|
217
|
+
}
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The Gov-Client-Screens value. Answers null when the machine reports no screen.
|
|
223
|
+
* @param {Array<{width: number, height: number, scalingFactor: number, colourDepth: number}>} displays
|
|
224
|
+
* @returns {string|null}
|
|
225
|
+
*/
|
|
226
|
+
export function screensHeader(displays) {
|
|
227
|
+
if (displays.length === 0) return null;
|
|
228
|
+
return displays
|
|
229
|
+
.map(
|
|
230
|
+
({ width, height, scalingFactor, colourDepth }) =>
|
|
231
|
+
`width=${width}&height=${height}&scaling-factor=${scalingFactor}&colour-depth=${colourDepth}`,
|
|
232
|
+
)
|
|
233
|
+
.join(",");
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
let machine = null;
|
|
237
|
+
|
|
238
|
+
function readMachineOnce() {
|
|
239
|
+
machine ??= { device: readDevice(), displays: readDisplays() };
|
|
240
|
+
return machine;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The headers a call to an HMRC route carries from the stdio server. A header with no value is
|
|
245
|
+
* left out of the answer.
|
|
246
|
+
* @param {{device: Object, displays: Array}} [machineFacts] - read from this machine when omitted
|
|
247
|
+
* @returns {Promise<Object>}
|
|
248
|
+
*/
|
|
249
|
+
export async function desktopClientHeaders({ device, displays } = readMachineOnce()) {
|
|
250
|
+
const interfaces = networkInterfaces();
|
|
251
|
+
const headers = {
|
|
252
|
+
"Gov-Client-Device-ID": deviceId(),
|
|
253
|
+
"Gov-Client-Local-IPs": localIpsHeader(interfaces),
|
|
254
|
+
"Gov-Client-Local-IPs-Timestamp": new Date().toISOString(),
|
|
255
|
+
"Gov-Client-MAC-Addresses": macAddressesHeader(interfaces),
|
|
256
|
+
"Gov-Client-Screens": screensHeader(displays),
|
|
257
|
+
"Gov-Client-Timezone": timezoneHeader(new Date().getTimezoneOffset()),
|
|
258
|
+
"Gov-Client-User-Agent": userAgentHeader(device),
|
|
259
|
+
"Gov-Client-User-IDs": `os=${encodeURIComponent(userInfo().username)}`,
|
|
260
|
+
"Gov-Vendor-Version": MCP_VENDOR_VERSION,
|
|
261
|
+
};
|
|
262
|
+
return Object.fromEntries(Object.entries(headers).filter(([, value]) => value));
|
|
263
|
+
}
|
|
@@ -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-10 Import a NatWest bank statement into diya-gl lines
|
|
5
|
+
// - **Use when:** a NatWest current-account CSV export must become validated diya-gl bank lines for a book.
|
|
6
|
+
// - **Does:** bankLinesFromCsv in mcp/lib/finance/bank-lines.js parses a NatWest CSV export into one validated line per transaction, with no filtering or netting. closingBalance reads the statement's closing balance. Direction is set in diya-gl:bankCode from the sign of the statement's Value column.
|
|
7
|
+
// - **Run:** no command; see Does and Entry
|
|
8
|
+
// - **Entry:** `mcp/lib/finance/bank-lines.js:bankLinesFromCsv`; `mcp/lib/finance/bank-lines.js:closingBalance`
|
|
9
|
+
// - **Files:** mcp/lib/finance/bank-lines.js, mcp/test/bank-lines.test.js
|
|
10
|
+
// - **Keywords:** natwest csv, bank statement import, diya-gl bank lines, bankcode, reconciliation, finance import
|
|
11
|
+
// - **Related:** MCP-11, MCP-12
|
|
12
|
+
// @end-capability
|
|
13
|
+
|
|
4
14
|
// bank-lines.js -- parses a NatWest current account CSV export
|
|
5
15
|
// (Date,Type,Description,Value,Balance,Account Name,Account Number) into
|
|
6
16
|
// validated diya-gl bank lines, one per statement transaction. Every
|
|
@@ -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-11 Seed a book from a workbook set
|
|
5
|
+
// - **Use when:** a finished trading year's Company package workbooks must seed a new book.toml for the following year.
|
|
6
|
+
// - **Does:** bookFromWorkbookSet in mcp/lib/finance/book-from-workbook.js reads a complete Company package through the diya-gl engine's own extractors. The package is Financialaccounts.xlsx, Fixedassets.xlsx, Companysecretary.xlsx and the Sales, Purchases and bank workbooks. It validates the result against the published v2 book schema.
|
|
7
|
+
// - **Run:** no command; see Does and Entry
|
|
8
|
+
// - **Entry:** `mcp/lib/finance/book-from-workbook.js:bookFromWorkbookSet`; `mcp/lib/finance/book-from-workbook.js:toToml`
|
|
9
|
+
// - **Files:** mcp/lib/finance/book-from-workbook.js, mcp/test/book-from-workbook.test.js
|
|
10
|
+
// - **Keywords:** book from workbook, seed book.toml, company package, workbook set, opening balances, fixed asset register, book schema
|
|
11
|
+
// - **Related:** MCP-03, MCP-10
|
|
12
|
+
// @end-capability
|
|
13
|
+
|
|
4
14
|
// book-from-workbook.js -- seeds a diya-gl book.toml (entity information,
|
|
5
15
|
// chart of accounts, opening balances, debtors, creditors, fixed assets,
|
|
6
16
|
// dividends and members) from a complete Company package's workbook set:
|