@tethlo/mcp-for-invoice-ninja 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tethlo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,142 @@
1
- # Temporary Holding Version
1
+ **Unofficial.** Not affiliated with, endorsed by or sponsored by Invoice Ninja. Invoice Ninja is a trademark of its owner.
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # Tethlo MCP server for Invoice Ninja (unofficial demo)
4
+
5
+ Run your invoicing from Claude, ChatGPT or any MCP client: "How much are we owed, and who should I
6
+ chase first?", "Bill Bluebird 450 for the logo animation", "Acme just wired 1,000 for invoice 0041".
7
+
8
+ [Invoice Ninja](https://invoiceninja.com) is an open-source invoicing, quotes and payments app for
9
+ freelancers and small businesses (hosted at invoicing.co or self-hosted). This server exposes it to
10
+ AI agents through the [Model Context Protocol](https://modelcontextprotocol.io).
11
+
12
+ > **Demo.** This server is a demonstration of how Tethlo builds MCP servers. It is tested and usable, but it has
13
+ > fewer guarantees than the connectors in this repository (no read-only switch, smaller scope).
14
+
15
+ ## Why this server is different
16
+
17
+ - **Tools built for the job, not for the endpoints.** 8 tools cover the daily invoicing loop
18
+ (find, bill, send, get paid, chase) instead of mirroring the hundreds of API endpoints.
19
+ `get_receivables_summary` computes aging buckets and top debtors that the API does not return directly.
20
+ - **Plain words work.** Clients by name, part of the name or contact email; invoices by number
21
+ (`0042`, `#0042`) or id. Ambiguous matches return the candidates with their emails.
22
+ - **Short, structured answers.** Status derived for humans (`overdue`, `partial`, `draft`…), days
23
+ overdue, rounded amounts, compact JSON also sent as `structuredContent`.
24
+ - **Safe money handling.** Invoices are drafts unless `send: true`; payments cannot exceed the
25
+ balance; nothing is sent to a client without an email; write requests are never retried
26
+ automatically (no duplicate invoices or payments).
27
+ - **Errors an agent can act on.** Validation errors become one readable line; a 403 explains the
28
+ hosted plan requirement.
29
+ - **Measured.** 10-task agent evaluation, checked offline in CI and runnable live against Claude.
30
+
31
+ ## Tools
32
+
33
+ | Tool | What it does |
34
+ |---|---|
35
+ | `find_clients` | Search customers by name or email, with balance and paid to date; or list who owes money. |
36
+ | `create_client` | Add a customer with a primary contact; returns the existing one instead of a duplicate. |
37
+ | `list_invoices` | Invoices by client and status (draft, sent, partial, unpaid, overdue, paid), with totals and days overdue. |
38
+ | `get_invoice` | One invoice: client email, line items, totals, balance, status, portal link. |
39
+ | `create_invoice` | Bill a client from line items; draft by default, or create and email it. |
40
+ | `send_invoice` | Email an invoice, or a reminder (reminder1/2/3 templates). |
41
+ | `record_payment` | Record money received against an invoice (full balance by default). |
42
+ | `get_receivables_summary` | Total outstanding and overdue, aging buckets, top debtors, oldest overdue invoices. |
43
+
44
+ ## Install
45
+
46
+ Requirements: Node.js 22.18 or later and an Invoice Ninja API
47
+ token (Settings > Account Management > API Tokens). On the hosted service, API access needs the Pro or
48
+ Enterprise plan; a self-hosted install is free.
49
+
50
+ ```bash
51
+ npx -y @tethlo/mcp-for-invoice-ninja
52
+ ```
53
+
54
+ The server reads `INVOICENINJA_API_TOKEN` from its environment: each user brings their own credentials.
55
+
56
+ ### Local (stdio): Claude Desktop, Claude Code, Cursor
57
+
58
+ ```json
59
+ {
60
+ "mcpServers": {
61
+ "invoiceninja": {
62
+ "command": "npx",
63
+ "args": ["-y", "@tethlo/mcp-for-invoice-ninja"],
64
+ "env": { "INVOICENINJA_API_TOKEN": "your-token" }
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ Claude Code: `claude mcp add invoiceninja -e INVOICENINJA_API_TOKEN=your-token -- npx -y @tethlo/mcp-for-invoice-ninja`
71
+
72
+ ### Remote (Streamable HTTP): ChatGPT, Claude.ai connectors, hosted agents
73
+
74
+ ```bash
75
+ npm run start:http # POST http://127.0.0.1:3000/mcp, GET /health
76
+ ```
77
+
78
+ From a clone of the repository (`cd packages/invoice-ninja`). Stateless Streamable HTTP, JSON responses, one MCP server per request. Two ways to authenticate:
79
+
80
+ - **Per user**: no token on the server; each client sends its own token in `X-InvoiceNinja-Api-Token`.
81
+ - **Single tenant**: set `INVOICENINJA_API_TOKEN` and `MCP_ACCESS_TOKEN` on the server; clients send
82
+ `Authorization: Bearer <MCP_ACCESS_TOKEN>`. The server refuses to start with a token but no access token.
83
+
84
+ For a public listing (ChatGPT app directory, Claude connector directory), put OAuth 2.1 in front of
85
+ the endpoint so users sign in instead of pasting tokens (not included in this demo).
86
+
87
+ To build plain JavaScript: `npm run build` (output in `dist/`).
88
+
89
+ ## Limits
90
+
91
+ - This server only calls the API of your own Invoice Ninja account or instance; it does not host Invoice Ninja.
92
+ - No read-only switch in this demo: sending and payment tools are guarded by drafts, balance checks and no automatic retries on writes.
93
+
94
+ ## Example conversation
95
+
96
+ > **User:** How much are customers owing us, and who should I chase first?
97
+ >
98
+ > *Claude calls `get_receivables_summary` →*
99
+ > `{"open_invoices":3,"total_outstanding":5400,"total_overdue":3700,"aging":{"not_due":1700,"1_30":0,"31_60":2500,"61_90":0,"over_90":1200},"top_debtors":[{"client":"Acme Corp","owed":4200},{"client":"Bluebird Studio","owed":1200}],"oldest_overdue":[{"number":"0043","client":"Bluebird Studio","days_overdue":102},{"number":"0041","client":"Acme Corp","days_overdue":54}]}`
100
+ >
101
+ > **Claude:** You are owed 5,400, of which 3,700 is overdue.
102
+ > Start with **Bluebird Studio**: invoice 0043 (1,200) is 102 days late. Then **Acme Corp**:
103
+ > invoice 0041 (2,500) is 54 days late. Acme's other open invoice (0042) is not due yet.
104
+ >
105
+ > **User:** Send Acme a polite reminder for 0041.
106
+ >
107
+ > *Claude calls `send_invoice {"invoice":"0041","template":"reminder1"}`* → **Claude:** Reminder sent to jane@acme.test.
108
+
109
+ (Data from the test fixtures.)
110
+
111
+ ## Tests and evaluation
112
+
113
+ ```bash
114
+ npm ci # at the repository root
115
+ cd packages/invoice-ninja
116
+ npm test # unit tests (fake API), stdio and HTTP transports, offline agent evaluation
117
+ npm run typecheck
118
+ npm run eval:claude # live evaluation: needs ANTHROPIC_API_KEY; tools run on the fake API, never your account
119
+ ```
120
+
121
+ - `test/fake-api.ts` imitates the Invoice Ninja v5 API (shapes from Invoice Ninja's published OpenAPI file,
122
+ simplified filters, 401/404/422 errors).
123
+ - `eval/tasks.ts` holds 10 natural-language tasks with the expected tool and arguments. Offline, the test
124
+ suite checks that each expected call solves its task and that a word-overlap router (`eval/router.ts`, no LLM)
125
+ picks the right tool from the descriptions alone.
126
+ - `eval/run-claude.ts` asks Claude (default `claude-opus-5-5`, override with `EVAL_MODEL`) to handle each task
127
+ with the real tool list, runs the call it chose on the fake API and prints the score
128
+ (correct tool and working arguments). It exits with 1 below `EVAL_MIN_SCORE` (default 0.9).
129
+
130
+ ## Disclaimer
131
+
132
+ This is an independent open-source demo by Tethlo. It is not made, reviewed or supported by Invoice Ninja.
133
+ You connect it with your own Invoice Ninja account and API credentials; your use of the Invoice Ninja API stays subject to
134
+ your agreement with Invoice Ninja. The software is provided as is, without warranty (see LICENSE).
135
+
136
+ ## License
137
+
138
+ MIT
139
+
140
+ ---
141
+
142
+ Built by Tethlo — MCP servers, ChatGPT apps and Claude connectors for B2B SaaS · https://tethlo.com
@@ -0,0 +1,125 @@
1
+ // Thin, typed client for the Invoice Ninja v5 REST API.
2
+ // Docs: https://invoiceninja.github.io/en/api-reference/ (OpenAPI: invoiceninja/invoiceninja, openapi/api-docs.yaml)
3
+ export class ApiError extends Error {
4
+ status;
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.name = "ApiError";
8
+ this.status = status;
9
+ }
10
+ }
11
+ const DEFAULT_BASE_URL = "https://invoicing.co";
12
+ function explain(status, detail) {
13
+ switch (status) {
14
+ case 401:
15
+ return "The Invoice Ninja API token is missing or invalid. Create one in Settings > Account Management > API Tokens.";
16
+ case 403:
17
+ return "Access denied. The token's user lacks this permission, or the hosted plan does not include API access (Pro or Enterprise).";
18
+ case 404:
19
+ return "Not found. It may have been deleted or archived; search again by name or number.";
20
+ case 422:
21
+ return `Invoice Ninja rejected the data: ${detail || "validation failed"}.`;
22
+ case 429:
23
+ return "Rate limited by Invoice Ninja. Wait a minute, then retry.";
24
+ default:
25
+ return status >= 500
26
+ ? `Invoice Ninja is temporarily unavailable (HTTP ${status}). Retry in a few minutes.`
27
+ : `Unexpected response from Invoice Ninja (HTTP ${status}).`;
28
+ }
29
+ }
30
+ /** Turns Laravel-style validation errors into one readable line. */
31
+ function validationDetail(body) {
32
+ const parsed = body;
33
+ if (parsed?.errors) {
34
+ return Object.entries(parsed.errors)
35
+ .map(([field, messages]) => `${field}: ${messages.join(" ")}`)
36
+ .join("; ");
37
+ }
38
+ return parsed?.message ?? "";
39
+ }
40
+ export class InvoiceNinjaApi {
41
+ #token;
42
+ #baseUrl;
43
+ #fetch;
44
+ #timeoutMs;
45
+ #retryDelayMs;
46
+ constructor(options) {
47
+ if (!options.token)
48
+ throw new ApiError(401, explain(401, ""));
49
+ this.#token = options.token;
50
+ this.#baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
51
+ this.#fetch = options.fetch ?? globalThis.fetch;
52
+ this.#timeoutMs = options.timeoutMs ?? 20_000;
53
+ this.#retryDelayMs = options.retryDelayMs ?? 1_000;
54
+ }
55
+ async #request(method, path, query = {}, body) {
56
+ const params = new URLSearchParams();
57
+ for (const [key, value] of Object.entries(query))
58
+ if (value !== undefined && value !== "")
59
+ params.set(key, String(value));
60
+ const url = `${this.#baseUrl}/api/v1${path}${params.size ? `?${params}` : ""}`;
61
+ for (let attempt = 0;; attempt++) {
62
+ let res;
63
+ try {
64
+ res = await this.#fetch(url, {
65
+ method,
66
+ headers: {
67
+ "X-API-TOKEN": this.#token,
68
+ "X-Requested-With": "XMLHttpRequest",
69
+ Accept: "application/json",
70
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
71
+ },
72
+ body: body === undefined ? undefined : JSON.stringify(body),
73
+ signal: AbortSignal.timeout(this.#timeoutMs),
74
+ });
75
+ }
76
+ catch (error) {
77
+ const reason = error instanceof Error && error.name === "TimeoutError" ? "timed out" : "failed";
78
+ throw new ApiError(0, `The request to Invoice Ninja ${reason}. Check the network or INVOICENINJA_BASE_URL, then retry.`);
79
+ }
80
+ // Only retry reads: retrying a POST could create a duplicate invoice or payment.
81
+ if ((res.status === 429 || res.status >= 500) && attempt === 0 && method === "GET") {
82
+ await new Promise((resolve) => setTimeout(resolve, this.#retryDelayMs));
83
+ continue;
84
+ }
85
+ const text = await res.text();
86
+ let parsed = null;
87
+ try {
88
+ parsed = text ? JSON.parse(text) : null;
89
+ }
90
+ catch {
91
+ if (res.ok)
92
+ throw new ApiError(res.status, "Invoice Ninja returned a response that is not JSON. Check INVOICENINJA_BASE_URL.");
93
+ }
94
+ if (!res.ok)
95
+ throw new ApiError(res.status, explain(res.status, validationDetail(parsed)));
96
+ return parsed;
97
+ }
98
+ }
99
+ listClients(query) {
100
+ return this.#request("GET", "/clients", { per_page: 20, ...query, status: "active" });
101
+ }
102
+ async getClient(id) {
103
+ return (await this.#request("GET", `/clients/${encodeURIComponent(id)}`)).data;
104
+ }
105
+ async createClient(input) {
106
+ return (await this.#request("POST", "/clients", {}, input)).data;
107
+ }
108
+ listInvoices(query) {
109
+ return this.#request("GET", "/invoices", { per_page: 20, sort: "date|desc", ...query });
110
+ }
111
+ async getInvoice(id) {
112
+ return (await this.#request("GET", `/invoices/${encodeURIComponent(id)}`, { include: "client" })).data;
113
+ }
114
+ async createInvoice(input, options) {
115
+ const query = options.send_email ? { send_email: "true" } : {};
116
+ return (await this.#request("POST", "/invoices", query, input)).data;
117
+ }
118
+ async bulkInvoices(action, ids, emailType) {
119
+ await this.#request("POST", "/invoices/bulk", {}, { action, ids, ...(emailType ? { email_type: emailType } : {}) });
120
+ }
121
+ async createPayment(input, options) {
122
+ const query = { email_receipt: options.email_receipt ? "true" : "false" };
123
+ return (await this.#request("POST", "/payments", query, input)).data;
124
+ }
125
+ }
@@ -0,0 +1,109 @@
1
+ // Remote mode: MCP over Streamable HTTP (stateless), for ChatGPT, Claude.ai connectors and hosted agents.
2
+ //
3
+ // Two ways to authenticate (OAuth is the production path, see README):
4
+ // - per user: each request carries the user's own API token in the `X-InvoiceNinja-Api-Token` header;
5
+ // - single tenant: INVOICENINJA_API_TOKEN is set on the server and clients send `Authorization: Bearer <MCP_ACCESS_TOKEN>`.
6
+ import { createServer as createHttpServer } from "node:http";
7
+ import { timingSafeEqual } from "node:crypto";
8
+ import { pathToFileURL } from "node:url";
9
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10
+ import { apiFromEnv, createServer, SERVER_INFO } from "./server.js";
11
+ const MAX_BODY_BYTES = 1_000_000;
12
+ function sendJson(res, status, body) {
13
+ res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body));
14
+ }
15
+ function rpcError(res, status, message) {
16
+ sendJson(res, status, { jsonrpc: "2.0", error: { code: -32000, message }, id: null });
17
+ }
18
+ function sameSecret(a, b) {
19
+ const left = Buffer.from(a);
20
+ const right = Buffer.from(b);
21
+ return left.length === right.length && timingSafeEqual(left, right);
22
+ }
23
+ async function readJson(req) {
24
+ const chunks = [];
25
+ let size = 0;
26
+ for await (const chunk of req) {
27
+ size += chunk.length;
28
+ if (size > MAX_BODY_BYTES)
29
+ throw new Error("too large");
30
+ chunks.push(chunk);
31
+ }
32
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
33
+ }
34
+ /** Returns the Invoice Ninja token to use for this request, or null after answering 401. */
35
+ function authenticate(req, res, env) {
36
+ const userKey = req.headers["x-invoiceninja-api-token"];
37
+ if (typeof userKey === "string" && userKey)
38
+ return userKey;
39
+ const serverKey = env.INVOICENINJA_API_TOKEN;
40
+ const accessToken = env.MCP_ACCESS_TOKEN;
41
+ const bearer = req.headers.authorization?.match(/^Bearer\s+(.+)$/i)?.[1];
42
+ if (serverKey && accessToken && bearer && sameSecret(bearer, accessToken))
43
+ return serverKey;
44
+ res.setHeader("WWW-Authenticate", 'Bearer realm="tethlo-mcp-for-invoice-ninja"');
45
+ rpcError(res, 401, "Missing credentials: send X-InvoiceNinja-Api-Token, or Authorization: Bearer <MCP_ACCESS_TOKEN>.");
46
+ return null;
47
+ }
48
+ export function startHttpServer(options = {}) {
49
+ const env = options.env ?? process.env;
50
+ const httpServer = createHttpServer(async (req, res) => {
51
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
52
+ if (path === "/health" && req.method === "GET") {
53
+ sendJson(res, 200, { ok: true, ...SERVER_INFO });
54
+ return;
55
+ }
56
+ if (path !== "/mcp") {
57
+ sendJson(res, 404, { error: "Not found. The MCP endpoint is /mcp." });
58
+ return;
59
+ }
60
+ if (req.method !== "POST") {
61
+ // Stateless server: no SSE stream to resume and no session to delete.
62
+ res.setHeader("Allow", "POST");
63
+ rpcError(res, 405, "Method not allowed. Send JSON-RPC requests with POST.");
64
+ return;
65
+ }
66
+ const token = authenticate(req, res, env);
67
+ if (!token)
68
+ return;
69
+ let body;
70
+ try {
71
+ body = await readJson(req);
72
+ }
73
+ catch {
74
+ sendJson(res, 400, { jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null });
75
+ return;
76
+ }
77
+ try {
78
+ const mcp = createServer(apiFromEnv(env, { ...options.api, token }), options.tools);
79
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
80
+ res.on("close", () => {
81
+ void transport.close();
82
+ void mcp.close();
83
+ });
84
+ await mcp.connect(transport);
85
+ await transport.handleRequest(req, res, body);
86
+ }
87
+ catch {
88
+ if (!res.headersSent)
89
+ rpcError(res, 500, "Internal server error");
90
+ }
91
+ });
92
+ return new Promise((resolve, reject) => {
93
+ httpServer.once("error", reject);
94
+ httpServer.listen(options.port ?? 3000, options.host ?? "127.0.0.1", () => {
95
+ const address = httpServer.address();
96
+ const port = typeof address === "object" && address ? address.port : options.port;
97
+ resolve({ server: httpServer, url: `http://${options.host ?? "127.0.0.1"}:${port}/mcp` });
98
+ });
99
+ });
100
+ }
101
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
102
+ const host = process.env.HOST ?? "127.0.0.1";
103
+ if (process.env.INVOICENINJA_API_TOKEN && !process.env.MCP_ACCESS_TOKEN) {
104
+ console.error("INVOICENINJA_API_TOKEN is set: also set MCP_ACCESS_TOKEN so that only your clients can use this token.");
105
+ process.exit(1);
106
+ }
107
+ const { url } = await startHttpServer({ port: Number(process.env.PORT ?? 3000), host });
108
+ console.error(`tethlo-mcp-for-invoice-ninja listening on ${url}`);
109
+ }
@@ -0,0 +1,23 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { InvoiceNinjaApi } from "./api.js";
3
+ import { registerTools } from "./tools.js";
4
+ export const SERVER_INFO = { name: "tethlo-mcp-for-invoice-ninja", version: "0.1.0" };
5
+ const INSTRUCTIONS = [
6
+ "Tools for Invoice Ninja, an invoicing and payments app for small businesses and freelancers.",
7
+ "Clients and invoices can be named in plain words: tools accept a client name or email and an invoice number.",
8
+ "Amounts are in each client's currency.",
9
+ "Use get_receivables_summary for questions about money owed overall, list_invoices for a client's invoices.",
10
+ "create_invoice saves a draft unless send is true: confirm amounts and recipient with the user before sending anything.",
11
+ ].join(" ");
12
+ export function createServer(api, options = {}) {
13
+ const server = new McpServer(SERVER_INFO, { instructions: INSTRUCTIONS });
14
+ registerTools(server, api, options);
15
+ return server;
16
+ }
17
+ export function apiFromEnv(env = process.env, overrides = {}) {
18
+ return new InvoiceNinjaApi({
19
+ token: overrides.token ?? env.INVOICENINJA_API_TOKEN ?? "",
20
+ baseUrl: overrides.baseUrl ?? env.INVOICENINJA_BASE_URL,
21
+ ...overrides,
22
+ });
23
+ }
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ // Local mode: the MCP client (Claude Desktop, Claude Code, Cursor...) starts this process.
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { apiFromEnv, createServer } from "./server.js";
5
+ if (!process.env.INVOICENINJA_API_TOKEN) {
6
+ console.error("INVOICENINJA_API_TOKEN is not set. Create a token in Invoice Ninja > Settings > Account Management > API Tokens.");
7
+ process.exit(1);
8
+ }
9
+ const server = createServer(apiFromEnv());
10
+ await server.connect(new StdioServerTransport());
11
+ // stdout is the protocol channel: log to stderr only.
12
+ console.error("tethlo-mcp-for-invoice-ninja running on stdio");
@@ -0,0 +1,384 @@
1
+ import { z } from "zod";
2
+ import { ApiError } from "./api.js";
3
+ /** A problem with the agent's input that it can fix (unknown client, ambiguous match, amount too high...). */
4
+ export class ToolError extends Error {
5
+ }
6
+ const DATE = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "use the YYYY-MM-DD format");
7
+ const DAY_MS = 86_400_000;
8
+ function ok(data) {
9
+ return { content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data };
10
+ }
11
+ async function run(fn) {
12
+ try {
13
+ return ok(await fn());
14
+ }
15
+ catch (error) {
16
+ const message = error instanceof ApiError || error instanceof ToolError
17
+ ? error.message
18
+ : "Unexpected error in the Invoice Ninja MCP server. Retry once; if it persists, report it to the server owner.";
19
+ return { isError: true, content: [{ type: "text", text: message }] };
20
+ }
21
+ }
22
+ export const money = (value) => Math.round(value * 100) / 100;
23
+ export function daysBetween(from, to) {
24
+ return Math.round((Date.parse(to) - Date.parse(from)) / DAY_MS);
25
+ }
26
+ export function statusOf(invoice, today) {
27
+ switch (String(invoice.status_id)) {
28
+ case "1":
29
+ return "draft";
30
+ case "4":
31
+ return "paid";
32
+ case "5":
33
+ return "cancelled";
34
+ case "6":
35
+ return "reversed";
36
+ default:
37
+ if (invoice.balance > 0 && invoice.due_date && invoice.due_date < today)
38
+ return "overdue";
39
+ return String(invoice.status_id) === "3" ? "partial" : "sent";
40
+ }
41
+ }
42
+ function primaryEmail(client) {
43
+ if (!client)
44
+ return undefined;
45
+ return (client.contacts.find((c) => c.is_primary) ?? client.contacts[0])?.email || undefined;
46
+ }
47
+ function clientSummary(client) {
48
+ return {
49
+ id: client.id,
50
+ name: client.display_name || client.name,
51
+ email: primaryEmail(client),
52
+ balance: money(client.balance),
53
+ paid_to_date: money(client.paid_to_date),
54
+ };
55
+ }
56
+ function invoiceSummary(invoice, today) {
57
+ const status = statusOf(invoice, today);
58
+ return {
59
+ id: invoice.id,
60
+ number: invoice.number,
61
+ client: invoice.client ? invoice.client.display_name || invoice.client.name : invoice.client_id,
62
+ status,
63
+ amount: money(invoice.amount),
64
+ balance: money(invoice.balance),
65
+ date: invoice.date,
66
+ due_date: invoice.due_date || undefined,
67
+ days_overdue: status === "overdue" ? daysBetween(invoice.due_date, today) : undefined,
68
+ };
69
+ }
70
+ function label(client) {
71
+ const email = primaryEmail(client);
72
+ return `"${client.name}"${email ? ` <${email}>` : ""}`;
73
+ }
74
+ /** Find a client from what the user said: name, contact email, part of the name, or id. */
75
+ export async function resolveClient(api, ref) {
76
+ const wanted = ref.trim();
77
+ const lower = wanted.toLowerCase();
78
+ const found = (await api.listClients({ filter: wanted, per_page: 20 })).data.filter((c) => !c.is_deleted);
79
+ const exact = found.filter((c) => c.id === wanted || c.name.toLowerCase() === lower || c.contacts.some((ct) => ct.email?.toLowerCase() === lower));
80
+ if (exact.length === 1)
81
+ return exact[0];
82
+ const candidates = exact.length ? exact : found;
83
+ if (candidates.length === 1)
84
+ return candidates[0];
85
+ if (candidates.length > 1) {
86
+ throw new ToolError(`"${wanted}" matches ${candidates.length} clients: ${candidates.slice(0, 8).map(label).join(", ")}. Ask the user which one.`);
87
+ }
88
+ if (/^[A-Za-z0-9]{4,}$/.test(wanted)) {
89
+ try {
90
+ return await api.getClient(wanted);
91
+ }
92
+ catch (error) {
93
+ if (!(error instanceof ApiError && error.status === 404))
94
+ throw error;
95
+ }
96
+ }
97
+ throw new ToolError(`No client matches "${wanted}". Search with find_clients, or add it with create_client.`);
98
+ }
99
+ /** Find an invoice by its number (e.g. "0042" or "INV-0042") or its id. */
100
+ export async function resolveInvoice(api, ref) {
101
+ const wanted = ref.trim().replace(/^#/, "");
102
+ const byNumber = (await api.listInvoices({ number: wanted, include: "client" })).data.filter((i) => !i.is_deleted);
103
+ const exact = byNumber.filter((i) => i.number.toLowerCase() === wanted.toLowerCase());
104
+ if (exact.length === 1)
105
+ return exact[0];
106
+ if (byNumber.length === 1)
107
+ return byNumber[0];
108
+ if (byNumber.length > 1) {
109
+ throw new ToolError(`"${wanted}" matches ${byNumber.length} invoices: ${byNumber.slice(0, 8).map((i) => i.number).join(", ")}.`);
110
+ }
111
+ try {
112
+ return await api.getInvoice(wanted);
113
+ }
114
+ catch (error) {
115
+ if (error instanceof ApiError && error.status === 404) {
116
+ throw new ToolError(`No invoice "${wanted}". Use list_invoices to find it by client or status.`);
117
+ }
118
+ throw error;
119
+ }
120
+ }
121
+ const STATUS_QUERY = {
122
+ all: {},
123
+ draft: { status_id: 1 },
124
+ sent: { status_id: 2 },
125
+ partial: { status_id: 3 },
126
+ unpaid: { client_status: "unpaid" },
127
+ overdue: { client_status: "overdue" },
128
+ paid: { client_status: "paid" },
129
+ };
130
+ export function registerTools(server, api, options = {}) {
131
+ const today = options.today ?? (() => new Date().toISOString().slice(0, 10));
132
+ server.registerTool("find_clients", {
133
+ title: "Find clients",
134
+ description: "Search the customers (clients) of the Invoice Ninja account by name, contact name or email, with what each one owes " +
135
+ "(balance) and has paid. Use it to check whether a customer already exists, get their contact details, or list " +
136
+ "who owes money. For invoices, use list_invoices.",
137
+ inputSchema: {
138
+ query: z.string().optional().describe("Text to search in client name, contact name or email. Empty = all clients."),
139
+ owes_money: z.boolean().default(false).describe("Only clients with an outstanding balance, largest first."),
140
+ limit: z.number().int().min(1).max(50).default(10),
141
+ },
142
+ annotations: { readOnlyHint: true, openWorldHint: true },
143
+ }, async ({ query, owes_money, limit }) => run(async () => {
144
+ const page = await api.listClients({ filter: query, per_page: owes_money ? 100 : limit, sort: owes_money ? "balance|desc" : "name|asc" });
145
+ const clients = page.data
146
+ .filter((c) => !c.is_deleted && (!owes_money || c.balance > 0))
147
+ .sort((a, b) => (owes_money ? b.balance - a.balance : 0));
148
+ return {
149
+ count: Math.min(clients.length, limit),
150
+ truncated: clients.length > limit,
151
+ clients: clients.slice(0, limit).map(clientSummary),
152
+ };
153
+ }));
154
+ server.registerTool("create_client", {
155
+ title: "Create a client",
156
+ description: "Add a new customer (client) with a primary contact. If a client with the same name already exists, returns it " +
157
+ "instead of creating a duplicate, unless allow_duplicate is true.",
158
+ inputSchema: {
159
+ name: z.string().min(1).max(255).describe("Company or person name, e.g. 'Acme Corp'."),
160
+ email: z.email().optional().describe("Primary contact email: invoices are sent there."),
161
+ first_name: z.string().optional(),
162
+ last_name: z.string().optional(),
163
+ phone: z.string().optional(),
164
+ website: z.string().optional(),
165
+ allow_duplicate: z.boolean().default(false),
166
+ },
167
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
168
+ }, async (args) => run(async () => {
169
+ if (!args.allow_duplicate) {
170
+ const existing = (await api.listClients({ filter: args.name, per_page: 20 })).data.find((c) => !c.is_deleted && c.name.toLowerCase() === args.name.trim().toLowerCase());
171
+ if (existing)
172
+ return { action: "existing", client: clientSummary(existing), note: "A client with this name already exists." };
173
+ }
174
+ const client = await api.createClient({
175
+ name: args.name.trim(),
176
+ phone: args.phone,
177
+ website: args.website,
178
+ contacts: [{ first_name: args.first_name ?? "", last_name: args.last_name ?? "", email: args.email ?? "", is_primary: true }],
179
+ });
180
+ return { action: "created", client: clientSummary(client) };
181
+ }));
182
+ server.registerTool("list_invoices", {
183
+ title: "List invoices",
184
+ description: "List invoices, newest first, filtered by client and/or status (draft, sent, partial, unpaid, overdue, paid). " +
185
+ "Returns totals and days overdue. Use it for 'what has Acme not paid?' or 'show last month's invoices'. " +
186
+ "For the overall money owed across all clients, use get_receivables_summary.",
187
+ inputSchema: {
188
+ client: z.string().optional().describe("Client name, email or id."),
189
+ status: z.enum(["all", "draft", "sent", "partial", "unpaid", "overdue", "paid"]).default("all"),
190
+ search: z.string().optional().describe("Text to search in number, PO number, item names or notes."),
191
+ limit: z.number().int().min(1).max(100).default(20),
192
+ },
193
+ annotations: { readOnlyHint: true, openWorldHint: true },
194
+ }, async ({ client, status, search, limit }) => run(async () => {
195
+ const clientId = client ? (await resolveClient(api, client)).id : undefined;
196
+ const page = await api.listInvoices({ ...STATUS_QUERY[status], client_id: clientId, filter: search, per_page: limit, include: "client" });
197
+ const date = today();
198
+ const invoices = page.data.filter((i) => !i.is_deleted).map((i) => invoiceSummary(i, date));
199
+ return {
200
+ count: invoices.length,
201
+ total_matching: page.meta?.pagination?.total ?? invoices.length,
202
+ total_amount: money(invoices.reduce((sum, i) => sum + i.amount, 0)),
203
+ total_balance: money(invoices.reduce((sum, i) => sum + i.balance, 0)),
204
+ invoices,
205
+ };
206
+ }));
207
+ server.registerTool("get_invoice", {
208
+ title: "Get an invoice",
209
+ description: "Full detail of ONE invoice by its number (e.g. '0042') or id: client and email, line items, totals, balance due, " +
210
+ "status, due date and the client portal link to view or pay it.",
211
+ inputSchema: { invoice: z.string().min(1).describe("Invoice number or id.") },
212
+ annotations: { readOnlyHint: true, openWorldHint: true },
213
+ }, async ({ invoice }) => run(async () => {
214
+ const found = await resolveInvoice(api, invoice);
215
+ return {
216
+ ...invoiceSummary(found, today()),
217
+ client_email: primaryEmail(found.client),
218
+ po_number: found.po_number || undefined,
219
+ paid_to_date: money(found.paid_to_date),
220
+ items: found.line_items.map((l) => ({
221
+ item: l.product_key || undefined,
222
+ description: l.notes,
223
+ quantity: l.quantity,
224
+ unit_price: money(l.cost),
225
+ total: money(l.line_total ?? l.cost * l.quantity),
226
+ })),
227
+ notes: found.public_notes || undefined,
228
+ link: found.invitations?.[0]?.link,
229
+ };
230
+ }));
231
+ server.registerTool("create_invoice", {
232
+ title: "Create an invoice",
233
+ description: "Bill a client: create an invoice from line items (description, quantity, unit price). Saved as a draft unless " +
234
+ "send is true, which also emails it to the client. Confirm the amounts with the user before sending.",
235
+ inputSchema: {
236
+ client: z.string().min(1).describe("Client name, email or id. Create the client first with create_client if needed."),
237
+ items: z
238
+ .array(z.object({
239
+ description: z.string().min(1),
240
+ quantity: z.number().positive().default(1),
241
+ unit_price: z.number().min(0),
242
+ product_key: z.string().optional().describe("Product or service code, if any."),
243
+ }))
244
+ .min(1)
245
+ .max(100),
246
+ due_date: DATE.optional().describe("YYYY-MM-DD. Default: the account's payment terms."),
247
+ po_number: z.string().optional(),
248
+ notes: z.string().max(5000).optional().describe("Public note printed on the invoice."),
249
+ send: z.boolean().default(false).describe("Email the invoice to the client right away."),
250
+ },
251
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
252
+ }, async (args) => run(async () => {
253
+ const client = await resolveClient(api, args.client);
254
+ if (args.send && !primaryEmail(client)) {
255
+ throw new ToolError(`${client.name} has no contact email, so the invoice cannot be sent. Create it with send=false.`);
256
+ }
257
+ const invoice = await api.createInvoice({
258
+ client_id: client.id,
259
+ due_date: args.due_date,
260
+ po_number: args.po_number,
261
+ public_notes: args.notes,
262
+ line_items: args.items.map((item) => ({
263
+ product_key: item.product_key ?? "",
264
+ notes: item.description,
265
+ quantity: item.quantity,
266
+ cost: item.unit_price,
267
+ })),
268
+ }, { send_email: args.send });
269
+ return {
270
+ action: args.send ? "created_and_sent" : "created_as_draft",
271
+ invoice: invoiceSummary({ ...invoice, client }, today()),
272
+ sent_to: args.send ? primaryEmail(client) : undefined,
273
+ link: invoice.invitations?.[0]?.link,
274
+ };
275
+ }));
276
+ server.registerTool("send_invoice", {
277
+ title: "Send an invoice or a reminder",
278
+ description: "Email an existing invoice to its client, or a payment reminder (reminder1, reminder2, reminder3 templates). " +
279
+ "Use it to send a draft, re-send an invoice, or chase a late payment.",
280
+ inputSchema: {
281
+ invoice: z.string().min(1).describe("Invoice number or id."),
282
+ template: z.enum(["invoice", "reminder1", "reminder2", "reminder3"]).default("invoice"),
283
+ },
284
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
285
+ }, async ({ invoice, template }) => run(async () => {
286
+ const found = await resolveInvoice(api, invoice);
287
+ const status = statusOf(found, today());
288
+ if (status === "paid" || status === "cancelled" || status === "reversed") {
289
+ throw new ToolError(`Invoice ${found.number} is ${status}; there is nothing to send.`);
290
+ }
291
+ const client = found.client ?? (await api.getClient(found.client_id));
292
+ const email = primaryEmail(client);
293
+ if (!email)
294
+ throw new ToolError(`${client.name} has no contact email. Add one in Invoice Ninja first.`);
295
+ if (template === "invoice")
296
+ await api.bulkInvoices("email", [found.id]);
297
+ else
298
+ await api.bulkInvoices("send_email", [found.id], template);
299
+ return { sent: true, template, invoice: found.number, to: email, balance: money(found.balance) };
300
+ }));
301
+ server.registerTool("record_payment", {
302
+ title: "Record a payment",
303
+ description: "Record money received against an invoice (bank transfer, check, cash...). Defaults to paying the full balance " +
304
+ "today. Marks the invoice paid or partially paid.",
305
+ inputSchema: {
306
+ invoice: z.string().min(1).describe("Invoice number or id."),
307
+ amount: z.number().positive().optional().describe("Amount received. Default: the full balance due."),
308
+ date: DATE.optional().describe("YYYY-MM-DD. Default: today."),
309
+ reference: z.string().max(100).optional().describe("Bank or transaction reference."),
310
+ send_receipt: z.boolean().default(false).describe("Email a payment receipt to the client."),
311
+ },
312
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
313
+ }, async (args) => run(async () => {
314
+ const found = await resolveInvoice(api, args.invoice);
315
+ if (found.balance <= 0)
316
+ throw new ToolError(`Invoice ${found.number} has no balance due.`);
317
+ const amount = money(args.amount ?? found.balance);
318
+ if (amount > money(found.balance)) {
319
+ throw new ToolError(`${amount} is more than the balance due on invoice ${found.number} (${money(found.balance)}).`);
320
+ }
321
+ const payment = await api.createPayment({
322
+ client_id: found.client_id,
323
+ amount,
324
+ date: args.date ?? today(),
325
+ transaction_reference: args.reference,
326
+ invoices: [{ invoice_id: found.id, amount }],
327
+ }, { email_receipt: args.send_receipt });
328
+ const remaining = money(found.balance - amount);
329
+ return {
330
+ recorded: true,
331
+ payment: payment.number,
332
+ invoice: found.number,
333
+ amount,
334
+ remaining_balance: remaining,
335
+ invoice_status: remaining === 0 ? "paid" : "partial",
336
+ };
337
+ }));
338
+ server.registerTool("get_receivables_summary", {
339
+ title: "Accounts receivable summary",
340
+ description: "How much money customers owe in total: outstanding and overdue amounts, aging buckets (not due, 1-30, 31-60, " +
341
+ "61-90, over 90 days late), the clients who owe the most and the oldest overdue invoices. Use it for cash-flow " +
342
+ "questions like 'how much are we owed?' or 'who should I chase first?'.",
343
+ inputSchema: {
344
+ client: z.string().optional().describe("Limit to one client (name, email or id)."),
345
+ },
346
+ annotations: { readOnlyHint: true, openWorldHint: true },
347
+ }, async ({ client }) => run(async () => {
348
+ const clientId = client ? (await resolveClient(api, client)).id : undefined;
349
+ const unpaid = [];
350
+ for (let page = 1; page <= 5; page++) {
351
+ const result = await api.listInvoices({ client_status: "unpaid", client_id: clientId, per_page: 100, page, include: "client" });
352
+ unpaid.push(...result.data.filter((i) => !i.is_deleted && i.balance > 0 && String(i.status_id) !== "1"));
353
+ if (result.data.length < 100)
354
+ break;
355
+ }
356
+ const date = today();
357
+ const buckets = { not_due: 0, "1_30": 0, "31_60": 0, "61_90": 0, over_90: 0 };
358
+ const byClient = new Map();
359
+ for (const invoice of unpaid) {
360
+ const late = invoice.due_date ? daysBetween(invoice.due_date, date) : 0;
361
+ const key = late <= 0 ? "not_due" : late <= 30 ? "1_30" : late <= 60 ? "31_60" : late <= 90 ? "61_90" : "over_90";
362
+ buckets[key] += invoice.balance;
363
+ const name = invoice.client ? invoice.client.display_name || invoice.client.name : invoice.client_id;
364
+ byClient.set(name, (byClient.get(name) ?? 0) + invoice.balance);
365
+ }
366
+ const overdue = unpaid.filter((i) => statusOf(i, date) === "overdue");
367
+ return {
368
+ as_of: date,
369
+ open_invoices: unpaid.length,
370
+ total_outstanding: money(unpaid.reduce((sum, i) => sum + i.balance, 0)),
371
+ total_overdue: money(overdue.reduce((sum, i) => sum + i.balance, 0)),
372
+ aging: Object.fromEntries(Object.entries(buckets).map(([k, v]) => [k, money(v)])),
373
+ top_debtors: [...byClient.entries()]
374
+ .sort((a, b) => b[1] - a[1])
375
+ .slice(0, 5)
376
+ .map(([name, owed]) => ({ client: name, owed: money(owed) })),
377
+ oldest_overdue: overdue
378
+ .sort((a, b) => a.due_date.localeCompare(b.due_date))
379
+ .slice(0, 5)
380
+ .map((i) => invoiceSummary(i, date)),
381
+ note: unpaid.length >= 500 ? "Only the first 500 open invoices were included." : undefined,
382
+ };
383
+ }));
384
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@tethlo/mcp-for-invoice-ninja",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Unofficial MCP server for Invoice Ninja (demo): find clients, create and send invoices, record payments and chase late payers from AI agents.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Tethlo (https://tethlo.com)",
8
+ "homepage": "https://github.com/tethlo/connectors/tree/main/packages/invoice-ninja#readme",
9
+ "bugs": {
10
+ "url": "https://github.com/tethlo/connectors/issues"
11
+ },
12
+ "mcpName": "io.github.tethlo/mcp-for-invoice-ninja",
13
+ "keywords": [
14
+ "mcp",
15
+ "model-context-protocol",
16
+ "mcp-server",
17
+ "ai-agents",
18
+ "claude",
19
+ "invoice-ninja",
20
+ "invoicing",
21
+ "payments",
22
+ "demo",
23
+ "tethlo"
24
+ ],
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/tethlo/connectors.git",
28
+ "directory": "packages/invoice-ninja"
29
+ },
30
+ "engines": {
31
+ "node": ">=22.18"
32
+ },
33
+ "bin": {
34
+ "tethlo-mcp-for-invoice-ninja": "dist/src/stdio.js"
35
+ },
36
+ "files": [
37
+ "dist/src",
38
+ "README.md",
39
+ "LICENSE",
40
+ "server.json"
41
+ ],
42
+ "scripts": {
43
+ "start": "node src/stdio.ts",
44
+ "start:http": "node src/http.ts",
45
+ "build": "tsc -p tsconfig.json --noEmit false --outDir dist",
46
+ "typecheck": "tsc -p tsconfig.json",
47
+ "test": "node --test \"test/*.test.ts\"",
48
+ "eval:claude": "node eval/run-claude.ts",
49
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
50
+ },
51
+ "dependencies": {
52
+ "@modelcontextprotocol/sdk": "1.32.2",
53
+ "zod": "4.6.7"
54
+ },
55
+ "devDependencies": {
56
+ "@anthropic-ai/sdk": "1.6.0",
57
+ "@types/node": "22.20.5",
58
+ "typescript": "5.9.3"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public"
62
+ }
63
+ }
package/server.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "io.github.tethlo/mcp-for-invoice-ninja",
4
+ "title": "Tethlo MCP server for Invoice Ninja (unofficial demo)",
5
+ "description": "Unofficial demo. Invoice Ninja for AI agents: clients, invoices, payments, receivables.",
6
+ "repository": {
7
+ "url": "https://github.com/tethlo/connectors",
8
+ "source": "github",
9
+ "subfolder": "packages/invoice-ninja"
10
+ },
11
+ "version": "0.1.0",
12
+ "packages": [
13
+ {
14
+ "registryType": "npm",
15
+ "registryBaseUrl": "https://registry.npmjs.org",
16
+ "identifier": "@tethlo/mcp-for-invoice-ninja",
17
+ "version": "0.1.0",
18
+ "transport": {
19
+ "type": "stdio"
20
+ },
21
+ "environmentVariables": [
22
+ {
23
+ "name": "INVOICENINJA_API_TOKEN",
24
+ "description": "Invoice Ninja API token (Settings > Account Management > API Tokens).",
25
+ "isRequired": true,
26
+ "isSecret": true,
27
+ "format": "string"
28
+ },
29
+ {
30
+ "name": "INVOICENINJA_BASE_URL",
31
+ "description": "Optional: a self-hosted instance, e.g. https://invoices.example.com. Default: https://invoicing.co",
32
+ "isRequired": false,
33
+ "isSecret": false,
34
+ "format": "string"
35
+ }
36
+ ]
37
+ }
38
+ ]
39
+ }