@tracken/cli 0.0.0-stage → 0.2.1

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 (143) hide show
  1. package/CHANGELOG.md +404 -0
  2. package/LICENSE +21 -0
  3. package/README.md +310 -2
  4. package/dist/bin/tracken.d.ts +2 -0
  5. package/dist/bin/tracken.js +5 -0
  6. package/dist/cli/args.d.ts +17 -0
  7. package/dist/cli/args.js +114 -0
  8. package/dist/cli/commands/api.d.ts +2 -0
  9. package/dist/cli/commands/api.js +73 -0
  10. package/dist/cli/commands/auth.d.ts +8 -0
  11. package/dist/cli/commands/auth.js +141 -0
  12. package/dist/cli/commands/mcp.d.ts +19 -0
  13. package/dist/cli/commands/mcp.js +89 -0
  14. package/dist/cli/commands/org.d.ts +24 -0
  15. package/dist/cli/commands/org.js +123 -0
  16. package/dist/cli/context.d.ts +54 -0
  17. package/dist/cli/context.js +135 -0
  18. package/dist/cli/execute.d.ts +16 -0
  19. package/dist/cli/execute.js +112 -0
  20. package/dist/cli/help.d.ts +8 -0
  21. package/dist/cli/help.js +153 -0
  22. package/dist/cli/main.d.ts +2 -0
  23. package/dist/cli/main.js +114 -0
  24. package/dist/cli/operation-args.d.ts +25 -0
  25. package/dist/cli/operation-args.js +245 -0
  26. package/dist/core/auth/oauth.d.ts +39 -0
  27. package/dist/core/auth/oauth.js +102 -0
  28. package/dist/core/auth/scopes.d.ts +19 -0
  29. package/dist/core/auth/scopes.js +49 -0
  30. package/dist/core/auth/secret-store.d.ts +60 -0
  31. package/dist/core/auth/secret-store.js +141 -0
  32. package/dist/core/auth/session.d.ts +75 -0
  33. package/dist/core/auth/session.js +200 -0
  34. package/dist/core/catalog.d.ts +12 -0
  35. package/dist/core/catalog.js +33 -0
  36. package/dist/core/client.d.ts +22 -0
  37. package/dist/core/client.js +45 -0
  38. package/dist/core/config.d.ts +27 -0
  39. package/dist/core/config.js +109 -0
  40. package/dist/core/environments.d.ts +21 -0
  41. package/dist/core/environments.js +53 -0
  42. package/dist/core/errors.d.ts +96 -0
  43. package/dist/core/errors.js +248 -0
  44. package/dist/core/index.d.ts +21 -0
  45. package/dist/core/index.js +22 -0
  46. package/dist/core/jobs.d.ts +15 -0
  47. package/dist/core/jobs.js +19 -0
  48. package/dist/core/operations.d.ts +108 -0
  49. package/dist/core/operations.js +7 -0
  50. package/dist/core/output/format.d.ts +19 -0
  51. package/dist/core/output/format.js +62 -0
  52. package/dist/core/output/render.d.ts +53 -0
  53. package/dist/core/output/render.js +229 -0
  54. package/dist/core/pagination.d.ts +2 -0
  55. package/dist/core/pagination.js +3 -0
  56. package/dist/core/request.d.ts +29 -0
  57. package/dist/core/request.js +109 -0
  58. package/dist/core/version.d.ts +10 -0
  59. package/dist/core/version.js +13 -0
  60. package/dist/generated/mcp-tools.d.ts +2 -0
  61. package/dist/generated/mcp-tools.js +5937 -0
  62. package/dist/generated/operations.d.ts +4 -0
  63. package/dist/generated/operations.js +17701 -0
  64. package/dist/mcp/errors.d.ts +34 -0
  65. package/dist/mcp/errors.js +100 -0
  66. package/dist/mcp/live.d.ts +3 -0
  67. package/dist/mcp/live.js +5 -0
  68. package/dist/mcp/prompts.d.ts +23 -0
  69. package/dist/mcp/prompts.js +101 -0
  70. package/dist/mcp/resources.d.ts +25 -0
  71. package/dist/mcp/resources.js +125 -0
  72. package/dist/mcp/server.d.ts +20 -0
  73. package/dist/mcp/server.js +59 -0
  74. package/dist/mcp/session.d.ts +60 -0
  75. package/dist/mcp/session.js +105 -0
  76. package/dist/mcp/tools.d.ts +17 -0
  77. package/dist/mcp/tools.js +181 -0
  78. package/dist/mcp/types.d.ts +25 -0
  79. package/dist/mcp/types.js +2 -0
  80. package/node_modules/@tracken/sdk/LICENSE +21 -0
  81. package/node_modules/@tracken/sdk/README.md +76 -0
  82. package/node_modules/@tracken/sdk/SOURCE.json +10 -0
  83. package/node_modules/@tracken/sdk/dist/client.d.ts +94 -0
  84. package/node_modules/@tracken/sdk/dist/client.js +258 -0
  85. package/node_modules/@tracken/sdk/dist/credentials.d.ts +60 -0
  86. package/node_modules/@tracken/sdk/dist/credentials.js +122 -0
  87. package/node_modules/@tracken/sdk/dist/decimal.d.ts +20 -0
  88. package/node_modules/@tracken/sdk/dist/decimal.js +67 -0
  89. package/node_modules/@tracken/sdk/dist/environments.d.ts +14 -0
  90. package/node_modules/@tracken/sdk/dist/environments.js +16 -0
  91. package/node_modules/@tracken/sdk/dist/errors.d.ts +150 -0
  92. package/node_modules/@tracken/sdk/dist/errors.js +190 -0
  93. package/node_modules/@tracken/sdk/dist/generated/operations.d.ts +1955 -0
  94. package/node_modules/@tracken/sdk/dist/generated/operations.js +2746 -0
  95. package/node_modules/@tracken/sdk/dist/generated/schema.d.ts +17988 -0
  96. package/node_modules/@tracken/sdk/dist/generated/schema.js +5 -0
  97. package/node_modules/@tracken/sdk/dist/index.d.ts +27 -0
  98. package/node_modules/@tracken/sdk/dist/index.js +24 -0
  99. package/node_modules/@tracken/sdk/dist/jobs.d.ts +23 -0
  100. package/node_modules/@tracken/sdk/dist/jobs.js +80 -0
  101. package/node_modules/@tracken/sdk/dist/operations.d.ts +23 -0
  102. package/node_modules/@tracken/sdk/dist/operations.js +2 -0
  103. package/node_modules/@tracken/sdk/dist/pagination.d.ts +19 -0
  104. package/node_modules/@tracken/sdk/dist/pagination.js +49 -0
  105. package/node_modules/@tracken/sdk/dist/request.d.ts +27 -0
  106. package/node_modules/@tracken/sdk/dist/request.js +10 -0
  107. package/node_modules/@tracken/sdk/dist/runtime.d.ts +22 -0
  108. package/node_modules/@tracken/sdk/dist/runtime.js +33 -0
  109. package/node_modules/@tracken/sdk/dist/tracken.d.ts +74 -0
  110. package/node_modules/@tracken/sdk/dist/tracken.js +203 -0
  111. package/node_modules/@tracken/sdk/dist/types.d.ts +130 -0
  112. package/node_modules/@tracken/sdk/dist/types.js +1 -0
  113. package/node_modules/@tracken/sdk/dist/version.d.ts +2 -0
  114. package/node_modules/@tracken/sdk/dist/version.js +2 -0
  115. package/node_modules/@tracken/sdk/package.json +42 -0
  116. package/node_modules/openapi-fetch/CHANGELOG.md +565 -0
  117. package/node_modules/openapi-fetch/CONTRIBUTING.md +102 -0
  118. package/node_modules/openapi-fetch/LICENSE +21 -0
  119. package/node_modules/openapi-fetch/README.md +122 -0
  120. package/node_modules/openapi-fetch/dist/index.cjs +547 -0
  121. package/node_modules/openapi-fetch/dist/index.cjs.map +1 -0
  122. package/node_modules/openapi-fetch/dist/index.d.cts +337 -0
  123. package/node_modules/openapi-fetch/dist/index.d.mts +335 -0
  124. package/node_modules/openapi-fetch/dist/index.d.ts +337 -0
  125. package/node_modules/openapi-fetch/dist/index.mjs +531 -0
  126. package/node_modules/openapi-fetch/dist/index.mjs.map +1 -0
  127. package/node_modules/openapi-fetch/package.json +77 -0
  128. package/node_modules/openapi-fetch/src/index.d.ts +345 -0
  129. package/node_modules/openapi-fetch/src/index.js +689 -0
  130. package/node_modules/openapi-typescript-helpers/CHANGELOG.md +98 -0
  131. package/node_modules/openapi-typescript-helpers/LICENSE +21 -0
  132. package/node_modules/openapi-typescript-helpers/README.md +5 -0
  133. package/node_modules/openapi-typescript-helpers/dist/index.cjs +3 -0
  134. package/node_modules/openapi-typescript-helpers/dist/index.cjs.map +1 -0
  135. package/node_modules/openapi-typescript-helpers/dist/index.d.cts +167 -0
  136. package/node_modules/openapi-typescript-helpers/dist/index.d.mts +167 -0
  137. package/node_modules/openapi-typescript-helpers/dist/index.d.ts +167 -0
  138. package/node_modules/openapi-typescript-helpers/dist/index.mjs +2 -0
  139. package/node_modules/openapi-typescript-helpers/dist/index.mjs.map +1 -0
  140. package/node_modules/openapi-typescript-helpers/package.json +39 -0
  141. package/openapi/SOURCE.json +10 -0
  142. package/openapi/openapi.yaml +30514 -0
  143. package/package.json +63 -4
@@ -0,0 +1,34 @@
1
+ import { type Credentials } from "../core/auth/session.js";
2
+ import { type McpSession } from "./session.js";
3
+ export interface ToolErrorPayload {
4
+ code: string;
5
+ message: string;
6
+ status?: number;
7
+ details?: Array<{
8
+ code?: string;
9
+ message?: string;
10
+ pointer?: string;
11
+ }>;
12
+ request_id?: string;
13
+ missing_scope?: string;
14
+ existing_id?: string;
15
+ retry_after?: number;
16
+ doc_url?: string;
17
+ job?: unknown;
18
+ /** What the model should do about it, when the failure says. */
19
+ action?: string;
20
+ }
21
+ /** Where a failure happened and as whom, for the advice beside it. */
22
+ export interface FailureContext {
23
+ /** What the model does once the cause is fixed: "call create_contact again", "read tracken://accounts again". */
24
+ retry: string;
25
+ environment: string;
26
+ /** `undefined` before any credentials were resolved (no session yet): a person's server. */
27
+ credentials?: "user" | "machine" | undefined;
28
+ /** The API scopes of a person's session. */
29
+ granted?: readonly string[] | undefined;
30
+ }
31
+ export declare function failureContext(session: McpSession, retry: string, credentials: Credentials | undefined): FailureContext;
32
+ export declare function failurePayload(error: unknown, context: FailureContext): ToolErrorPayload;
33
+ /** The text block of a failure: the CLI's rendering of an API error, then the action. */
34
+ export declare function failureText(error: unknown, payload: ToolErrorPayload, context: FailureContext): string;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Failures as the model reads them. Every failure of a tool call (or a resource read) becomes
3
+ * `{code, message, details, request_id, …}` plus `action`: what the model should do next, written
4
+ * for an assistant rather than for a terminal ("ask the person to run …", "do not retry"). A 401 has
5
+ * already had the client's one renewal by the time it gets here, so the action never says "retry":
6
+ * the model would only loop on a session that has ended.
7
+ */
8
+ import { apiScopesOf } from "../core/auth/scopes.js";
9
+ import { UserCredentials } from "../core/auth/session.js";
10
+ import { ApiError, AuthError, JobFailedError, NetworkError, OAuthError, OPERATION_NOT_PUBLIC, renderError, scopeToAdd, subscriptionAdvice, TrackenError, TRIAL_LIMIT_REACHED, trialLimitFacts, UsageError, } from "../core/errors.js";
11
+ import { LIVE_TOOL_NAMES } from "./live.js";
12
+ import { ScopeError } from "./session.js";
13
+ export function failureContext(session, retry, credentials) {
14
+ return {
15
+ retry,
16
+ environment: session.environment.name,
17
+ credentials: credentials?.kind,
18
+ granted: credentials instanceof UserCredentials ? apiScopesOf(credentials.current.scope) : undefined,
19
+ };
20
+ }
21
+ const login = (environment, extra = "") => `tracken login${environment === "prod" ? "" : ` --env ${environment}`}${extra}`;
22
+ /** A person's session that Tracken ID or the API no longer accepts, after the client's one renewal. */
23
+ const signInAction = (context) => `The Tracken session has ended. Ask the person to run \`${login(context.environment)}\` in a terminal, then ${context.retry}. Do not retry before they have: every call fails until they sign in.`;
24
+ const MACHINE_REFUSED_ACTION = "The API credential this server runs with (TRACKEN_CLIENT_ID) was refused: disabled, expired or rotated. Tell the person; whoever configured the server must check it under Settings → API access or set a current TRACKEN_CLIENT_ID and TRACKEN_CLIENT_SECRET. Do not retry.";
25
+ function forbiddenAction(error, context) {
26
+ if (error.code === OPERATION_NOT_PUBLIC) {
27
+ return `Tracken ${context.environment} does not serve this operation to this kind of sign-in yet. Tell the person it is not available yet; do not retry.`;
28
+ }
29
+ const add = scopeToAdd(error.admittingScopes);
30
+ if (!add)
31
+ return "Neither the session's scopes nor the person's role in this organization allow this. Tell the person; do not retry.";
32
+ if (context.credentials === "machine") {
33
+ return `The API credential this server runs with lacks the ${add} scope. Tell the person to grant it under Settings → API access (and to TRACKEN_SCOPE if that is set); do not retry before that.`;
34
+ }
35
+ // `tracken login --scope` replaces the session's scopes, so the command keeps those it holds.
36
+ const scopes = [...new Set([...(context.granted ?? []), add])];
37
+ return `This session lacks the ${add} scope. Ask the person to run \`${login(context.environment, ` --scope ${scopes.join(" ")}`)}\` in a terminal, then ${context.retry}.`;
38
+ }
39
+ /** A trial allowance is used: the model waits for its reset day, or for an owner to choose a plan. */
40
+ function trialLimitAction(error) {
41
+ const { used, resetsOn } = trialLimitFacts(error);
42
+ return resetsOn
43
+ ? `${used}; it resets on ${resetsOn}. Tell the person; do not retry before ${resetsOn}. An owner can choose a plan in the app to lift it sooner.`
44
+ : `${used} until an owner chooses a plan in the app. Tell the person; do not retry before they have.`;
45
+ }
46
+ export function failurePayload(error, context) {
47
+ if (error instanceof ApiError) {
48
+ const payload = { code: error.code, message: error.message, status: error.status };
49
+ if (error.details.length > 0)
50
+ payload.details = error.details;
51
+ if (error.requestId)
52
+ payload.request_id = error.requestId;
53
+ if (error.missingScope)
54
+ payload.missing_scope = error.missingScope;
55
+ if (error.existingId)
56
+ payload.existing_id = error.existingId;
57
+ if (error.retryAfter !== undefined && error.status === 429)
58
+ payload.retry_after = error.retryAfter;
59
+ if (error.docUrl)
60
+ payload.doc_url = error.docUrl;
61
+ const advice = subscriptionAdvice(error, context.retry);
62
+ if (error.code === TRIAL_LIMIT_REACHED)
63
+ payload.action = trialLimitAction(error);
64
+ else if (advice)
65
+ payload.action = `${advice} Tell the person; do not retry before they have acted.`;
66
+ else if (error.status === 401)
67
+ payload.action = context.credentials === "machine" ? MACHINE_REFUSED_ACTION : signInAction(context);
68
+ else if (error.status === 403)
69
+ payload.action = forbiddenAction(error, context);
70
+ return payload;
71
+ }
72
+ if (error instanceof ScopeError)
73
+ return { code: error.code, message: error.message };
74
+ if (error instanceof JobFailedError)
75
+ return { code: "JOB_FAILED", message: error.message, job: error.job };
76
+ if (error instanceof AuthError || error instanceof OAuthError) {
77
+ return { code: "NOT_SIGNED_IN", message: error.message, action: context.credentials === "machine" ? MACHINE_REFUSED_ACTION : signInAction(context) };
78
+ }
79
+ if (error instanceof NetworkError)
80
+ return { code: "NETWORK_ERROR", message: error.message };
81
+ if (error instanceof UsageError) {
82
+ return /^No organization chosen/.test(error.message)
83
+ ? {
84
+ code: "NO_ORGANIZATION",
85
+ message: `${error.message} For this server, the person can also start it with --org <id> or TRACKEN_ORG_ID; ${LIVE_TOOL_NAMES.has("get_current_user") ? "get_current_user" : "`tracken org list`"} lists their organizations.`,
86
+ }
87
+ : { code: "INVALID_REQUEST", message: error.message };
88
+ }
89
+ // CliError extends TrackenError: any failure the CLI or the SDK raised on purpose.
90
+ if (error instanceof TrackenError)
91
+ return { code: "FAILED", message: error.message };
92
+ return { code: "INTERNAL_ERROR", message: error instanceof Error ? error.message : String(error) };
93
+ }
94
+ /** The text block of a failure: the CLI's rendering of an API error, then the action. */
95
+ export function failureText(error, payload, context) {
96
+ const rendered = { environment: context.environment, credentials: context.credentials, grantedScopes: context.granted, retry: context.retry };
97
+ const text = error instanceof ApiError ? renderError(error, rendered) : `Error ${payload.code}: ${payload.message}`;
98
+ return payload.action ? `${text}\nWhat to do: ${payload.action}` : text;
99
+ }
100
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,3 @@
1
+ import type { McpToolSpec } from "./types.js";
2
+ export declare const LIVE_TOOLS: readonly McpToolSpec[];
3
+ export declare const LIVE_TOOL_NAMES: ReadonlySet<string>;
@@ -0,0 +1,5 @@
1
+ /** The tools the server lists: the generated table holds planned ones too, for when the API serves them. */
2
+ import { MCP_TOOLS } from "../generated/mcp-tools.js";
3
+ export const LIVE_TOOLS = MCP_TOOLS.filter((tool) => tool.availability === "live");
4
+ export const LIVE_TOOL_NAMES = new Set(LIVE_TOOLS.map((tool) => tool.name));
5
+ //# sourceMappingURL=live.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Prompts for common jobs. Each names the exact tools to call, in order, and where a person must
3
+ * confirm before anything is booked, issued or sent. A test checks every tool a prompt names exists.
4
+ */
5
+ import type { GetPromptResult } from "@modelcontextprotocol/server";
6
+ export interface PromptArgumentSpec {
7
+ name: string;
8
+ description: string;
9
+ required: boolean;
10
+ }
11
+ export interface PromptSpec {
12
+ name: string;
13
+ title: string;
14
+ description: string;
15
+ arguments: PromptArgumentSpec[];
16
+ /** Every tool the prompt names; the server offers the prompt only while all of them are listed. */
17
+ tools: readonly string[];
18
+ render(args: Record<string, string | undefined>): string;
19
+ }
20
+ export declare const PROMPTS: readonly PromptSpec[];
21
+ export declare function renderPrompt(spec: PromptSpec, args: Record<string, string | undefined>): GetPromptResult;
22
+ /** The JSON Schema of a prompt's arguments; prompt arguments are always strings. */
23
+ export declare function promptArgsSchema(spec: PromptSpec): Record<string, unknown>;
@@ -0,0 +1,101 @@
1
+ const SAFETY = "Money amounts are decimal strings (\"1234.50\"); show amounts and dates to the person in Estonian format (1 234,50 EUR, 31.10.2026). " +
2
+ "Never issue, post, send or start anything without the person's explicit confirmation of what you showed them.";
3
+ const given = (value, fallback) => (value && value.trim() ? value.trim() : fallback);
4
+ export const PROMPTS = [
5
+ {
6
+ name: "month_end_check",
7
+ title: "Month-end check",
8
+ description: "Check that a month is ready to close: open bank lines, unbooked documents, draft and overdue invoices, VAT, and the trial balance.",
9
+ arguments: [{ name: "month", description: "The month to check, as YYYY-MM (default: the previous month).", required: false }],
10
+ tools: ["get_organization", "list_periods", "list_bank_lines", "list_purchase_invoices", "list_documents", "list_sales_invoices", "list_vat_returns", "run_report"],
11
+ render: ({ month }) => [
12
+ `Run a month-end check for ${given(month, "the previous month")} in Tracken Accounts. Only read; change nothing.`,
13
+ "1. get_organization for the company and its fiscal year; list_periods to see whether the month's period is still open.",
14
+ "2. list_bank_lines with status=open and the month's date_from/date_to: every bank line still waiting to be reconciled.",
15
+ "3. list_purchase_invoices with status=draft (supplier invoices not yet booked) and list_documents with linked=false (uploaded documents nothing uses yet).",
16
+ "4. list_sales_invoices with status=draft (not issued) and with overdue=true (customers late to pay).",
17
+ "5. list_vat_returns to see whether the month's VAT return (KMD) is drafted, reviewed or filed.",
18
+ "6. run_report with code=trial-balance and date_from/date_to for the month; flag accounts with unexpected balances (a negative cash account, a suspense account not at zero).",
19
+ "Page through every list (cursor=next_cursor) before counting. Finish with a short checklist: what is done, what is open and who should act, with the record numbers.",
20
+ SAFETY,
21
+ ].join("\n"),
22
+ },
23
+ {
24
+ name: "record_supplier_invoice",
25
+ title: "Record a supplier invoice",
26
+ description: "Enter a supplier (purchase) invoice from what the person gives you, check it with a dry run, and book it once they confirm.",
27
+ arguments: [
28
+ { name: "details", description: "The invoice as text: supplier, number, dates, lines and amounts, or where to find it.", required: false },
29
+ { name: "document_id", description: "An uploaded document (the invoice PDF or image) to read the invoice from, if there is one.", required: false },
30
+ ],
31
+ tools: ["list_contacts", "create_contact", "list_accounts", "list_tax_codes", "list_purchase_invoices", "create_purchase_invoice", "post_purchase_invoice", "get_document", "digitize_document"],
32
+ render: ({ details, document_id }) => [
33
+ "Record a supplier invoice in Tracken Accounts.",
34
+ details ? `The invoice: ${details}` : "Ask the person for the invoice: supplier, its invoice number, invoice and due dates, lines with amounts and VAT.",
35
+ document_id
36
+ ? `The invoice is the uploaded document ${document_id}: read it with get_document and expand=extraction (after digitize_document with wait=true if nothing was read from it yet). No tool here attaches it to the invoice: once the invoice exists, tell the person to attach the document in the app or with \`tracken documents create-link\`.`
37
+ : "",
38
+ "1. Find the supplier with list_contacts (q, registry_code or vat_number). If there is none, show the person the details and, once they agree, create_contact.",
39
+ "2. Pick each line's expense account from the tracken://accounts resource or list_accounts, and its tax code from tracken://tax-codes or list_tax_codes. Check list_purchase_invoices with supplier_invoice_number first, so the invoice is not entered twice.",
40
+ "3. create_purchase_invoice with dry_run=true; show the person the lines, VAT and total it computed, and fix any error (each detail's pointer names the field).",
41
+ "4. Once they confirm, create_purchase_invoice for real (it is a draft), then post_purchase_invoice to book it into the ledger only after they confirm again.",
42
+ SAFETY,
43
+ ]
44
+ .filter(Boolean)
45
+ .join("\n"),
46
+ },
47
+ {
48
+ name: "explain_report",
49
+ title: "Explain a report",
50
+ description: "Run a financial report and explain it in plain language: what it shows, what changed and what stands out.",
51
+ arguments: [
52
+ { name: "code", description: "The report code, e.g. balance-sheet, income-statement, trial-balance (list_reports has them all).", required: true },
53
+ { name: "as_of", description: "For a point-in-time report (balance sheet): the date, YYYY-MM-DD.", required: false },
54
+ { name: "date_from", description: "For a period report: the first day, YYYY-MM-DD.", required: false },
55
+ { name: "date_to", description: "For a period report: the last day, YYYY-MM-DD.", required: false },
56
+ ],
57
+ tools: ["list_reports", "run_report"],
58
+ render: ({ code, as_of, date_from, date_to }) => [
59
+ `Explain the ${given(code, "requested")} report of this company in Tracken Accounts to a non-accountant.`,
60
+ "1. list_reports to check the code and which parameters it takes.",
61
+ `2. run_report with code=${given(code, "<code>")}${as_of ? ` as_of=${as_of}` : ""}${date_from ? ` date_from=${date_from}` : ""}${date_to ? ` date_to=${date_to}` : ""} and compare=prior_period (or prior_year) when the report supports it; follow next_cursor if it pages.`,
62
+ "3. Explain the totals first, then the three to five lines that matter most and why they moved. Name accounts by name, not code.",
63
+ "Read only: change nothing. If a figure looks wrong, say what to check rather than correcting it.",
64
+ SAFETY,
65
+ ].join("\n"),
66
+ },
67
+ {
68
+ name: "billing_run_preview",
69
+ title: "Prepare a billing run preview",
70
+ description: "Compute a billing plan's run for a period as a dry run and present it for review, without issuing anything.",
71
+ arguments: [
72
+ { name: "plan_id", description: "The billing plan (list_billing_plans finds it).", required: false },
73
+ { name: "period", description: "The period to bill: its first day, YYYY-MM-DD.", required: true },
74
+ ],
75
+ tools: ["get_billing_plan", "list_billing_plans", "list_billing_runs", "get_billing_formula_catalog", "create_billing_run"],
76
+ render: ({ plan_id, period }) => [
77
+ `Prepare the billing run for ${given(period, "the period")} in Tracken Accounts as a preview.`,
78
+ plan_id ? `The plan is ${plan_id}; get_billing_plan to read it.` : "Find the plan with list_billing_plans (approved=true) and confirm with the person which one.",
79
+ "1. list_billing_runs with the plan_id and period, to see whether this period was billed already.",
80
+ "2. get_billing_formula_catalog for the plan if a formula needs explaining.",
81
+ "3. create_billing_run with dry_run=true (finish=draft unless the person asked otherwise). Present the recipients, counts and totals, and every blocker with what would fix it.",
82
+ "4. Stop there. Starting the run for real is a separate step: create_billing_run without dry_run and with expected_fingerprint set to the preview's fingerprint, only after the person confirms the preview.",
83
+ SAFETY,
84
+ ].join("\n"),
85
+ },
86
+ ];
87
+ export function renderPrompt(spec, args) {
88
+ return {
89
+ description: spec.description,
90
+ messages: [{ role: "user", content: { type: "text", text: spec.render(args) } }],
91
+ };
92
+ }
93
+ /** The JSON Schema of a prompt's arguments; prompt arguments are always strings. */
94
+ export function promptArgsSchema(spec) {
95
+ return {
96
+ type: "object",
97
+ properties: Object.fromEntries(spec.arguments.map((argument) => [argument.name, { type: "string", description: argument.description }])),
98
+ required: spec.arguments.filter((argument) => argument.required).map((argument) => argument.name),
99
+ };
100
+ }
101
+ //# sourceMappingURL=prompts.js.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Reference data as MCP resources: the lists a model looks things up in before it writes (which
3
+ * account, which tax code, which dimension value), read through the API with the session, every
4
+ * page followed. Each resource is the records of one list operation as JSON.
5
+ */
6
+ import type { ReadResourceResult } from "@modelcontextprotocol/server";
7
+ import type { McpSession } from "./session.js";
8
+ /** A resource stops collecting here and says so; reference data larger than this belongs in a tool's paging. */
9
+ export declare const RESOURCE_RECORD_LIMIT = 5000;
10
+ export interface ResourceSpec {
11
+ /** `tracken://accounts`. */
12
+ uri: string;
13
+ name: string;
14
+ title: string;
15
+ description: string;
16
+ operationId: string;
17
+ /** Adds each record's children (a dimension's values). */
18
+ children?: {
19
+ operationId: string;
20
+ pathParam: string;
21
+ property: string;
22
+ };
23
+ }
24
+ export declare const RESOURCES: readonly ResourceSpec[];
25
+ export declare function readResource(spec: ResourceSpec, session: McpSession): Promise<ReadResourceResult>;
@@ -0,0 +1,125 @@
1
+ import { operationById } from "../core/catalog.js";
2
+ import { pageItems, pages } from "../core/pagination.js";
3
+ import { buildRequest } from "../core/request.js";
4
+ import { failureContext, failurePayload, failureText } from "./errors.js";
5
+ /** A resource stops collecting here and says so; reference data larger than this belongs in a tool's paging. */
6
+ export const RESOURCE_RECORD_LIMIT = 5000;
7
+ export const RESOURCES = [
8
+ {
9
+ uri: "tracken://accounts",
10
+ name: "accounts",
11
+ title: "Chart of accounts",
12
+ description: "Every account: code, name, type, role and default tax code. Codes differ between charts, so look up account_id by type and role here.",
13
+ operationId: "listAccounts",
14
+ },
15
+ {
16
+ uri: "tracken://tax-codes",
17
+ name: "tax-codes",
18
+ title: "Tax codes",
19
+ description: "VAT codes with their kind, rate and VAT accounts. Look up tax_code_id for invoice and posting lines here.",
20
+ operationId: "listTaxCodes",
21
+ },
22
+ {
23
+ uri: "tracken://dimensions",
24
+ name: "dimensions",
25
+ title: "Dimensions and their values",
26
+ description: "Analytical dimensions (cost centre, project, apartment, fund…), each with its values. Look up dimension value ids here.",
27
+ operationId: "listDimensions",
28
+ children: { operationId: "listDimensionValues", pathParam: "dimension_id", property: "values" },
29
+ },
30
+ {
31
+ uri: "tracken://items",
32
+ name: "items",
33
+ title: "Items",
34
+ description: "Products and services lines are built from: unit, prices, sale and purchase accounts and tax codes.",
35
+ operationId: "listItems",
36
+ },
37
+ {
38
+ uri: "tracken://object-types",
39
+ name: "object-types",
40
+ title: "Object types",
41
+ description: "The kinds of objects the organization keeps (apartments, parking spaces…) and the properties their objects hold.",
42
+ operationId: "listObjectTypes",
43
+ },
44
+ {
45
+ uri: "tracken://fiscal-years",
46
+ name: "fiscal-years",
47
+ title: "Fiscal years",
48
+ description: "The organization's fiscal years: start and end dates and kind.",
49
+ operationId: "listFiscalYears",
50
+ },
51
+ {
52
+ uri: "tracken://periods",
53
+ name: "periods",
54
+ title: "Accounting periods",
55
+ description: "Accounting periods and whether each is open or closed; postings into a closed period are refused. Check before posting into a past month.",
56
+ operationId: "listPeriods",
57
+ },
58
+ {
59
+ uri: "tracken://reports",
60
+ name: "reports",
61
+ title: "Report catalogue",
62
+ description: "The reports run_report can produce: code, name, the parameters each takes and whether it pages.",
63
+ operationId: "listReports",
64
+ },
65
+ ];
66
+ function requireOperation(operationId) {
67
+ const operation = operationById(operationId);
68
+ if (!operation)
69
+ throw new Error(`The resource list names ${operationId}, which is not a v1 operation.`);
70
+ return operation;
71
+ }
72
+ async function collect(client, operation, path, limit) {
73
+ const request = buildRequest(operation, { path });
74
+ if (!operation.paginated) {
75
+ const response = await client.send(request);
76
+ return { records: pageItems(response.body), truncated: false };
77
+ }
78
+ const records = [];
79
+ for await (const page of pages(client, request)) {
80
+ records.push(...pageItems(page.body));
81
+ if (records.length >= limit)
82
+ return { records: records.slice(0, limit), truncated: true };
83
+ }
84
+ return { records, truncated: false };
85
+ }
86
+ export async function readResource(spec, session) {
87
+ const operation = requireOperation(spec.operationId);
88
+ const childOperation = spec.children ? requireOperation(spec.children.operationId) : undefined;
89
+ let credentials;
90
+ try {
91
+ credentials = await session.credentials();
92
+ session.checkScopes(credentials, operation, spec.uri);
93
+ if (childOperation)
94
+ session.checkScopes(credentials, childOperation, spec.uri);
95
+ const client = await session.client(credentials);
96
+ const { records, truncated } = await collect(client, operation, {}, RESOURCE_RECORD_LIMIT);
97
+ let budget = RESOURCE_RECORD_LIMIT - records.length;
98
+ let childrenTruncated = false;
99
+ if (spec.children && childOperation) {
100
+ for (const record of records) {
101
+ const id = record.id;
102
+ if (typeof id !== "string")
103
+ continue;
104
+ if (budget <= 0) {
105
+ childrenTruncated = true;
106
+ break;
107
+ }
108
+ const children = await collect(client, childOperation, { [spec.children.pathParam]: id }, budget);
109
+ record[spec.children.property] = children.records;
110
+ budget -= children.records.length;
111
+ childrenTruncated ||= children.truncated;
112
+ }
113
+ }
114
+ const body = { data: records };
115
+ if (truncated || childrenTruncated)
116
+ body.truncated = `Only the first ${RESOURCE_RECORD_LIMIT} records; use the list tools with filters for the rest.`;
117
+ return { contents: [{ uri: spec.uri, mimeType: "application/json", text: JSON.stringify(body) }] };
118
+ }
119
+ catch (error) {
120
+ // Resources have no error result; the client shows the message of a failed read.
121
+ const context = failureContext(session, `read ${spec.uri} again`, credentials);
122
+ throw new Error(failureText(error, failurePayload(error, context), context));
123
+ }
124
+ }
125
+ //# sourceMappingURL=resources.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The local MCP server: a thin proxy over Tracken Accounts' public API. Tools are the live
3
+ * operations the document marks `x-mcp` (generated, see `codegen/mcp.ts`), resources the reference
4
+ * lists, prompts a few common jobs; a resource or prompt that needs an operation the API does not
5
+ * serve yet is left out. Transport-agnostic: `tracken mcp` connects it to stdio, the tests to an
6
+ * in-memory pair.
7
+ */
8
+ import { McpServer } from "@modelcontextprotocol/server";
9
+ import type { McpSession } from "./session.js";
10
+ import type { McpToolSpec } from "./types.js";
11
+ export interface CreateServerOptions {
12
+ session: McpSession;
13
+ /** Reads a file a tool uploads (`import_bank_statement`'s file_path); the disk by default. */
14
+ readFile?: (path: string) => Promise<Uint8Array>;
15
+ /** The tools to list; the live ones by default. */
16
+ tools?: readonly McpToolSpec[];
17
+ }
18
+ /** `serverInfo.description`: which API document the tools were generated from, for support and for the model. */
19
+ export declare const SERVER_DESCRIPTION: string;
20
+ export declare function createMcpServer(options: CreateServerOptions): McpServer;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The local MCP server: a thin proxy over Tracken Accounts' public API. Tools are the live
3
+ * operations the document marks `x-mcp` (generated, see `codegen/mcp.ts`), resources the reference
4
+ * lists, prompts a few common jobs; a resource or prompt that needs an operation the API does not
5
+ * serve yet is left out. Transport-agnostic: `tracken mcp` connects it to stdio, the tests to an
6
+ * in-memory pair.
7
+ */
8
+ import { fromJsonSchema, McpServer } from "@modelcontextprotocol/server";
9
+ import { operationById } from "../core/catalog.js";
10
+ import { VERSION } from "../core/version.js";
11
+ import { DOCUMENT } from "../generated/operations.js";
12
+ import { promptArgsSchema, PROMPTS, renderPrompt } from "./prompts.js";
13
+ import { readResource, RESOURCES } from "./resources.js";
14
+ import { callTool, LIVE_TOOLS } from "./tools.js";
15
+ function instructions(tools) {
16
+ return [
17
+ tools.has("get_current_user")
18
+ ? "Tracken Accounts: Estonian bookkeeping. Call get_current_user first to learn the organization and the session's scopes."
19
+ : "Tracken Accounts: Estonian bookkeeping. get_organization names the organization this server acts in.",
20
+ "Reference data (accounts, tax codes, dimensions, items, periods, reports) is in the tracken:// resources and the list tools.",
21
+ "Money is a decimal string (\"1234.50\"), never a float. Lists page: pass next_cursor back as cursor.",
22
+ "Writes need a session signed in with `tracken login --write`. Check a write with dry_run=true first, show the person the result, and issue, post, send or start nothing without their confirmation.",
23
+ ].join(" ");
24
+ }
25
+ /** `serverInfo.description`: which API document the tools were generated from, for support and for the model. */
26
+ export const SERVER_DESCRIPTION = `Tracken Accounts' public API as tools, generated from API document ${DOCUMENT.version} (accounting_software ${DOCUMENT.commit.slice(0, 9)}).`;
27
+ const isLive = (operationId) => operationId === undefined || operationById(operationId)?.availability === "live";
28
+ export function createMcpServer(options) {
29
+ const tools = options.tools ?? LIVE_TOOLS;
30
+ const listed = new Set(tools.map((tool) => tool.name));
31
+ const server = new McpServer({ name: "tracken", title: "Tracken Accounts", version: VERSION, description: SERVER_DESCRIPTION }, { instructions: instructions(listed) });
32
+ const deps = { session: options.session, ...(options.readFile ? { readFile: options.readFile } : {}) };
33
+ // A4: the audit log records which assistant acted with the person's token.
34
+ server.server.oninitialized = () => {
35
+ const client = server.server.getClientVersion();
36
+ if (client)
37
+ options.session.useAgent(client.name, client.version);
38
+ };
39
+ for (const tool of tools) {
40
+ server.registerTool(tool.name, {
41
+ title: tool.title,
42
+ description: tool.description,
43
+ inputSchema: fromJsonSchema(tool.inputSchema),
44
+ annotations: { title: tool.title, ...tool.annotations },
45
+ }, (args) => callTool(tool, args, deps));
46
+ }
47
+ for (const spec of RESOURCES) {
48
+ if (!isLive(spec.operationId) || !isLive(spec.children?.operationId))
49
+ continue;
50
+ server.registerResource(spec.name, spec.uri, { title: spec.title, description: spec.description, mimeType: "application/json" }, () => readResource(spec, options.session));
51
+ }
52
+ for (const spec of PROMPTS) {
53
+ if (!spec.tools.every((name) => listed.has(name)))
54
+ continue;
55
+ server.registerPrompt(spec.name, { title: spec.title, description: spec.description, argsSchema: fromJsonSchema(promptArgsSchema(spec)) }, (args) => renderPrompt(spec, args));
56
+ }
57
+ return server;
58
+ }
59
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Who the MCP server acts as, resolved per call rather than at start: the server must answer
3
+ * `initialize` and `tools/list` before anyone has signed in, and a `tracken login --write` or
4
+ * `tracken org use` in a terminal must take effect on the next tool call without restarting the
5
+ * client. The person's session is the CLI's own (same secret store, same refresh lock), so the CLI
6
+ * and the server can rotate its refresh token without ever presenting a spent one.
7
+ */
8
+ import type { Clock, Fetch } from "../core/auth/oauth.js";
9
+ import type { SecretStore } from "../core/auth/secret-store.js";
10
+ import { type Credentials } from "../core/auth/session.js";
11
+ import { TrackenClient } from "../core/client.js";
12
+ import type { ConfigStore } from "../core/config.js";
13
+ import type { Environment } from "../core/environments.js";
14
+ import { CliError } from "../core/errors.js";
15
+ import type { OperationSpec } from "../core/operations.js";
16
+ export interface McpSessionOptions {
17
+ environment: Environment;
18
+ env: NodeJS.ProcessEnv;
19
+ config: ConfigStore;
20
+ /** Opened once, on the first call that needs it (opening the keychain may warn on stderr). */
21
+ openStore: () => Promise<SecretStore>;
22
+ fetch: Fetch;
23
+ clock: Clock;
24
+ /** `--org` or `TRACKEN_ORG_ID`; else the organization chosen with `tracken org use`. */
25
+ organizationId?: string | undefined;
26
+ language?: string | undefined;
27
+ debug?: ((line: string) => void) | undefined;
28
+ }
29
+ /** A tool needs a scope the session was not granted. */
30
+ export declare class ScopeError extends CliError {
31
+ readonly missing: string[];
32
+ readonly granted: string[];
33
+ readonly code = "SCOPE_REQUIRED";
34
+ constructor(message: string, missing: string[], granted: string[]);
35
+ }
36
+ export declare class McpSession {
37
+ private readonly options;
38
+ private storePromise;
39
+ private machine;
40
+ private person;
41
+ constructor(options: McpSessionOptions);
42
+ get environment(): Environment;
43
+ get clock(): Clock;
44
+ private manager;
45
+ /** The machine credential from the environment, else the person's stored session as it is now. */
46
+ credentials(): Promise<Credentials>;
47
+ organizationId(): Promise<string | undefined>;
48
+ /**
49
+ * Refuses before any request when a person's session lacks a scope the operation needs, so a
50
+ * read-only session gets "sign in with --write" rather than an API 403. A machine credential's
51
+ * scopes are its own business: the API answers for them.
52
+ */
53
+ checkScopes(credentials: Credentials, operation: OperationSpec, tool: string): void;
54
+ /** `Tracken-Agent` for the API: the MCP client's own name and version, once it has said them. */
55
+ private agent;
56
+ /** From `initialize`'s clientInfo (`claude-code/2.1.0`); the CLI's own label until then. */
57
+ useAgent(name: string, version: string): void;
58
+ /** An API client for one call, with the given credentials (from `credentials()`) or the current ones. */
59
+ client(credentials?: Credentials): Promise<TrackenClient>;
60
+ }