UNPKG

@ekwo-ai/mcp

Version:

MCP server for Ekwo OS: let an AI agent work on the books, under the user's own row level security.

848 lines • 92 kB
/**
 * The server itself: the tools, the resources and the two prompts.
 *
 * The descriptions here are written for a model rather than for a reference
 * manual — when to reach for the tool, what comes back, and what it will not
 * do. That last part is the one that earns its place: a model told that
 * `post_document` cannot be undone asks before calling it — and the database
 * holds it to the company's agent_posting whatever it decides — and a model told
 * that a missing tax is not zero per cent stops inventing one.
 */
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { EkwoMcpError } from './backend.js';
import { columns, relayableCloudOffer, relayableInvitation } from '@ekwo-ai/core';
import * as read from './tools/read.js';
import * as write from './tools/write.js';
import { toolsetsFor } from './tools/modules.js';
import { TOOL_EFFECTS, annotationsFor } from './tools/effect.js';
import { ON_DEMAND_INSTRUCTIONS, loadTools, searchTools, startOnDemand } from './tools/loading.js';
export const SERVER_NAME = '@ekwo-ai/mcp';
/**
 * What this server tells a client it is, in the MCP handshake.
 *
 * Repeated here rather than read from `package.json`, for the reason
 * `SCHEMA_MIN` is: a bundle that never ships a manifest still has to carry it.
 * `tests/mcp/surface.test.ts` keeps the two equal, so a release that bumps one
 * and forgets the other fails the build.
 */
export const SERVER_VERSION = '0.27.0';
/** Everything a tool returns: JSON, pretty-printed, as one text block. */
function ok(payload) {
    return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
}
/**
 * A failure, with the database's own words first.
 *
 * `period_locked: 2026-03-31 is on or before the accounting lock date` is
 * more useful to a model than anything this package could paraphrase, so it
 * leads; the sentence underneath says what to do about it.
 */
function fail(error) {
    const message = error instanceof Error ? error.message : String(error);
    const hint = error instanceof EkwoMcpError ? error.hint : undefined;
    return {
        isError: true,
        content: [{ type: 'text', text: hint === undefined ? message : `${message}\n\n${hint}` }],
    };
}
async function guard(run) {
    try {
        return ok(await run());
    }
    catch (error) {
        return fail(error);
    }
}
/**
 * What a client reads at the handshake, before it calls anything.
 *
 * Written as the first session an agent has with a set of books: what to call
 * first, where the company and its financial years are, how to read a tax
 * return, how to correct what is posted, and what a refusal means.
 * `tests/mcp/surface.test.ts` checks that every tool and prompt named here is
 * one this server offers, and that every refusal named has its sentence.
 */
export const INSTRUCTIONS = [
    'Ekwo OS keeps double-entry books in the user\'s own Postgres. You act as that user: everything you can see and change is what row level security lets them see and change. Amounts are decimal strings ("1210.00"), dates are ISO (2026-06-15), identifiers are uuids.',
    'A first session, in order. (1) list_companies: every other tool takes a company_id from it; an empty list means this user has not been invited to a company yet, and status says who you are acting as. (2) get_company: the financial years and whether each is closed, the lock dates, the journals and the role accounts — a date you book on falls in an open year, after the lock date. (3) list_accounts and the resource ekwo://companies/{companyId}/taxes: a document line names its account and its tax by code, never by rate, because several taxes share a rate; describe_pack says which country pack those codes come from and how far it has been reviewed. (4) search_contacts, then create_contact only if nobody matches, then create_document: a draft with the totals the database computed. Show it to the user. (5) post_document once the user has said yes to that document; record_payment when the money moves. How you may post is the database\'s to hold you to, and status says it: the company\'s agent_posting (in get_company) and the choice the person made for this session. In review, the default, a document is posted only after a person approved that draft as it stands, and post_document is refused with approval_required until then; in autopilot — the company\'s setting, or a session the person started so — you post directly, and every posting is recorded on the audit trail with this session. A company that forbids autopilot refuses it (autopilot_forbidden).',
    'Reading a tax return: vat_return gives the boxes of a period with their names and amounts, summed from what was posted, and the boxes computed from other boxes; a draft is in no box. Name a report_code only where the country files several declarations. It prepares figures and files nothing — the prompt prepare_vat_return walks through checking them against the ledger. The reports beside it are trial_balance, general_ledger, journal_book (the book of one journal or of all of them, with the totals of each), aged_balance, subledger (a receivable or payable account contact by contact, with its control against the trial balance), contact_statement (one contact), financial_statement (list_statements first), financial_analysis, the figures a ratio is computed from, and analytic_report, the result of each project, cost centre or site of an analytic axis.',
    'Correcting: a posted entry is never deleted or edited. A posted invoice is undone by cancel_document — back to draft where its country allows it and nothing has left, by the credit note that names it otherwise, and it says which — and an entry keyed by hand by reverse_entry. A paid document is unmatched first with unreconcile, and only when the user says so. Ask the user before every post, cancel, reversal, payment or lock.',
    'When the database refuses, the message starts with a name — period_locked, entry_unbalanced, document_total_mismatch, reversal_date_needed — followed by a sentence saying what to do next. Report it to the user and follow that sentence rather than working around it.',
].join('\n\n');
/** The instructions, with the invitation to register and the Cloud offer when they apply. */
export function instructionsFor(options = {}) {
    return [
        INSTRUCTIONS,
        ...(options.inviteToRegister === true ? [relayableInvitation()] : []),
        ...(options.offerCloud === true ? [relayableCloudOffer()] : []),
        ...(options.tools === 'on_demand' ? [ON_DEMAND_INSTRUCTIONS] : []),
    ].join('\n\n');
}
/**
 * The same tool, with its title where every reader looks for it.
 *
 * The protocol lets a tool carry its human-readable name in two places: a
 * top-level `title`, which the SDK's `registerTool` takes, and
 * `annotations.title`, which some directories and clients are the only ones
 * to read. A tool declared with one and not the other is listed by its
 * machine name there. So the one title given below is copied into the
 * annotations, and a title already set there is left as it is.
 */
function titled(config) {
    if (config.title === undefined || config.annotations?.title !== undefined)
        return config;
    return { ...config, annotations: { ...config.annotations, title: config.title } };
}
/**
 * The one door every tool of this server goes through: it copies the title
 * into the annotations and keeps each registered tool by name, for
 * `search_tools` and `load_tools`. Done once rather than at each
 * registration below, so a tool added later goes through it too, and
 * `tests/mcp/surface.test.ts` reads the list a client sees to make sure none
 * slipped past.
 */
function toolRegistrar(server, registered) {
    return (name, config, cb) => {
        const tool = server.registerTool(name, titled(config), cb);
        registered.set(name, tool);
        return tool;
    };
}
/**
 * The sentence the posting tools end with: how this session posts, as the
 * person who started it chose — the tool list is read once, so it is said
 * where the model reads it.
 */
export function sessionPosting(backend) {
    switch (backend.agent?.posting) {
        case 'autopilot':
            return ' This session runs in autopilot: you post without an approval wherever the company allows it.';
        case 'review':
            return ' This session runs in review: you post only what a person approved.';
        default:
            return " This session follows each company's agent_posting.";
    }
}
export function buildServer(backend, options = {}) {
    const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: instructionsFor(options) });
    const tools = new Map();
    const register = toolRegistrar(server, tools);
    // -------------------------------------------------------------------- read
    register('list_companies', {
        title: 'List companies',
        description: 'The companies of this installation that you are a member of, with your role on each. Start here: every other tool needs a company_id. Returns id, name, country, currency and your role. It does not list companies you were never invited to — those are invisible, not hidden. Next: get_company on the one the user means.',
        inputSchema: read.ListCompaniesInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async () => guard(() => read.listCompanies(backend)));
    register('get_company', {
        title: 'Company settings',
        description: 'Everything needed before booking in a company: its financial years and whether they are closed, its lock dates, its journals, and the accounts that play the receivable, payable, suspense and retained-earnings roles. Read this before creating a document if you do not already know the journals and the lock dates. Next: list_accounts and the ekwo://companies/{companyId}/taxes resource give the codes a document line names.',
        inputSchema: read.GetCompanyInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.getCompany(backend, args)));
    register('list_accounts', {
        title: 'Chart of accounts',
        description: 'The accounts a company actually works with, filtered by code prefix, by account type, or by a search on the name. Use it to find the income or expense account a document line should carry. By default it returns the working chart — the accounts that carry entries, that the company\'s settings or an enabled module point at, or that somebody pinned — because a country pack transcribes the whole regulation and a company uses a few dozen of its several hundred accounts; `in_use_from` and `in_use_to` narrow the movements to a period, `include_all` returns the whole chart, and `include_deprecated` returns it with the retired accounts too. This is a reading and not a restriction: any account of the chart that is not deprecated may still be booked on.',
        inputSchema: read.ListAccountsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listAccounts(backend, args)));
    register('search_contacts', {
        title: 'Find a contact',
        description: 'Customers, suppliers and other third parties of a company, by name, by type or by VAT number. Use it before creating a document: a document is booked against a contact, and creating a second contact for a customer who already exists splits their account. Nobody matches: create_contact. Found: create_document with its id.',
        inputSchema: read.SearchContactsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.searchContacts(backend, args)));
    register('suggest_duplicate_contacts', {
        title: 'Find the contacts that are probably one party',
        description: 'The active contacts of a company that are probably one party — two spellings of one customer, two imports of one supplier — strongest first, one row per contact to absorb. The rows that share a keep_id are one group (the contacts a chain of pairs joins); each names the contact to keep (the one of the group more ledger lines and documents name, then the older), the one to absorb, proposed_name (the simplest name the group carries — the fewest words carried by contacts outside the group, then the fewest words — a proposal for the kept contact, written only if the user wants it), a score from 0 to 1, the kinds of evidence (vat_number, registration_number, account: the same number or bank account, score 1; name: the words of the shorter name in the longer, each weighed by how few contacts carry it, so that a shared trade, place or legal form alone is never a pair; 0.950 for the same name, 0.900 otherwise, 0.600 when the shorter name agrees with several contacts) and the evidence in sentences. Two contacts with different VAT or registration numbers, a contact and its own parent, and inactive or merged contacts are never proposed. contact_types keeps the proposals among the contacts of those types — customer, supplier and both for the parties of the books — and every contact is read when it is absent. It writes nothing: show the user both contacts and call merge_contacts only on a pair they confirm, with the contact they choose to keep.',
        inputSchema: read.SuggestDuplicateContactsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.suggestDuplicateContacts(backend, args)));
    register('contact_statement', {
        title: 'Statement of a contact',
        description: 'The statement of account of one customer or supplier over a period: the balance carried forward from before it, then every posted line of their receivable and payable accounts — date, journal, entry, the document it books, debit, credit and running balance — and the balance the period ends on. Debit minus credit, in the company currency: positive is what the contact owes the company, negative what the company owes them. Each line says how far a matching has settled it today (matching_state open, partial or matched, and open_amount). Drafts are not in it. It is the ledger read for one contact, the same figures aged_balance gives.',
        inputSchema: read.ContactStatementInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.contactStatement(backend, args)));
    register('list_documents', {
        title: 'List documents',
        description: 'Invoices, credit notes and quotes of a company, filtered by type, state, settlement state, contact or date range. `state` is the document (draft, posted, cancelled) and `payment_state` is the settlement (not_paid, partially_paid, paid) — two different questions. A quote or an order also carries its answer (accepted_at, accepted_by, declined_at) and `quote_status` — draft, sent, accepted, declined, expired or cancelled — derived by the database from those facts; null on other documents. Returns headers and totals, not lines; use get_document for those.',
        inputSchema: read.ListDocumentsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listDocuments(backend, args)));
    register('get_document', {
        title: 'Read a document',
        description: 'One document with its lines, the account and tax of each line, the legal mentions its country requires on it, that country\'s payment and e-invoicing rules, and — when it has been posted — the ledger entry it produced with every ledger line. Use it to check what a document will book, what it did book, and what has to be printed on it.',
        inputSchema: read.GetDocumentInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.getDocument(backend, args)));
    register('render_invoice_pdf', {
        title: 'The PDF of an invoice',
        description: 'The PDF of a sale invoice or a sale credit note, rendered from the books: the seller with its logo, the buyer, the lines, the tax summary, the totals and what is still due, how to pay, and the legal mentions the country requires — as the views publish them, in the accent colour and on the logo side the company set with update_company_profile. Comes back as a PDF resource (base64) beside a JSON summary: filename, pages, whether the logo was used. factur_x: true embeds the CII XML of a posted document and returns the rules of EN 16931 it breaks. Words of the layout are English unless labels gives them in the document\'s language. Records nothing, sends nothing: the copy a customer received is not kept here.',
        inputSchema: read.RenderInvoicePdfInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: true },
    }, async (args) => {
        try {
            const logoFetch = options.logoFetch ?? ((url, init) => globalThis.fetch(url, init));
            const { file, ...summary } = await read.renderInvoicePdf(backend, args, logoFetch);
            return {
                content: [
                    { type: 'text', text: JSON.stringify(summary, null, 2) },
                    {
                        type: 'resource',
                        resource: { uri: `ekwo://documents/${summary.document_id}/pdf`, mimeType: 'application/pdf', blob: read.base64Of(file) },
                    },
                ],
            };
        }
        catch (error) {
            return fail(error);
        }
    });
    register('get_preferences', {
        title: 'What this user prefers',
        description: 'The signed-in user\u2019s own preferences — which company an interface opens on, the language they read labels in, their timezone and how they like a date and a number written — and the language chain to read labels with: theirs, then the company\u2019s, then the country pack\u2019s. Every one of them may be null, and null means "take the next answer in the chain" rather than a default this installation picked.',
        inputSchema: read.GetPreferencesInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.getPreferences(backend, args)));
    register('list_api_keys', {
        title: 'Machine keys of a company',
        description: 'The keys a company has issued to machines, what each one may do, how it posts a document (posting_mode, review or autopilot, fixed when it was issued), when it was last used and whether it is still live. Only somebody who manages members sees them, and no secret is in here: a key is shown once, when it is issued.',
        inputSchema: read.ListApiKeysInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listApiKeys(backend, args)));
    register('list_invitations', {
        title: 'Invitations into a company',
        description: 'The people invited into a company and not yet on its books, with the preset and the capabilities each was invited with, and whether the invitation is still pending, expired, accepted or withdrawn. Only somebody who manages members sees them. The token is never in here: it is shown once, when the invitation is issued.',
        inputSchema: read.ListInvitationsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listInvitations(backend, args)));
    register('list_shares', {
        title: 'Public links onto documents',
        description: 'The links a company has published onto its own sales documents, with how many times each was opened and when it was last opened. No token is in here: a link is shown once, when it is made. Use it to answer "did the customer open the invoice?" and to find the link to withdraw.',
        inputSchema: read.ListSharesInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listShares(backend, args)));
    register('list_bank_transactions', {
        title: 'Bank transactions',
        description: 'Statement lines of a company, pending by default — the ones still waiting to be dealt with. `amount` is signed: positive is money in. A statement line is not a ledger entry; recording a payment is what books it.',
        inputSchema: read.ListBankTransactionsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listBankTransactions(backend, args)));
    register('trial_balance', {
        title: 'Trial balance',
        description: 'Opening balance, movements of the period and closing balance for every account, from posted entries only. The debit and credit totals are equal on a healthy ledger; if they are not, say so rather than explaining it away.',
        inputSchema: read.TrialBalanceInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.trialBalance(backend, args)));
    register('general_ledger', {
        title: 'General ledger',
        description: 'Every posted line of an account over a period, with the balance carried forward from before it and a running balance. Give account_code for one account; leave it out for all of them, which on a real company is a lot of lines. contact_ids keeps the lines of those contacts only, each with its own balance carried forward and running balance — the detail of a row of subledger.',
        inputSchema: read.GeneralLedgerInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.generalLedger(backend, args)));
    register('journal_book', {
        title: 'Journal book',
        description: 'The book of a journal: every line of every posted entry over a period, in the order a book is read — day, journal, entry number, line — each with its entry, the document behind it, its account and its contact, and the totals of each journal at the head. Give journal_code for one journal (the sales journal, the bank); leave it out for the book of every journal, which on a real company is a lot of lines. For one account with its running balance, use general_ledger.',
        inputSchema: read.JournalBookInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.journalBook(backend, args)));
    register('suggest_line_contacts', {
        title: 'Suggest the contact of lines that name nobody',
        description: 'For each open line on a receivable or payable account that names no contact — typically the open items of books imported line by line — the contacts it could be, best first, each with a score, the method (a learned motif, the number of a document of the company quoted in the label, the description or the reference of the entry, the words of a contact\'s name), the evidence in a sentence, and alternatives: how many contacts the same evidence reached. More than 1 is a question for the user, not an answer. It writes nothing; set_line_contact names a line once the user has chosen.',
        inputSchema: read.SuggestLineContactsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.suggestLineContacts(backend, args)));
    register('suggest_item_combinations', {
        title: 'Suggest which open items settle each other',
        description: 'For each open line on a receivable or payable account of one counterparty (a branch and its parent are one party), the lines of the other side on the same account that could settle it, up to three proposals a line: an exact pair, several lines that add up to it to the cent ("this payment settles these three invoices", or one invoice paid in instalments), and — only when nothing is exact — a pair or several lines within the company\'s difference tolerance, with the difference (the line less the total). Each proposal has a stable proposal_id, a kind (pair, combination), the lines and a sentence. It writes nothing: show the user, then reconcile_many for a difference of 0.00, or reconcile_with_difference once they have seen the difference and chosen a reason.',
        inputSchema: read.SuggestItemCombinationsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.suggestItemCombinations(backend, args)));
    register('matching_difference_options', {
        title: 'The reasons and the tolerance for booking a difference',
        description: 'What reconcile_with_difference accepts for this company: the largest difference it books (in units of the currency and as an amount) and the reasons — rounding, exchange_difference — each with the account the pack gives, the side it answers (charge, income, either) and whether it is available. No pack carries a role for bank charges or payment discounts, so they are not reasons.',
        inputSchema: read.MatchingDifferenceOptionsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.matchingDifferenceOptions(backend, args)));
    register('aged_balance', {
        title: 'Aged balance',
        description: 'What customers still owe (or what is still owed to suppliers), bucketed by how overdue it is. It reads unmatched ledger lines, not invoices, so it ties back to the balance sheet: an invoice counts as settled only once its payment has been matched.',
        inputSchema: read.AgedBalanceInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.agedBalance(backend, args)));
    register('subledger', {
        title: 'Subsidiary ledger',
        description: 'A control account read contact by contact, as an accountant audits it: for each receivable and payable account (or the one account_code names) and each contact, the balance brought forward from before the period, the debit and credit of the period, the closing balance, the number of lines of the period and the number still open today; the lines that name no contact in a row of their own, contact_id null. Debit minus credit, in the company currency; drafts are not in it. control gives, per account, its figures in the trial balance, the sum of its named contacts and the difference — the lines naming nobody — with ties_out true when that row is the difference to the cent. The lines of one row: general_ledger with account_code and contact_ids; one contact across its accounts: contact_statement.',
        inputSchema: read.SubledgerInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.subledger(backend, args)));
    register('vat_return', {
        title: 'VAT return',
        description: 'The boxes of the VAT return for a period, with their names: the base and tax boxes are summed from what the postings wrote on the ledger lines, the totals are derived from them by the declaration form of the country pack. No country rule lives in this tool, nor in the function behind it. Name a report_code only where a country files several declarations. It prepares figures; it files nothing.',
        inputSchema: read.VatReturnInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.vatReturn(backend, args)));
    register('instalment_plan', {
        title: 'VAT instalments of a period',
        description: 'The payments on account of a declaration that the VAT scheme a company recorded asks for during its period — a simplified scheme pays part of the year\'s tax before filing the annual return — with what was due, what was paid and what is outstanding. The schedule, the percentages and the box of the previous year they are read on are country pack data; no country rule lives in this tool. It reads; it pays nothing.',
        inputSchema: read.InstalmentPlanInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.instalmentPlan(backend, args)));
    register('ec_sales_list', {
        title: 'Recapitulative statement of European Union supplies',
        description: 'Who, in another Member State, was supplied without VAT over a period, and for how much: one line per customer VAT number and per nature — goods, services — read from the treatment of the tax on each sale line, with credit notes deducted. The totals tie back to the European Union boxes of vat_return for the same period. A line that carries an issue cannot be filed as it stands, most often because the customer has no VAT number recorded: say so rather than leaving it out of the answer. Name a report_code to have the period checked against the cadence this company files that statement on — it has one of its own, and it is rarely the cadence of the return. No country rule lives in this tool. It prepares a statement; it files nothing.',
        inputSchema: read.EcSalesListInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.ecSalesList(backend, args)));
    register('portfolio_upcoming_filings', {
        title: 'Returns falling due, across your companies',
        description: 'What falls due between two dates in every company you may read the declarations of — the question a firm asks of all the books it keeps, and the one a person asks of the single company they run. "Portfolio" is meant as an accounting firm means it — its client portfolio — and is nothing but that: the companies you hold filings.read on, worked out at each call, never a list anybody maintains. Every one of them is in the answer, including a company whose country pack names no deadline, which is listed without a date and says so; a company left out would be indistinguishable from one that was never looked at. No country rule lives in this tool. It reads a calendar; it prepares and files nothing.',
        inputSchema: read.PortfolioUpcomingFilingsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.portfolioUpcomingFilings(backend, args)));
    register('portfolio_filings_touched_since', {
        title: 'Declared periods that moved, across your companies',
        description: 'Which declarations, across your portfolio — every company you may read the declarations of, which for an accounting firm is its clients — had entries posted into their period after they were filed — with the company named, how many entries, and how many of the filed figures now disagree. A period stays open after its return has gone, on purpose; this is what keeps a late entry from going unnoticed. Companies with nothing to report are named too, with how many filed declarations were examined. It reads; whether a corrective is owed is for whoever keeps the books.',
        inputSchema: read.PortfolioFilingsTouchedSinceInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.portfolioFilingsTouchedSince(backend, args)));
    register('portfolio_overview', {
        title: 'What is overdue, across your companies',
        description: 'What customers owe each company past their due date, and what each company owes its suppliers past theirs, on one day, in every company you may read the ledger of — for an accounting firm, its clients; for a person, the company they run. One row per company: what is open, what is overdue, what is more than ninety days late, and how many parties are late, on each side, in the currency of the company. It is aged_balance of every company, summed: aged_balance itself gives the detail party by party. Every company of the portfolio is in the answer, with zeros where nothing is open; a company left out would be indistinguishable from one owed nothing. It reads; it reminds nobody and pays nothing.',
        inputSchema: read.PortfolioOverviewInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.portfolioOverview(backend, args)));
    register('list_statements', {
        title: 'List financial statements',
        description: 'The schemes this company can be presented on: those of its country and of its chart of accounts, plus the generic framework by account type that fits any chart. Ask this before financial_statement rather than guessing a code.',
        inputSchema: read.ListStatementsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listStatements(backend, args)));
    register('financial_statement', {
        title: 'Financial statement',
        description: 'A balance sheet or an income statement for a period, on the scheme the country pack declares — the Belgian abbreviated model, the French liasse — or on the generic framework by account type. Each line is summed from the accounts its rules catch and the totals are derived from the lines; no country rule lives in this tool. It also returns the accounts no line catches: if that list is not empty, say so instead of presenting a statement that does not tie out. It prepares figures; it files nothing.',
        inputSchema: read.FinancialStatementInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.financialStatement(backend, args)));
    register('financial_analysis', {
        title: 'Financial analysis',
        description: "The figures an analysis of a company is computed from — revenue, other operating income, purchases, staff costs, depreciation, the financial result, income tax, the net result, equity, total and current assets, cash, trade receivables, current liabilities, trade payables, long-term debt — each with the accounts that make it. The movements are read over the period and the balances at its end; equity includes the result of the years not closed yet. Which accounts make each figure is written in the company's country pack and in no tool. Each row carries source: pack when the country pack defines the analysis; framework when it defines none and the figures are read by account type through the generic framework, which leaves out staff costs, the financial result and income tax because no account type tells them apart — say those are not read rather than zero. The figures are never to be guessed from account codes. Ratios — a margin, a current ratio, days of sales outstanding — are worked out from these, not stored. It prepares figures; it files nothing.",
        inputSchema: read.FinancialAnalysisInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.financialAnalysis(backend, args)));
    register('list_analytic_axes', {
        title: 'Analytic axes',
        description: 'The analytic axes of a company — a cost centre, a project, a site, a business unit — each with its values, which may nest under a parent_id, and required_on: none, or expense, income or result — the lines that must carry the axis whole, or posting refuses them (analytic_axis_required). A value says what a cost, a revenue or a fixed asset is for; a product says what was sold or bought. A retired value takes no new share. Read it before analytic_report, which takes an axis by its code.',
        inputSchema: read.ListAnalyticAxesInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listAnalyticAxes(backend, args)));
    register('analytic_report', {
        title: 'Result by analytic value',
        description: 'The result of each value of one analytic axis over a period, read from the posted ledger: the income, the expense and their difference per value, in the company\'s currency, from the whole income statement — salaries, rent and depreciation included, wherever they were split — and fixed_assets, the net movement of the fixed-asset accounts, beside the result and never in it. A value with others below it holds their subtotal; its own amount alone is in the direct_ columns, and level is its depth. unassigned is the part no share of the axis reaches and total the whole period: the direct_ amounts and unassigned add up to total, so say how large unassigned is rather than presenting the values as the whole, and never add a parent to its children. The margin of each product is a different question, read from the invoices. It prepares figures; it files nothing.',
        inputSchema: read.AnalyticReportInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.analyticReport(backend, args)));
    register('generate_fec', {
        title: 'Generate the French FEC',
        description: 'The Fichier des Écritures Comptables for a period: the eighteen columns of the arrêté du 29 juillet 2013, as text, with the checks a tax inspector applies first (mandatory fields, one side per line, entries balancing) and the filename the format wants. The file comes back in the answer; writing it to disk is the caller\'s business.',
        inputSchema: read.GenerateFecInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.generateFec(backend, args)));
    register('describe_pack', {
        title: 'Where a country pack comes from',
        description: "The country packs this installation holds, with their version, how much anyone has read them, and the register of texts each was built from — the title, the official publisher, an absolute link and the day somebody opened it, per text. Use it whenever you are asked where a rate, a chart of accounts or a box of the declaration comes from, and before repeating a figure a pack gave you: a community pack has not been read by an accountant, and the status says so. The article behind a single rule is on that rule itself — legal_reference on a tax or on a box — and the register is where that article can be read. It carries no copy of the law: a link that has gone quiet means the register is stale, never that the rule is wrong.",
        inputSchema: read.DescribePackInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.describePack(backend, args)));
    register('status', {
        title: 'Installation status',
        description: 'The schema version, the instance this is, how this server is connected and as whom, whether this session posts in review or in autopilot, and the companies you can see with the mode a posting meets in each. Use it first when something does not add up — an empty company list usually means the user was never invited rather than that the books are empty.',
        inputSchema: read.StatusInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async () => guard(() => read.status(backend, { inviteToRegister: options.inviteToRegister === true })));
    register('read_audit_log', {
        title: 'Audit trail',
        description: "Who changed what, and when. Every change to the configuration and reference data of a company — the chart of accounts, the journals, the taxes and the accounts they post to, the bank accounts, the contacts, the products, the financial years, the members and their roles, the country pack version — and every act that changes a state: a document posted or cancelled, an entry posted or reversed, a payment booked, matched or unmatched, a financial year closed or reopened. Filter by table, by natural key, by user, by act, or by date range. The ledger itself is not in here: a posted entry is immutable and is corrected by a reversal, so what is recorded is the act of posting and never the lines. Read-only, and there is no tool that writes it: the trail is append-only and even the operator cannot edit a row.",
        inputSchema: read.ReadAuditLogInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.readAuditLog(backend, args)));
    // ------------------------------------------------------------------- write
    register('search_products', {
        title: 'Find a product',
        description: 'The catalogue of a company: what it sells and buys, with the code, the unit, the price, the account each books to and the tax each carries. Search it before writing a line by hand — a product fills in the text, the price, the account and the tax, and keeps two invoices for the same thing consistent. Retired products are left out unless you ask for them.',
        inputSchema: read.SearchProductsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.searchProducts(backend, args)));
    register('create_product', {
        title: 'Add a product',
        description: 'Adds an item to the catalogue: a code unique in the company, a name, a unit, a price, and optionally the account and the tax a sale or a purchase of it carries. It changes nothing already booked — a product is what a new line is filled in from, never a rule applied to the past. Search first: a second code for the same thing is how a price list stops being one.',
        inputSchema: write.CreateProductInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.createProduct(backend, args)));
    register('update_product', {
        title: 'Change a product',
        description: "Changes a catalogue row — its name, price, unit, account, tax — or retires it with active: false. Documents already written keep the text, the price and the account they were invoiced with; an invoice is a statement about the day it was raised, and this tool cannot rewrite one. Retiring is the way to withdraw something: deleting is refused while any line still points at it.",
        inputSchema: write.UpdateProductInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.updateProduct(backend, args)));
    register('create_contact', {
        title: 'Create a contact',
        description: 'Adds a customer, supplier or other third party to a company. Search first: a duplicate contact splits a customer account in two and the aged balance stops making sense. payment_terms_days drives the due date a posted invoice gets when none is given. Next: create_document with the id it returns.',
        inputSchema: write.CreateContactInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.createContact(backend, args)));
    register('merge_contacts', {
        title: 'Merge two contacts of one company',
        description: 'One party created twice — two spellings of one customer, two imports of one supplier: everything that names the absorbed contact names the kept one afterwards, in one transaction — posted ledger lines and issued documents included, statement lines, payments, branches, files and learned motifs — and the kept contact\'s empty fields (VAT number, IBAN, address, email…) are filled from the absorbed one without overwriting any. The absorbed contact is retired, never deleted, and no row may name it again. No amount, account, date or tax box moves, and there is no unmerge. Refused by name: unknown_contact (also a contact of another company), same_contact, already_merged, different_identifiers (two different VAT or registration numbers are two parties), matching_across_parties, not_allowed. suggest_duplicate_contacts proposes the pairs. Show the user the two contacts side by side with search_contacts and ask which one to keep before calling it; never decide that two contacts are one yourself.',
        inputSchema: write.MergeContactsInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.mergeContacts(backend, args)));
    register('create_document', {
        title: 'Create a draft invoice',
        description: 'Creates a draft invoice, credit note or quote with its lines, and returns it with the totals the database computed — never with totals you supplied. A line may name a product_code, which fills in its text, price, unit, account and tax; anything the line carries wins over that. With no product and no account_code, the account falls back to the company default and then to its country model. A tax is different: a line with none is booked as a base with no VAT box, which is not the same as 0 %. Nothing is in the ledger yet. Next: show the draft to the user; update_document_lines changes it, and post_document books it once they agree.',
        inputSchema: write.CreateDocumentInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.createDocument(backend, args)));
    register('update_document_lines', {
        title: 'Replace the lines of a draft',
        description: 'Replaces every line of a draft document with the set you give, and returns the document with its recomputed totals. Lines take product_code the same way create_document does. Drafts only: a posted document is never edited; cancel_document undoes it with a credit note.',
        inputSchema: write.UpdateDocumentLinesInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.updateDocumentLines(backend, args)));
    register('post_document', {
        title: 'Post a document to the ledger',
        description: 'Books a draft document: base lines, VAT lines from the tax configuration, and the customer or supplier counterpart, numbered and posted. A posted entry is never edited; a mistake is undone by cancel_document, which puts the document back to draft only where its country allows it and nothing has left, and issues a credit note otherwise. The database decides whether you may, from the company\'s agent_posting (get_company) and this session\'s choice: in review, the default, only once a person has approved this draft as it stands (ekwo doc approve, or the web application) — refused with approval_required otherwise, and again if the draft changed after the approval; in autopilot, directly, within your rights; autopilot_forbidden where the session asked for autopilot and the company allows review only. Either way the posting is recorded on the audit trail as an agent\'s, with the mode and the session. dry_run: true is always allowed and is what to show the user before they approve.' +
            sessionPosting(backend) +
            ' It refuses a locked period, a tax that is not in force, and a header total that disagrees with the lines. Next: get_document shows the entry it wrote, and record_payment books the money when it moves.',
        inputSchema: write.PostDocumentInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.postDocument(backend, args)));
    register('accept_document', {
        title: 'Record that a quote was accepted',
        description: "Records on a sale quote or a purchase order that the other party accepted it: accepted_at (now, or the moment the user gives) and accepted_by, who accepted. A dated fact on the document — nothing is booked — and its quote_status becomes accepted. Where the crm module holds a deal that carries this quote, the deal is won by the database itself, and its party becomes a customer. Refused by name on an invoice (document_not_answerable), on a declined quote (document_already_answered: undo_document_answer first), for a moment to come (answer_in_the_future). The database holds you to the company's agent_posting as for a posting: in review, only once a person approved the quote as it stands (approval_required otherwise); in autopilot, directly; recorded on the audit trail as an agent's. Ask the user before calling it." +
            sessionPosting(backend),
        inputSchema: write.AcceptDocumentInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.acceptDocument(backend, args)));
    register('decline_document', {
        title: 'Record that a quote was declined',
        description: "Records on a sale quote or a purchase order that the other party declined it: declined_at, now or the moment the user gives. Nothing is booked; its quote_status becomes declined. Where the crm module holds a deal that carries this quote and no other quote of that deal is still alive, the deal is lost. Refused by name on an invoice (document_not_answerable), on an accepted quote (document_already_answered: undo_document_answer first), for a moment to come (answer_in_the_future). Held to the company's agent_posting as a posting is (approval_required in review without a person's approval). Ask the user before calling it." +
            sessionPosting(backend),
        inputSchema: write.DeclineDocumentInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.declineDocument(backend, args)));
    register('undo_document_answer', {
        title: 'Take back the answer recorded on a quote',
        description: 'Takes back an acceptance or a refusal recorded on a sale quote or a purchase order by mistake: the quote is unanswered again, and its quote_status is sent, expired or draft as its facts say. A deal of the crm module that the answer had won or lost opens again at the stage it was at. Refused on a quote with no answer (document_not_answered). Held to the company\'s agent_posting as a posting is. Ask the user before calling it.' +
            sessionPosting(backend),
        inputSchema: write.UndoDocumentAnswerInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.undoDocumentAnswer(backend, args)));
    register('cancel_document', {
        title: 'Undo a posted invoice',
        description: "Undoes a posted sale or purchase invoice in one call, the one way its country and its facts allow, and says which in undone_by. 'draft': the country's posted_edit_policy lets a posted document go back to draft and nothing about this one has left — never sent nor on Peppol, not paid, not declared, its period open and, where numbering is gapless, its number the last one drawn; its entry is taken away, its number given back, and it is a draft to correct and post again. 'credit_note' otherwise, with the reason in why: its credit note — the same lines, taxes, accounts, contact, currency and rate — is issued naming it, posted and matched against it, and the invoice is cancelled, payment state reversed; the invoice keeps its number and its entry. Tell the user which it was. A date, or credit_note: true, asks for the credit note outright. Dated on the invoice's booking day unless you give a date; refused by name when that period is locked or closed (reversal_date_needed), and then you ask the user for a date rather than choosing one. Refused for a draft, a credit note, an invoice already cancelled or credited, and one that is paid in part or in full — the payment is unmatched first with unreconcile, and only when the user says so. Where you post in review, the credit note is a posting nobody approved, so that way is refused (approval_required) and the user cancels it themselves. Ask the user before calling it." + sessionPosting(backend),
        inputSchema: write.CancelDocumentInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.undoDocument(backend, args)));
    register('reverse_entry', {
        title: 'Reverse a posted entry',
        description: "Undoes a posted entry in one call: writes its mirror in the same journal — every line on the other side — naming it, posts it under the next number, and matches the two. The original keeps its number and its lines. Dated on the original's day unless you give a date; refused by name when that period is locked or closed (reversal_date_needed), and then you ask the user for a date rather than choosing one. Refused for an entry a document wrote (use cancel_document), the entries of a close (reopen_fiscal_year), an opening, the entry of a payment, a bank transaction, a module or a matching, an entry already reversed or that is itself a reversal, and a matched entry — unmatch it first with unreconcile, and only when the user says so. Ask the user before calling it.",
        inputSchema: write.ReverseEntryInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.reverseEntry(backend, args)));
    register('record_payment', {
        title: 'Record a payment',
        description: 'Records money in or out, books it (bank against the customer or supplier account) and, unless you say otherwise, matches it against that contact\'s oldest open invoices up to the amount paid. Matching is what makes an invoice count as paid. The entry it produces cannot be unposted, though the matching can be undone with unreconcile.',
        inputSchema: write.RecordPaymentInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.recordPayment(backend, args)));
    register('reconcile', {
        title: 'Match two ledger lines',
        description: 'Matches a debit line against a credit line on the same reconcilable account, for an amount, defaulting to the smaller of the two open amounts. Use it to settle an invoice against a payment by hand. Matching changes no account and stays possible after a period is locked.',
        inputSchema: write.ReconcileInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.reconcile(backend, args)));
    register('unreconcile', {
        title: 'Undo a matching',
        description: 'Removes one matching, putting the residual back on both lines. The entries themselves are untouched. It is what cancel_document and reverse_entry ask for first when what they would undo is matched.',
        inputSchema: write.UnreconcileInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.unreconcile(backend, args)));
    register('set_line_contact', {
        title: 'Name the contact of a ledger line',
        description: 'Names the contact of an open line on a receivable or payable account that names nobody — the open items of books imported line by line — once, from nothing to a contact of the same company, and learns the label as a motif of that contact for the next suggestion. Refused by name: unknown_line, line_not_posted, line_has_contact (a posted counterparty is corrected by reversing the entry), line_matched (unmatch it first, and only when the user says so), line_not_third_party, unknown_contact. Changes no amount, account or tax box. Show the user the candidates of suggest_line_contacts and ask which one before calling it; never pick one yourself.',
        inputSchema: write.SetLineContactInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.setLineContact(backend, args)));
    register('leave_line_unnamed', {
        title: 'Leave a ledger line without a contact',
        description: 'Records that an open line on a receivable or payable account names nobody on purpose — a cash difference, a one-off refund — with the user\'s reason: suggest_line_contacts no longer proposes it. The line does not move and stays an open item. Refused by name: unknown_line, not_allowed, reason_required, reason_too_long, line_not_posted, line_has_contact, line_not_third_party, line_left_unnamed. Ask the user before calling it.',
        inputSchema: write.LeaveLineUnnamedInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.leaveLineUnnamed(backend, args)));
    register('undo_leave_line_unnamed', {
        title: 'Take back leaving a line without a contact',
        description: 'Takes back leave_line_unnamed: the line is proposed a contact again. Refused by name: unknown_line, not_allowed, line_not_left_unnamed.',
        inputSchema: write.UndoLeaveLineUnnamedInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.undoLeaveLineUnnamed(backend, args)));
    register('reconcile_many', {
        title: 'Match several ledger lines together',
        description: 'Matches several lines together in one call — one payment against several invoices, one invoice against several instalments — when their open debits and credits are equal to the cent: posted lines of one company, one reconcilable account, one counterparty (a line naming nobody is attributed by the matching), in the company\'s currency. Paired oldest first through reconcile, under one letter. Refused by name, and never settled in part: reconcile_unbalanced gives the difference. Show the user the lines and ask before calling it.',
        inputSchema: write.ReconcileManyInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.reconcileMany(backend, args)));
    register('reconcile_with_difference', {
        title: 'Match ledger lines and book a small difference',
        description: 'Matches the same set of lines as reconcile_many when their totals differ by no more than the company\'s tolerance: posts an entry that books the difference on the same account and counterparty against the account the pack gives for the reason (matching_difference_options: rounding, exchange_difference), then matches everything under one letter. Refused by name: difference_above_tolerance, no_difference, unknown_difference_reason, no_account_for_reason, and every refusal of reconcile_many. The entry is posted; unreconcile of the matching of the difference line takes it back. Show the user the difference and the account, and let them choose the reason, before calling it.',
        inputSchema: write.ReconcileWithDifferenceInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.reconcileWithDifference(backend, args)));
    register('settle_from_statement', {
        title: 'Settle a bank statement line',
        description: 'Books a pending statement line as the payment it is and matches it against the documents or open items named, in one entry: the bank, the customer or supplier account, and the extra lines the money is net of — the fee a payment provider kept from a payout, the charges of a bank, each on the account and with the tax the user names. A payout of 97.00 for an invoice of 100.00 settles the invoice in full with an extra line of 3.00 on a fee account. amounts says how much settles each item; left out, oldest first. The line has to balance to the cent (settlement_unbalanced otherwise, with the difference). Extra lines alone settle a bank charge. One counterparty per line. The entry cannot be unposted. Ask the user before calling it, and for the fee account and its tax.',
        inputSchema: write.SettleFromStatementInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.settleFromStatement(backend, args)));
    register('create_bank_account', {
        title: 'Add a bank account',
        description: "Registers a bank account of the company from its identifier — an IBAN, an ABA routing number and an account number, a sort code and an account number, whatever the banks of the company's country use; the pack of the country says which, and it is checked — and wires it to the bank journal and to the ledger account behind it — both of which the country template has already chosen, so neither has to be given. Running it twice with the same identifier returns the one that exists rather than creating a second; a name another account already carries is refused (bank_account_exists), so ask the user for a label when a company has several accounts. The schema's create_bank_account() does the work, the same function a web application calls. Do this once per account: until a company has one, an invoice carries no account to pay into and record_payment can only book on the journal's default account.",
        inputSchema: write.CreateBankAccountInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.createBankAccount(backend, args)));
    register('list_bank_accounts', {
        title: 'Bank accounts',
        description: 'The bank accounts of a company, with their identifier and the scheme it is written in, the journal they book through, the ledger account behind each and statement_profile, the lay-out of its CSV statements when one is kept (null otherwise). Read it before recording a payment on a particular account, and to find out whether the company has one at all.',
        inputSchema: read.ListBankAccountsInput.shape,
        annotations: { readOnlyHint: true, openWorldHint: false },
    }, async (args) => guard(() => read.listBankAccounts(backend, args)));
    register('update_bank_account', {
        title: 'Change a bank account',
        description: "Keeps on a bank account the profile of its CSV statements — the delimiter, the date format, the decimal mark and which column is the date, the amount, the balance — so that import_bank_statement reads a CSV of it without csv_profile, for every member of the company. null forgets it. An import given csv_profile keeps it there too, so this is for describing the lay-out before the first file, or correcting it. A profile no file could be read with is refused (invalid_profile). Nothing is imported or booked.",
        inputSchema: write.UpdateBankAccountInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.updateBankAccount(backend, args)));
    register('create_bank_transaction', {
        title: 'Add a bank transaction',
        description: 'Records one statement line by hand, for an installation without a bank feed. `amount` is signed: positive is money in. It books nothing — the line waits as pending until a payment is recorded.',
        inputSchema: write.CreateBankTransactionInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.createBankTransaction(backend, args)));
    register('import_bank_statement', {
        title: 'Import a bank statement',
        description: 'Reads a bank statement file and writes its statements and lines. `format` says what the file is — `camt.053` (the ISO 20022 XML statement), `coda`, `cfonb120`, or `csv` with the account it is of (`bank_account_id`) and the profile of its columns (`csv_profile`, kept on the account once an import with it succeeds, and read from there when left out), which are the ones this server reads today — and `content` is the file as text. It is never guessed from the content. It books nothing: every line waits as pending, to be settled afterwards. Safe to repeat: the same file imported twice creates nothing the second time, and a statement overlapping an earlier one imports only the new lines. Refused by name, with nothing written: an account the company does not have (create it first with create_bank_account — an import never creates one), a statement whose opening balance plus lines is not its closing balance, a line in another currency. Signalled in `warnings`, not refused: an opening balance that is not the previous closing one, which means a statement is missing.',
        inputSchema: write.ImportBankStatementInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.importBankStatement(backend, args)));
    register('create_company', {
        title: 'Create a company',
        description: 'Creates a company on a country pack: its chart of accounts, its journals and its taxes are copied in, its first financial year is opened on the month that country opens one on, and you become its first member. Creating a company is an instance-level act — it needs an instance administrator, and being one is not the same as being on anybody\u2019s books. Ask the user for the country rather than guessing: the wrong answer is a whole chart of accounts.',
        inputSchema: write.CreateCompanyInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.createCompany(backend, args)));
    register('update_company_profile', {
        title: 'Change the company itself',
        description: 'Changes what a company says about itself on its documents: the names it goes by, its address and identifiers, its logo and the colour, logo side and typeface of its invoice PDF, whether its invoices print the late payment mention of its country, the pattern of its document numbers, its stated capital, its activity code and the bank account customers are asked to pay into — and agent_posting, how agents post its documents, which you only ever make stricter. Only the fields you name change. It touches nothing in the ledger, and it needs company.write — the owner preset, not the accountant one.',
        inputSchema: write.UpdateCompanyProfileInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.updateCompanyProfile(backend, args)));
    register('set_number_prefix', {
        title: 'Change what a journal prints in its numbers',
        description: "Sets the prefix one journal prints in place of {CODE} in the numbers it draws — FAC instead of SAL, for instance — or puts its code back with null. The journal keeps its code and its counter: the series goes on at the next number. A prefix another journal of the company already prints is refused. The pattern around it (year, width) is the company's number_format in update_company_profile. Needs settings.write.",
        inputSchema: write.SetNumberPrefixInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.setNumberPrefix(backend, args)));
    register('set_preferences', {
        title: 'Change what this user prefers',
        description: 'Writes the signed-in user\u2019s own preferences and nobody else\u2019s. Only the fields you name change: leave one out and it is untouched, pass null and it is cleared, which puts that question back to the company and then to the country pack. It changes nothing in the books.',
        inputSchema: write.SetPreferencesInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.setPreferences(backend, args)));
    register('invite_member', {
        title: 'Invite somebody into a company',
        description: 'Invites an address into a company with a preset — viewer reads, client reads and hands pieces over, accountant keeps the books, owner also administers — and any capability granted on top of it. It returns a token once and stores only its hash, so hand the token to the person you invited: they accept it themselves, signed in with that address. It does not send an e-mail, and it does not create an account. Inviting the same address again withdraws the invitation that was pending.',
        inputSchema: write.InviteMemberInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.inviteMember(backend, args)));
    register('create_api_key', {
        title: 'Issue a key to a machine',
        description: 'Issues a key so a script — a nightly import, a till, a bank feed — can work in one company without a person signing in. It carries an explicit list of capabilities and nothing else, it can never reach another company, and it cannot hold a capability you do not hold yourself — at issuance and at every use: if you lose a capability or leave the company, the key loses it too. Its posting_mode is fixed now and never raised afterwards: review by default, autopilot only when the user asks for it in so many words. The secret comes back once and is stored only as a hash: show it to the user and say it cannot be read back. Prefer this to sharing anybody\u2019s password, and never suggest a service key.',
        inputSchema: write.CreateApiKeyInput.shape,
        // Destructive: a key reaches the books without a person, until it is withdrawn.
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.createApiKey(backend, args)));
    register('revoke_api_key', {
        title: 'Withdraw a machine key',
        description: 'Stops a key working, now and for good. There is no un-withdraw: a secret that has been out of the building is issued again rather than brought back. Whatever the machine was doing with it stops, so say so before calling it.',
        inputSchema: write.RevokeApiKeyInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.revokeApiKey(backend, args)));
    register('revoke_invitation', {
        title: 'Withdraw an invitation',
        description: 'Withdraws an invitation that has not been accepted, so its token stops working. An invitation that has already become a membership is refused: a member is taken out with remove_member.',
        inputSchema: write.RevokeInvitationInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.revokeInvitation(backend, args)));
    register('remove_member', {
        title: 'Take somebody out of a company',
        description: 'Removes a member from a company, now: they stop reading and writing its books. Needs members.manage, except to leave a company yourself. The last owner of a company is refused, themself included; make somebody else owner with set_member_role first. Their pending invitations are not touched. Say who is being removed before calling it.',
        inputSchema: write.RemoveMemberInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.removeMember(backend, args)));
    register('set_member_role', {
        title: 'Move a member to another preset',
        description: 'Changes the preset of a member of a company — viewer reads, client reads and hands pieces over, accountant keeps the books, owner also administers. Needs members.manage. The capabilities granted or revoked on that member so far are cleared, and the ones you pass are granted on top of the new preset, the way an invitation writes a new member. The last owner of a company cannot be demoted: promote the successor first.',
        inputSchema: write.SetMemberRoleInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.setMemberRole(backend, args)));
    register('share_document', {
        title: 'Publish a document behind a link',
        description: 'Publishes a posted sales invoice, credit note or quote behind a link the customer opens without an account and without a password: the token in the url is the whole secret. It returns that token once and stores only its hash, so give the url to the customer and say it cannot be read back. The page shows the document as it was sent and what is still owed on it today, so the link stays worth opening after a payment. A purchase document is refused — it is a third party\u2019s own document — and so is a draft. A link is never edited: to change when it expires, withdraw it and make another.',
        inputSchema: write.ShareDocumentInput.shape,
        // Destructive: the document leaves the ledger for whoever holds the link.
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
    }, async (args) => guard(() => write.shareDocument(backend, args)));
    register('revoke_share', {
        title: 'Withdraw a published link',
        description: 'Stops a link working, now and for good. Whoever holds it sees exactly what they would see for a link that never existed. There is no un-withdraw: a secret that has been out of the building is issued again rather than brought back, so say so before calling it.',
        inputSchema: write.RevokeShareInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.revokeShare(backend, args)));
    register('pin_accounts', {
        title: 'Pin accounts to the working chart',
        description: 'Adds accounts to the working chart of a company, so list_accounts offers them whether or not anything has been booked on them. Pass pinned: false to take one back out. Pinning is display and nothing else: an unpinned account may still be booked on, and a pinned one is still hidden once it is deprecated.',
        inputSchema: write.PinAccountsInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.pinAccounts(backend, args)));
    register('lock_period', {
        title: 'Lock a period',
        description: 'Moves the accounting lock date, the VAT lock date, or both. After this, nothing can be booked, changed or deleted on or before that date — including corrections you may want later. Only an owner of the company may do it. Always ask the user first, and never lock a period you have just posted into without being told to.',
        inputSchema: write.LockPeriodInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.lockPeriod(backend, args)));
    register('import_books', {
        title: 'Import books from another system',
        description: write.IMPORT_BOOKS_DESCRIPTION,
        inputSchema: write.ImportBooksInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
    }, async (args) => guard(() => write.importBooksTool(backend, args)));
    register('opening_balance', {
        title: 'Import an opening balance',
        description: 'Turns the trial balance of whatever kept the books before into the opening entry of a fiscal year, on the opening journal, dated on its first day — or on opening_date, the day inside the year the books were taken over. Lines are {account_code, debit, credit}; total debit must equal total credit. Balance-sheet accounts only, unless allow_result_accounts is set, which is for taking books over in the middle of a year. items are the invoices and credit notes still open that day, each posted as a document with its number, payment reference and due date, so a bank statement finds it; the items of an account replace its line and must add up to it. A year holds one opening: a second call is refused rather than added to.',
        inputSchema: write.OpeningBalanceInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.openingBalance(backend, args)));
    register('close_fiscal_year', {
        title: 'Close a fiscal year',
        description: 'Closes a year: the result of the year leaves the income statement the way the country model says — straight to retained earnings, into a current-year result account, or through the appropriation accounts — every income and expense account goes back to zero, and the year stops accepting entries. The close can be undone with reopen_fiscal_year; final_close in the answer says whether the country also requires a final close, which cannot, and by when. Refused while the year holds a draft entry, while an earlier year with entries is open, or when a later year is already closed. It never writes what a general meeting decides to do with the result. Always ask the user before calling it.',
        inputSchema: write.CloseFiscalYearInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.closeFiscalYear(backend, args)));
    register('reopen_fiscal_year', {
        title: 'Re-open a closed fiscal year',
        description: 'Undoes an ordinary close, to correct the year: the entries it wrote are reversed, never deleted, and the year accepts entries again. Entries already posted in later years do not prevent it and are not touched — they read this year from the ledger, so closing it again carries the corrected result to them. Refused for a year under a final close (fiscal_year_finally_closed), for everybody, and while a later year is closed (later_fiscal_year_closed): reopen that one first. Always ask the user before calling it.',
        inputSchema: write.ReopenFiscalYearInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.reopenFiscalYear(backend, args)));
    register('close_fiscal_year_finally', {
        title: 'Close a fiscal year for good',
        description: 'The final close: a year already closed is frozen, and from then on nobody can reopen it or change it — not the owner, not an accountant, not the operator. Refused on an open year (fiscal_year_not_closed) and while a closed year before it is not finally closed. Whether the country requires it, and by when, is final_close in the answer of close_fiscal_year. Irreversible: call it only when the user has asked for this specific year to be closed for good.',
        inputSchema: write.CloseFiscalYearFinallyInput.shape,
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
    }, async (args) => guard(() => write.closeFiscalYearFinally(backend, args)));
    // --------------------------------------------------------------- resources
    server.registerResource('chart-of-accounts', new ResourceTemplate('ekwo://companies/{companyId}/chart', { list: undefined }), {
        title: 'Chart of accounts',
        description: 'The whole chart of accounts of a company, as JSON, for when a search is not enough.',
        mimeType: 'application/json',
    }, async (uri, variables) => {
        const companyId = String(variables['companyId']);
        const accounts = await backend.select({
            table: 'accounts',
            columns: columns.ACCOUNT,
            where: [{ column: 'company_id', op: 'eq', value: companyId }],
            order: [{ column: 'code' }],
        });
        return {
            contents: [
                {
                    uri: uri.href,
                    mimeType: 'application/json',
                    text: JSON.stringify({ company_id: companyId, accounts }, null, 2),
                },
            ],
        };
    });
    server.registerResource('taxes', new ResourceTemplate('ekwo://companies/{companyId}/taxes', { list: undefined }), {
        title: 'Taxes',
        description: 'The taxes of a company with their rates, validity periods, kind and recoverability, and the ledger account and declaration box each posting feeds. A tax_on_base posting names no account: its share of the tax lands on the account of the document line, which is how non-deductible VAT is booked.',
        mimeType: 'application/json',
    }, async (uri, variables) => {
        const companyId = String(variables['companyId']);
        const taxes = await backend.select({
            table: 'taxes',
            columns: columns.TAX,
            where: [{ column: 'company_id', op: 'eq', value: companyId }],
            order: [{ column: 'code' }],
        });
        const postings = await backend.select({
            table: 'tax_postings',
            columns: [
                'id',
                'tax_id',
                'document_kind',
                'posting_type',
                'factor_percent::text',
                'account_id',
                'declaration_box',
                // Every box this one amount is printed in, not only the one the
                // posting is known by: a client reading the first alone would
                // under-report a form that prints a figure in two boxes at once.
                'declaration_boxes',
                'box_factor_percent::text',
                'report_code',
                'sequence',
            ],
            where: [{ column: 'company_id', op: 'eq', value: companyId }],
            order: [{ column: 'sequence' }],
        });
        return {
            contents: [
                {
                    uri: uri.href,
                    mimeType: 'application/json',
                    text: JSON.stringify({
                        company_id: companyId,
                        taxes: taxes.map((tax) => ({
                            ...tax,
                            postings: postings.filter((posting) => posting['tax_id'] === tax['id']),
                        })),
                    }, null, 2),
                },
            ],
        };
    });
    // ----------------------------------------------------------------- prompts
    server.registerPrompt('close_month', {
        title: 'Close a month',
        description: 'The checklist for closing a month: drafts, unmatched bank lines, the balance, the VAT.',
        argsSchema: {
            company_id: z.string().describe('The company to close.'),
            from: z.string().describe('First day of the month, as YYYY-MM-DD.'),
            to: z.string().describe('Last day of the month, as YYYY-MM-DD.'),
        },
    }, ({ company_id, from, to }) => ({
        messages: [
            {
                role: 'user',
                content: {
                    type: 'text',
                    text: [
                        `Close the month from ${from} to ${to} for company ${company_id}. Work through this in order and report what you find; change nothing without asking.`,
                        '',
                        `1. Documents still in draft: list_documents with state "draft" over the period. Each one is either waiting to be posted or waiting to be deleted — say which, do not decide.`,
                        `2. Bank lines still pending: list_bank_transactions. For each, say what it looks like (a customer payment, a supplier payment, something else) and whether a matching invoice exists.`,
                        `3. The trial balance over the period: trial_balance. Check that the debit and credit totals agree, and point out any suspense account that carries a balance.`,
                        `4. The VAT: vat_return over the period. Report the boxes and the balance due or refundable.`,
                        `5. What is still open: aged_balance at ${to}, receivable and payable.`,
                        '',
                        'Finish with a short list of what has to happen before this month can be locked, and ask before locking anything.',
                    ].join('\n'),
                },
            },
        ],
    }));
    server.registerPrompt('prepare_vat_return', {
        title: 'Prepare a VAT return',
        description: 'Pull the boxes for a period and check them against the ledger before anything is filed.',
        argsSchema: {
            company_id: z.string().describe('The company to prepare the return for.'),
            from: z.string().describe('First day of the period, as YYYY-MM-DD.'),
            to: z.string().describe('Last day of the period, as YYYY-MM-DD.'),
        },
    }, ({ company_id, from, to }) => ({
        messages: [
            {
                role: 'user',
                content: {
                    type: 'text',
                    text: [
                        `Prepare the VAT return of company ${company_id} for ${from} to ${to}.`,
                        '',
                        '1. vat_return for the period. Report every box with its amount, and say which ones are computed from the others.',
                        '2. Check that nothing is missing: list_documents with state "draft" over the period. A draft invoice is in no box, and that is usually the error.',
                        '3. Tie the VAT accounts back to the ledger: general_ledger on the VAT payable and VAT recoverable accounts for the period, and compare with the boxes.',
                        '4. If the company supplied anything to another Member State: ec_sales_list for the period, and check its total against the European Union boxes of the return. Name every line it flags — a customer with no VAT number is a statement that cannot be filed.',
                        '5. Say what is due or refundable, and what would have to be corrected before filing.',
                        '',
                        'This prepares figures. It files nothing, and it changes nothing in the books.',
                    ].join('\n'),
                },
            },
        ],
    }));
    // ------------------------------------------------------------------ modules
    //
    // The socle's tools are written out above because they are the socle. A
    // module's are declared as data and registered here, so adding a module to
    // this server is adding a toolset to `tools/modules.ts` and nothing else —
    // the same shape the registry table takes in the database. Its prompts come
    // with its tools, under the same prefix.
    for (const toolset of toolsetsFor(options.modules ?? [])) {
        for (const tool of toolset.tools) {
            register(`${toolset.prefix}_${tool.verb}`, {
                title: tool.title,
                description: tool.description,
                inputSchema: tool.input.shape,
                // Said by the module, the way the socle's tools say it above: a
                // card or a note is added, a depreciation booked or a file sent
                // destroys. See packages/mcp/TOOL_DESIGN.md.
                annotations: annotationsFor(tool.effect, {
                    ...(tool.idempotent === undefined ? {} : { idempotent: tool.idempotent }),
                    ...(tool.openWorld === undefined ? {} : { openWorld: tool.openWorld }),
                }),
            }, async (args) => guard(() => tool.run(backend, args, {
                ...(options.einvoiceTransport === undefined ? {} : { einvoiceTransport: options.einvoiceTransport }),
                ...(options.fiscalSystem === undefined ? {} : { fiscalSystem: options.fiscalSystem }),
            })));
        }
        for (const prompt of toolset.prompts ?? []) {
            server.registerPrompt(`${toolset.prefix}_${prompt.name}`, {
                title: prompt.title,
                description: prompt.description,
                argsSchema: Object.fromEntries(Object.entries(prompt.args).map(([name, description]) => [name, z.string().describe(description)])),
            }, (args) => ({
                messages: [{ role: 'user', content: { type: 'text', text: prompt.text(args) } }],
            }));
        }
    }
    // ------------------------------------------------------------- on demand
    //
    // Registered last, so that they see every tool above. A session that asked
    // for all of them never sees these two.
    if (options.tools === 'on_demand') {
        register('search_tools', {
            title: 'Search tools',
            description: 'Finds the tools of this server by what they do: give a word or two of the task — "fixed asset", "contract", "bank statement", "budget" — and get the matching tools, best first, each with its title, the first sentence of its description, whether it reads, adds or destroys (effect), and whether it is loaded in this session. Without a query, every tool. It changes nothing; load_tools adds the ones you need.',
            inputSchema: {
                query: z.string().max(200).optional().describe('Words of the task. Left out, every tool is listed.'),
                effect: z.enum(TOOL_EFFECTS).optional().describe('Only the tools that read, that add, or that are destructive.'),
                limit: z.number().int().min(1).max(200).optional().describe('At most this many, 20 by default.'),
            },
            annotations: { readOnlyHint: true, openWorldHint: false },
        }, async (args) => guard(async () => searchTools(tools, args.query, args.effect, args.limit ?? 20)));
        register('load_tools', {
            title: 'Load tools',
            description: 'Adds the tools you name to this session, by the names search_tools gave. The tool list changes and your client is told so; call them as any other. Answers which were loaded, which were already there and which this server does not have. It changes the tools you see, never the books, and loading a tool gives it no right the database would refuse.',
            inputSchema: {
                names: z.array(z.string().min(1).max(64)).min(1).max(50).describe('The names of the tools to add, as search_tools lists them.'),
            },
            annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
        }, async (args) => guard(async () => loadTools(tools, args.names)));
        startOnDemand(tools);
    }
    return server;
}
//# sourceMappingURL=server.js.map