easybill-mcp 1.0.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -0
  3. package/dist/constants.d.ts +50 -0
  4. package/dist/constants.js +204 -0
  5. package/dist/constants.js.map +1 -0
  6. package/dist/index.d.ts +17 -0
  7. package/dist/index.js +154 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/instructions.d.ts +11 -0
  10. package/dist/instructions.js +89 -0
  11. package/dist/instructions.js.map +1 -0
  12. package/dist/schemas/common.d.ts +44 -0
  13. package/dist/schemas/common.js +59 -0
  14. package/dist/schemas/common.js.map +1 -0
  15. package/dist/services/client.d.ts +57 -0
  16. package/dist/services/client.js +258 -0
  17. package/dist/services/client.js.map +1 -0
  18. package/dist/services/format.d.ts +70 -0
  19. package/dist/services/format.js +158 -0
  20. package/dist/services/format.js.map +1 -0
  21. package/dist/tools/catalog.d.ts +4 -0
  22. package/dist/tools/catalog.js +74 -0
  23. package/dist/tools/catalog.js.map +1 -0
  24. package/dist/tools/crud.d.ts +51 -0
  25. package/dist/tools/crud.js +152 -0
  26. package/dist/tools/crud.js.map +1 -0
  27. package/dist/tools/customers.d.ts +4 -0
  28. package/dist/tools/customers.js +91 -0
  29. package/dist/tools/customers.js.map +1 -0
  30. package/dist/tools/documents.d.ts +8 -0
  31. package/dist/tools/documents.js +326 -0
  32. package/dist/tools/documents.js.map +1 -0
  33. package/dist/tools/files.d.ts +4 -0
  34. package/dist/tools/files.js +108 -0
  35. package/dist/tools/files.js.map +1 -0
  36. package/dist/tools/finance.d.ts +4 -0
  37. package/dist/tools/finance.js +39 -0
  38. package/dist/tools/finance.js.map +1 -0
  39. package/dist/tools/meta.d.ts +10 -0
  40. package/dist/tools/meta.js +74 -0
  41. package/dist/tools/meta.js.map +1 -0
  42. package/dist/tools/registry.d.ts +39 -0
  43. package/dist/tools/registry.js +56 -0
  44. package/dist/tools/registry.js.map +1 -0
  45. package/dist/tools/search.d.ts +13 -0
  46. package/dist/tools/search.js +243 -0
  47. package/dist/tools/search.js.map +1 -0
  48. package/dist/tools/work.d.ts +4 -0
  49. package/dist/tools/work.js +76 -0
  50. package/dist/tools/work.js.map +1 -0
  51. package/package.json +58 -0
@@ -0,0 +1,258 @@
1
+ /**
2
+ * HTTP client for the easybill REST API.
3
+ *
4
+ * Responsibilities:
5
+ * - Bearer authentication from EASYBILL_API_KEY
6
+ * - Proactive client-side throttling (easybill allows only 10-60 req/min)
7
+ * - Retry with backoff on 429 / 5xx / network blips, honouring Retry-After
8
+ * - Mapping HTTP failures onto actionable error messages
9
+ */
10
+ import { API_BASE_URL, MAX_RETRIES, RATE_LIMIT_PER_MINUTE, SERVER_NAME, SERVER_VERSION, TIMEOUT_MS, } from "../constants.js";
11
+ /** An easybill API error carrying enough context for an actionable message. */
12
+ export class EasybillApiError extends Error {
13
+ status;
14
+ statusText;
15
+ path;
16
+ detail;
17
+ retryAfterSeconds;
18
+ constructor(status, statusText, path, detail, retryAfterSeconds) {
19
+ super(`easybill API ${status} ${statusText} on ${path}${detail ? `: ${detail}` : ""}`);
20
+ this.status = status;
21
+ this.statusText = statusText;
22
+ this.path = path;
23
+ this.detail = detail;
24
+ this.retryAfterSeconds = retryAfterSeconds;
25
+ this.name = "EasybillApiError";
26
+ }
27
+ }
28
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29
+ /**
30
+ * Sliding-window throttle. Keeps at most RATE_LIMIT_PER_MINUTE request
31
+ * timestamps and waits for the oldest to age out before issuing the next call.
32
+ * Serialised through a promise chain so concurrent tool calls queue in order.
33
+ */
34
+ class RateLimiter {
35
+ perMinute;
36
+ timestamps = [];
37
+ queue = Promise.resolve();
38
+ constructor(perMinute) {
39
+ this.perMinute = perMinute;
40
+ }
41
+ /** Resolves once the caller is allowed to send a request. */
42
+ acquire() {
43
+ const wait = this.queue.then(() => this.reserve());
44
+ // Swallow rejections so one failure cannot poison the chain.
45
+ this.queue = wait.catch(() => undefined);
46
+ return wait;
47
+ }
48
+ async reserve() {
49
+ const windowMs = 60_000;
50
+ for (;;) {
51
+ const now = Date.now();
52
+ while (this.timestamps.length > 0 && now - this.timestamps[0] >= windowMs) {
53
+ this.timestamps.shift();
54
+ }
55
+ if (this.timestamps.length < this.perMinute) {
56
+ this.timestamps.push(now);
57
+ return;
58
+ }
59
+ // +50ms guards against waking a hair too early due to timer rounding.
60
+ await sleep(windowMs - (now - this.timestamps[0]) + 50);
61
+ }
62
+ }
63
+ }
64
+ /** Serialises a query object into URLSearchParams, dropping empty values. */
65
+ function buildQuery(query) {
66
+ if (!query)
67
+ return "";
68
+ const params = new URLSearchParams();
69
+ for (const [key, value] of Object.entries(query)) {
70
+ if (value === undefined || value === null || value === "")
71
+ continue;
72
+ // easybill accepts repeated filter values comma-separated.
73
+ params.append(key, Array.isArray(value) ? value.join(",") : String(value));
74
+ }
75
+ const qs = params.toString();
76
+ return qs ? `?${qs}` : "";
77
+ }
78
+ /** Pulls a human-readable message out of an easybill error body. */
79
+ function extractDetail(raw) {
80
+ if (!raw)
81
+ return "";
82
+ try {
83
+ const parsed = JSON.parse(raw);
84
+ if (typeof parsed === "string")
85
+ return parsed;
86
+ if (parsed && typeof parsed === "object") {
87
+ const obj = parsed;
88
+ const message = obj.message ?? obj.error ?? obj.detail;
89
+ const parts = [];
90
+ if (typeof message === "string")
91
+ parts.push(message);
92
+ // Validation failures arrive as { errors: { field: [msg, ...] } }.
93
+ if (obj.errors && typeof obj.errors === "object") {
94
+ for (const [field, msgs] of Object.entries(obj.errors)) {
95
+ const text = Array.isArray(msgs) ? msgs.join("; ") : String(msgs);
96
+ parts.push(`${field}: ${text}`);
97
+ }
98
+ }
99
+ if (parts.length > 0)
100
+ return parts.join(" | ");
101
+ }
102
+ }
103
+ catch {
104
+ // Not JSON — fall through to the raw text.
105
+ }
106
+ return raw.slice(0, 500);
107
+ }
108
+ function parseRetryAfter(header) {
109
+ if (!header)
110
+ return undefined;
111
+ const seconds = Number.parseInt(header, 10);
112
+ return Number.isNaN(seconds) ? undefined : seconds;
113
+ }
114
+ function fileNameFromDisposition(header) {
115
+ if (!header)
116
+ return undefined;
117
+ const utf8 = /filename\*=UTF-8''([^;]+)/i.exec(header);
118
+ if (utf8?.[1])
119
+ return decodeURIComponent(utf8[1].trim());
120
+ const plain = /filename="?([^";]+)"?/i.exec(header);
121
+ return plain?.[1]?.trim();
122
+ }
123
+ export class EasybillClient {
124
+ apiKey;
125
+ limiter = new RateLimiter(RATE_LIMIT_PER_MINUTE);
126
+ constructor(apiKey) {
127
+ this.apiKey = apiKey;
128
+ }
129
+ /** Performs a JSON request and returns the decoded body (undefined for 204). */
130
+ async request(path, options = {}) {
131
+ const response = await this.send(path, options);
132
+ if (response.status === 204)
133
+ return undefined;
134
+ const text = await response.text();
135
+ if (!text)
136
+ return undefined;
137
+ try {
138
+ return JSON.parse(text);
139
+ }
140
+ catch {
141
+ // A few endpoints answer with a bare string.
142
+ return text;
143
+ }
144
+ }
145
+ /** Performs a request expecting a binary body (PDF, JPG, attachment content). */
146
+ async requestBinary(path, options = {}) {
147
+ const response = await this.send(path, options);
148
+ const buffer = Buffer.from(await response.arrayBuffer());
149
+ const result = {
150
+ data: buffer,
151
+ contentType: response.headers.get("content-type") ?? "application/octet-stream",
152
+ };
153
+ const fileName = fileNameFromDisposition(response.headers.get("content-disposition"));
154
+ if (fileName !== undefined)
155
+ result.fileName = fileName;
156
+ return result;
157
+ }
158
+ async send(path, options) {
159
+ const { method = "GET", body, query, accept = "application/json", headers = {} } = options;
160
+ const url = `${API_BASE_URL}${path}${buildQuery(query)}`;
161
+ let lastError;
162
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
163
+ await this.limiter.acquire();
164
+ const requestHeaders = {
165
+ Authorization: `Bearer ${this.apiKey}`,
166
+ Accept: accept,
167
+ "User-Agent": `${SERVER_NAME}/${SERVER_VERSION}`,
168
+ ...headers,
169
+ };
170
+ let payload;
171
+ if (options.rawBody !== undefined) {
172
+ payload = options.rawBody;
173
+ }
174
+ else if (body !== undefined) {
175
+ payload = JSON.stringify(body);
176
+ requestHeaders["Content-Type"] = "application/json";
177
+ }
178
+ try {
179
+ const response = await fetch(url, {
180
+ method,
181
+ headers: requestHeaders,
182
+ ...(payload === undefined ? {} : { body: payload }),
183
+ signal: AbortSignal.timeout(TIMEOUT_MS),
184
+ });
185
+ if (response.ok)
186
+ return response;
187
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
188
+ const retriable = response.status === 429 || response.status >= 500;
189
+ if (retriable && attempt < MAX_RETRIES) {
190
+ // Honour Retry-After when present, otherwise exponential backoff.
191
+ const backoffMs = retryAfter !== undefined ? retryAfter * 1000 : 2 ** attempt * 1500;
192
+ await sleep(Math.min(backoffMs, 60_000));
193
+ continue;
194
+ }
195
+ const detail = extractDetail(await response.text());
196
+ throw new EasybillApiError(response.status, response.statusText, path, detail, retryAfter);
197
+ }
198
+ catch (error) {
199
+ if (error instanceof EasybillApiError)
200
+ throw error;
201
+ lastError = error;
202
+ // Timeouts and connection resets are worth one more shot.
203
+ if (attempt < MAX_RETRIES) {
204
+ await sleep(2 ** attempt * 1000);
205
+ continue;
206
+ }
207
+ }
208
+ }
209
+ const reason = lastError instanceof Error ? lastError.message : String(lastError);
210
+ if (lastError instanceof Error && lastError.name === "TimeoutError") {
211
+ throw new Error(`Request to ${path} timed out after ${TIMEOUT_MS}ms. ` +
212
+ `Retry, or narrow the request with filters / a smaller 'limit'.`);
213
+ }
214
+ throw new Error(`Request to ${path} failed: ${reason}`);
215
+ }
216
+ }
217
+ /**
218
+ * Turns any thrown error into a message that tells the agent what to do next.
219
+ */
220
+ export function formatApiError(error) {
221
+ if (error instanceof EasybillApiError) {
222
+ const { status, path, detail } = error;
223
+ const suffix = detail ? ` Details: ${detail}` : "";
224
+ switch (status) {
225
+ case 400:
226
+ return `Error: easybill rejected the request as invalid (400) on ${path}.${suffix} Check required fields and that dates use YYYY-MM-DD.`;
227
+ case 401:
228
+ return `Error: authentication failed (401). Verify EASYBILL_API_KEY is a valid easybill API key (easybill: Einstellungen -> App-Center -> API).${suffix}`;
229
+ case 403:
230
+ return `Error: access denied (403) on ${path}. Your easybill plan or API key may not include this resource.${suffix}`;
231
+ case 404:
232
+ return `Error: not found (404) on ${path}. Verify the ID exists — list the resource first to get valid IDs.${suffix}`;
233
+ case 409:
234
+ return `Error: conflict (409) on ${path}.${suffix} The record may already be completed, cancelled, or referenced elsewhere.`;
235
+ case 414:
236
+ return `Error: request URI too long (414). easybill caps the request line at 4094 bytes — pass fewer filter values per call.`;
237
+ case 422:
238
+ return `Error: validation failed (422) on ${path}.${suffix}`;
239
+ case 429: {
240
+ const wait = error.retryAfterSeconds
241
+ ? ` Retry in ${error.retryAfterSeconds}s.`
242
+ : " Wait about a minute before retrying.";
243
+ return (`Error: easybill rate limit exceeded (429).${wait} ` +
244
+ `The plan limit is 10 req/min (PLUS) or 60 req/min (BUSINESS). ` +
245
+ `Set EASYBILL_RATE_LIMIT_PER_MINUTE to match your plan so the server throttles itself.`);
246
+ }
247
+ default:
248
+ if (status >= 500) {
249
+ return `Error: easybill server error (${status}) on ${path}. This is on easybill's side — retry shortly.${suffix}`;
250
+ }
251
+ return `Error: easybill API returned ${status} on ${path}.${suffix}`;
252
+ }
253
+ }
254
+ if (error instanceof Error)
255
+ return `Error: ${error.message}`;
256
+ return `Error: unexpected failure: ${String(error)}`;
257
+ }
258
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/services/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EACL,YAAY,EACZ,WAAW,EACX,qBAAqB,EACrB,WAAW,EACX,cAAc,EACd,UAAU,GACX,MAAM,iBAAiB,CAAC;AAwBzB,+EAA+E;AAC/E,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAE9B;IACA;IACA;IACA;IACA;IALX,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AAM,EAAE,CAAC;YACf,KAAK,GAAG;gBACN,OAAO,4DAA4D,IAAI,IAAI,MAAM,uDAAuD,CAAC;YAC3I,KAAK,GAAG;gBACN,OAAO,0IAA0I,MAAM,EAAE,CAAC;YAC5J,KAAK,GAAG;gBACN,OAAO,iCAAiC,IAAI,iEAAiE,MAAM,EAAE,CAAC;YACxH,KAAK,GAAG;gBACN,OAAO,6BAA6B,IAAI,qEAAqE,MAAM,EAAE,CAAC;YACxH,KAAK,GAAG;gBACN,OAAO,4BAA4B,IAAI,IAAI,MAAM,2EAA2E,CAAC;YAC/H,KAAK,GAAG;gBACN,OAAO,sHAAsH,CAAC;YAChI,KAAK,GAAG;gBACN,OAAO,qCAAqC,IAAI,IAAI,MAAM,EAAE,CAAC;YAC/D,KAAK,GAAG,CAAC,CAAC,CAAC;gBACT,MAAM,IAAI,GAAG,KAAK,CAAC,iBAAiB;oBAClC,CAAC,CAAC,aAAa,KAAK,CAAC,iBAAiB,IAAI;oBAC1C,CAAC,CAAC,uCAAuC,CAAC;gBAC5C,OAAO,CACL,6CAA6C,IAAI,GAAG;oBACpD,gEAAgE;oBAChE,uFAAuF,CACxF,CAAC;YACJ,CAAC;YACD;gBACE,IAAI,MAAM,IAAI,GAAG,EAAE,CAAC;oBAClB,OAAO,iCAAiC,MAAM,QAAQ,IAAI,gDAAgD,MAAM,EAAE,CAAC;gBACrH,CAAC;gBACD,OAAO,gCAAgC,MAAM,OAAO,IAAI,IAAI,MAAM,EAAE,CAAC;QACzE,CAAC;IACH,CAAC;IACD,IAAI,KAAK,YAAY,KAAK;QAAE,OAAO,UAAU,KAAK,CAAC,OAAO,EAAE,CAAC;IAC7D,OAAO,8BAA8B,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACvD,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Shared response shaping: field selection, pagination envelopes,
3
+ * markdown rendering and character-limit truncation.
4
+ *
5
+ * All list tools funnel through `buildListResponse` and all single-record
6
+ * tools through `buildRecordResponse`, so formatting stays consistent.
7
+ */
8
+ export declare const RESPONSE_FORMATS: readonly ["markdown", "json"];
9
+ export type ResponseFormat = (typeof RESPONSE_FORMATS)[number];
10
+ /** The pagination envelope easybill wraps every list resource in. */
11
+ export interface EasybillList<T> {
12
+ page: number;
13
+ pages: number;
14
+ limit: number;
15
+ total: number;
16
+ items: T[];
17
+ }
18
+ export type Record_ = Record<string, unknown>;
19
+ /** An MCP tool result. */
20
+ export interface ToolResult {
21
+ content: {
22
+ type: "text";
23
+ text: string;
24
+ }[];
25
+ structuredContent?: Record_;
26
+ isError?: boolean;
27
+ }
28
+ export declare function textResult(text: string, isError?: boolean): ToolResult;
29
+ /**
30
+ * Reduces a record to the requested fields.
31
+ * - `fields` omitted -> `defaults` (compact summary)
32
+ * - `["all"]` -> untouched record
33
+ * - explicit list -> exactly those keys, plus `id` so results stay addressable
34
+ *
35
+ * Falls back to the full record if the selection matches nothing, so a stale
36
+ * field list can never silently blank out a response.
37
+ */
38
+ export declare function selectFields(record: Record_, defaults: readonly string[], fields?: string[]): Record_;
39
+ export interface ListResponseOptions<T extends Record_> {
40
+ /** Raw easybill list envelope. */
41
+ list: EasybillList<T>;
42
+ /** Plural resource label used in headings, e.g. "documents". */
43
+ resource: string;
44
+ /** Compact field set used when the caller passes no `fields`. */
45
+ defaultFields: readonly string[];
46
+ fields?: string[];
47
+ format: ResponseFormat;
48
+ /** Echoed back so the agent can see what it filtered on. */
49
+ filters?: Record<string, unknown>;
50
+ }
51
+ /**
52
+ * Builds a list tool result: field-selected items, pagination metadata,
53
+ * and truncation if the payload would blow past CHARACTER_LIMIT.
54
+ */
55
+ export declare function buildListResponse<T extends Record_>(options: ListResponseOptions<T>): ToolResult;
56
+ export interface RecordResponseOptions {
57
+ record: Record_ | undefined;
58
+ /** Singular resource label, e.g. "document". */
59
+ resource: string;
60
+ defaultFields: readonly string[];
61
+ /** Single-record lookups return everything unless the caller narrows it. */
62
+ fields?: string[];
63
+ format: ResponseFormat;
64
+ /** Set when the caller asked for a compact view by default. */
65
+ compact?: boolean;
66
+ }
67
+ /** Builds a single-record tool result. */
68
+ export declare function buildRecordResponse(options: RecordResponseOptions): ToolResult;
69
+ /** Confirmation result for a mutation, echoing the affected record. */
70
+ export declare function buildMutationResponse(action: string, resource: string, record: Record_ | undefined, format: ResponseFormat, defaultFields: readonly string[]): ToolResult;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Shared response shaping: field selection, pagination envelopes,
3
+ * markdown rendering and character-limit truncation.
4
+ *
5
+ * All list tools funnel through `buildListResponse` and all single-record
6
+ * tools through `buildRecordResponse`, so formatting stays consistent.
7
+ */
8
+ import { CHARACTER_LIMIT } from "../constants.js";
9
+ export const RESPONSE_FORMATS = ["markdown", "json"];
10
+ export function textResult(text, isError = false) {
11
+ return { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) };
12
+ }
13
+ /**
14
+ * Reduces a record to the requested fields.
15
+ * - `fields` omitted -> `defaults` (compact summary)
16
+ * - `["all"]` -> untouched record
17
+ * - explicit list -> exactly those keys, plus `id` so results stay addressable
18
+ *
19
+ * Falls back to the full record if the selection matches nothing, so a stale
20
+ * field list can never silently blank out a response.
21
+ */
22
+ export function selectFields(record, defaults, fields) {
23
+ if (fields?.includes("all"))
24
+ return record;
25
+ const wanted = fields && fields.length > 0 ? ["id", ...fields] : defaults;
26
+ const result = {};
27
+ for (const key of wanted) {
28
+ if (key in record)
29
+ result[key] = record[key];
30
+ }
31
+ return Object.keys(result).length > 0 ? result : record;
32
+ }
33
+ /** Formats a value for markdown output. */
34
+ function renderValue(value) {
35
+ if (value === null || value === undefined)
36
+ return "–";
37
+ if (Array.isArray(value)) {
38
+ if (value.length === 0)
39
+ return "–";
40
+ return value.map((v) => (typeof v === "object" ? JSON.stringify(v) : String(v))).join(", ");
41
+ }
42
+ if (typeof value === "object")
43
+ return JSON.stringify(value);
44
+ if (typeof value === "boolean")
45
+ return value ? "yes" : "no";
46
+ return String(value);
47
+ }
48
+ /** Picks the most human-meaningful label available on a record. */
49
+ function recordLabel(record) {
50
+ for (const key of ["display_name", "number", "name", "title", "file_name", "description"]) {
51
+ const value = record[key];
52
+ if (typeof value === "string" && value.trim() !== "")
53
+ return value.trim();
54
+ }
55
+ return record.id !== undefined ? `#${String(record.id)}` : "(unnamed)";
56
+ }
57
+ function renderRecordMarkdown(record, heading) {
58
+ const lines = [heading, ""];
59
+ for (const [key, value] of Object.entries(record)) {
60
+ if (key === "id")
61
+ continue;
62
+ lines.push(`- **${key}**: ${renderValue(value)}`);
63
+ }
64
+ return lines.join("\n");
65
+ }
66
+ /**
67
+ * Builds a list tool result: field-selected items, pagination metadata,
68
+ * and truncation if the payload would blow past CHARACTER_LIMIT.
69
+ */
70
+ export function buildListResponse(options) {
71
+ const { list, resource, defaultFields, fields, format, filters } = options;
72
+ const rawItems = Array.isArray(list?.items) ? list.items : [];
73
+ const page = list?.page ?? 1;
74
+ const pages = list?.pages ?? 1;
75
+ const total = list?.total ?? rawItems.length;
76
+ if (rawItems.length === 0) {
77
+ const active = Object.entries(filters ?? {}).filter(([, v]) => v !== undefined && v !== null && v !== "");
78
+ const filterText = active.length
79
+ ? ` matching ${active.map(([k, v]) => `${k}=${String(v)}`).join(", ")}`
80
+ : "";
81
+ return textResult(`No ${resource} found${filterText}. ` +
82
+ `Try widening the filters, or check the spelling of any name/number filter.`);
83
+ }
84
+ const shaped = rawItems.map((item) => selectFields(item, defaultFields, fields));
85
+ const buildOutput = (items, truncation) => ({
86
+ total,
87
+ count: items.length,
88
+ page,
89
+ pages,
90
+ has_more: page < pages,
91
+ ...(page < pages ? { next_page: page + 1 } : {}),
92
+ items,
93
+ ...(truncation ? { truncated: true, truncation_message: truncation } : {}),
94
+ });
95
+ const render = (output) => {
96
+ if (format === "json")
97
+ return JSON.stringify(output, null, 2);
98
+ const items = output.items;
99
+ const lines = [
100
+ `# ${resource} (${items.length} of ${total})`,
101
+ `Page ${page} of ${pages}${output.has_more ? ` — request page ${page + 1} for more` : ""}`,
102
+ "",
103
+ ];
104
+ for (const item of items) {
105
+ lines.push(renderRecordMarkdown(item, `## ${recordLabel(item)} (id ${String(item.id)})`));
106
+ lines.push("");
107
+ }
108
+ if (output.truncation_message)
109
+ lines.push(`> ${String(output.truncation_message)}`);
110
+ return lines.join("\n");
111
+ };
112
+ let output = buildOutput(shaped);
113
+ let text = render(output);
114
+ // Halve the item count until the payload fits, so the agent still gets usable data.
115
+ if (text.length > CHARACTER_LIMIT) {
116
+ let kept = shaped.length;
117
+ while (text.length > CHARACTER_LIMIT && kept > 1) {
118
+ kept = Math.max(1, Math.floor(kept / 2));
119
+ const message = `Response truncated from ${shaped.length} to ${kept} ${resource}. ` +
120
+ `Use a smaller 'limit', add filters, or pass 'fields' to request fewer columns.`;
121
+ output = buildOutput(shaped.slice(0, kept), message);
122
+ text = render(output);
123
+ }
124
+ }
125
+ return { content: [{ type: "text", text }], structuredContent: output };
126
+ }
127
+ /** Builds a single-record tool result. */
128
+ export function buildRecordResponse(options) {
129
+ const { record, resource, defaultFields, fields, format, compact = false } = options;
130
+ if (!record || typeof record !== "object") {
131
+ return textResult(`No ${resource} returned by easybill.`);
132
+ }
133
+ // Detail views default to the complete record; compact views to the summary set.
134
+ const shaped = fields === undefined && !compact ? record : selectFields(record, defaultFields, fields);
135
+ const text = format === "json"
136
+ ? JSON.stringify(shaped, null, 2)
137
+ : renderRecordMarkdown(shaped, `# ${resource}: ${recordLabel(record)} (id ${String(record.id ?? "?")})`);
138
+ const truncated = text.length > CHARACTER_LIMIT
139
+ ? `${text.slice(0, CHARACTER_LIMIT)}\n\n> Response truncated at ${CHARACTER_LIMIT} characters. Pass 'fields' to request only the columns you need.`
140
+ : text;
141
+ return { content: [{ type: "text", text: truncated }], structuredContent: shaped };
142
+ }
143
+ /** Confirmation result for a mutation, echoing the affected record. */
144
+ export function buildMutationResponse(action, resource, record, format, defaultFields) {
145
+ if (!record || typeof record !== "object" || Object.keys(record).length === 0) {
146
+ return textResult(`${action} ${resource} succeeded.`);
147
+ }
148
+ const shaped = selectFields(record, defaultFields);
149
+ const summary = `${action} ${resource} ${recordLabel(record)} (id ${String(record.id ?? "?")}).`;
150
+ const text = format === "json"
151
+ ? JSON.stringify({ message: summary, [resource]: shaped }, null, 2)
152
+ : `${summary}\n\n${renderRecordMarkdown(shaped, `## ${resource}`)}`;
153
+ return {
154
+ content: [{ type: "text", text }],
155
+ structuredContent: { message: summary, [resource]: shaped },
156
+ };
157
+ }
158
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.js","sourceRoot":"","sources":["../../src/services/format.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,UAAU,EAAE,MAAM,CAAU,CAAC;AAqB9D,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,OAAO,GAAG,KAAK;IACtD,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACtF,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAe,EACf,QAA2B,EAC3B,MAAiB;IAEjB,IAAI,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC;IAC3C,MAAM,MAAM,GAAG,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IAE1E,MAAM,MAAM,GAAY,EAAE,CAAC;IAC3B,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,IAAI,GAAG,IAAI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AAE,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE;KAC5D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,4 @@
1
+ /** Article catalogue: positions (products/services) and their stock movements. */
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { EasybillClient } from "../services/client.js";
4
+ export declare function registerCatalogTools(server: McpServer, client: EasybillClient): void;
@@ -0,0 +1,74 @@
1
+ /** Article catalogue: positions (products/services) and their stock movements. */
2
+ import { z } from "zod";
3
+ import { SUMMARY_FIELDS } from "../constants.js";
4
+ import { multiFilter } from "../schemas/common.js";
5
+ import { registerCrudTools } from "./crud.js";
6
+ const POSITION_BODY_HINT = `Required: number, description, sale_price.
7
+
8
+ IMPORTANT: prices are INTEGERS IN CENTS — 1999 means 19.99 EUR. Never send decimal euros.
9
+
10
+ Key fields:
11
+ - number (string): article number, must be unique.
12
+ - description (string): article name shown on documents.
13
+ - sale_price (integer, CENTS): the price. Interpreted as net or gross per 'price_type'.
14
+ - price_type ('NETTO'|'BRUTTO'): whether sale_price is net or gross. Default 'NETTO'.
15
+ - vat_percent (number): VAT rate, default 19.
16
+ - cost_price (integer, CENTS): purchase price, for margin reporting.
17
+ - type ('PRODUCT'|'SERVICE'|'TEXT'): default 'PRODUCT'.
18
+ - unit (string): e.g. 'Stk.', 'h', 'm'.
19
+ - sale_price2 ... sale_price10 (integer, CENTS): tiered prices matching a customer's sale_price_level.
20
+ - stock ('YES'|'NO'): enable stock management for this article. Default 'NO'.
21
+ - stock_count (number): current stock level. Adjust it via easybill_create_stock, not here.
22
+ - stock_limit (number), stock_limit_notify (boolean): low-stock alerting.
23
+ - group_id (integer): position group.
24
+ - note, document_note (string): internal note vs. text printed on documents.
25
+ - archived (boolean).`;
26
+ export function registerCatalogTools(server, client) {
27
+ registerCrudTools(server, client, {
28
+ singular: "position",
29
+ plural: "positions",
30
+ nameSingular: "position",
31
+ namePlural: "positions",
32
+ path: "/positions",
33
+ defaultFields: SUMMARY_FIELDS.position,
34
+ operations: ["list", "get", "create", "update", "delete"],
35
+ listNotes: "Positions are the reusable article catalogue (products, services and text blocks). " +
36
+ "Referencing one by 'position_id' in a document line item copies its price and description over.\n" +
37
+ "Prices are integers in cents (1999 = 19.99 EUR).",
38
+ bodyHint: POSITION_BODY_HINT,
39
+ deleteNotes: "Documents that already reference this article keep their own copy of its data.",
40
+ filters: {
41
+ number: multiFilter("Filter by exact article number."),
42
+ type: z
43
+ .enum(["PRODUCT", "SERVICE", "TEXT"])
44
+ .optional()
45
+ .describe("Filter by article type."),
46
+ },
47
+ });
48
+ registerCrudTools(server, client, {
49
+ singular: "stock entry",
50
+ plural: "stock entries",
51
+ nameSingular: "stock_entry",
52
+ namePlural: "stock_entries",
53
+ path: "/stocks",
54
+ defaultFields: SUMMARY_FIELDS.stock,
55
+ operations: ["list", "get", "create"],
56
+ listNotes: "Stock entries are the inventory movement log for articles that have stock management " +
57
+ "enabled (position.stock = 'YES'). Each entry records a new absolute stock level.\n" +
58
+ "Filter by position_id to see one article's history.",
59
+ bodyHint: `Required: position_id and stock_count.
60
+
61
+ - position_id (integer): the article to adjust. It must have stock management enabled.
62
+ - stock_count (number): the NEW absolute stock level, not a delta.
63
+ - note (string): reason for the adjustment, e.g. 'Inventur 2026' or 'Wareneingang LS-4711'.
64
+ - stored_at (string): date of the movement, YYYY-MM-DD. Defaults to now.
65
+
66
+ Stock entries are an append-only audit log — create a new entry to correct a level
67
+ rather than editing history.`,
68
+ filters: {
69
+ position_id: multiFilter("Filter by article (position) ID."),
70
+ document_id: multiFilter("Filter by the document that triggered the movement."),
71
+ },
72
+ });
73
+ }
74
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/tools/catalog.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAGlF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAA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;;6BAQe;QACzB,OAAO,EAAE;YACP,WAAW,EAAE,WAAW,CAAC,kCAAkC,CAAC;YAC5D,WAAW,EAAE,WAAW,CAAC,qDAAqD,CAAC;SAChF;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Generic CRUD tool factory.
3
+ *
4
+ * Most easybill resources expose the same five operations over the same
5
+ * pagination envelope, so they are generated from a declarative config here
6
+ * instead of being hand-written five times per resource. Resource-specific
7
+ * behaviour (document actions, downloads, sending) lives in its own module.
8
+ */
9
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
+ import type { ZodRawShape } from "zod";
11
+ import type { EasybillClient } from "../services/client.js";
12
+ import { type Args } from "./registry.js";
13
+ export type { Args };
14
+ export type CrudOperation = "list" | "get" | "create" | "update" | "delete";
15
+ export interface ParentConfig {
16
+ /** Parameter name, e.g. "customer_id". */
17
+ param: string;
18
+ /** Path segment prefix builder, e.g. (id) => `/customers/${id}`. */
19
+ path: (parentId: number) => string;
20
+ description: string;
21
+ }
22
+ export interface CrudConfig {
23
+ /** Singular resource label, e.g. "document". */
24
+ singular: string;
25
+ /** Plural resource label used in tool names and headings, e.g. "documents". */
26
+ plural: string;
27
+ /** Tool name stem, e.g. "document" -> easybill_list_documents / easybill_get_document. */
28
+ namePlural: string;
29
+ nameSingular: string;
30
+ /** API path relative to the base URL, e.g. "/documents". */
31
+ path: string;
32
+ defaultFields: readonly string[];
33
+ /** Which operations to generate. */
34
+ operations: CrudOperation[];
35
+ /** Extra list filter parameters beyond limit/page/fields/response_format. */
36
+ filters?: ZodRawShape;
37
+ /** Prose appended to the list tool description. */
38
+ listNotes?: string;
39
+ /** Prose describing the create/update body — document the important fields here. */
40
+ bodyHint: string;
41
+ /**
42
+ * Prose placed at the very TOP of the create tool description, before the field
43
+ * reference. Use it for prerequisite ordering ("resolve the customer first").
44
+ */
45
+ createNotes?: string;
46
+ /** Extra prose for the delete tool, e.g. legal caveats. */
47
+ deleteNotes?: string;
48
+ /** Nested resource parent, e.g. contacts live under a customer. */
49
+ parent?: ParentConfig;
50
+ }
51
+ export declare function registerCrudTools(server: McpServer, client: EasybillClient, config: CrudConfig): void;