@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,105 @@
1
+ import { apiScopesOf, isReadOnlyScope } from "../core/auth/scopes.js";
2
+ import { MachineCredentials, machineCredentialFromEnv, resolveCredentials, SessionManager, UserCredentials } from "../core/auth/session.js";
3
+ import { TrackenClient } from "../core/client.js";
4
+ import { CliError, EXIT } from "../core/errors.js";
5
+ import { agentLabel } from "../core/version.js";
6
+ /** A tool needs a scope the session was not granted. */
7
+ export class ScopeError extends CliError {
8
+ missing;
9
+ granted;
10
+ code = "SCOPE_REQUIRED";
11
+ constructor(message, missing, granted) {
12
+ super(message, EXIT.forbidden);
13
+ this.missing = missing;
14
+ this.granted = granted;
15
+ }
16
+ }
17
+ const covers = (granted, scope) => granted.includes(scope) || (isReadOnlyScope(scope) && granted.includes("read"));
18
+ export class McpSession {
19
+ options;
20
+ storePromise;
21
+ machine;
22
+ person;
23
+ constructor(options) {
24
+ this.options = options;
25
+ }
26
+ get environment() {
27
+ return this.options.environment;
28
+ }
29
+ get clock() {
30
+ return this.options.clock;
31
+ }
32
+ async manager() {
33
+ this.storePromise ??= this.options.openStore();
34
+ const { environment, config, fetch, clock } = this.options;
35
+ return new SessionManager(environment, await this.storePromise, config.directory, fetch, clock);
36
+ }
37
+ /** The machine credential from the environment, else the person's stored session as it is now. */
38
+ async credentials() {
39
+ const { environment, env, fetch, clock } = this.options;
40
+ // A machine credential never touches the secret store, so a server on a box without a keychain needs none.
41
+ const machine = machineCredentialFromEnv(env);
42
+ if (machine) {
43
+ this.machine ??= new MachineCredentials(environment, machine, fetch, clock);
44
+ return this.machine;
45
+ }
46
+ const manager = await this.manager();
47
+ const stored = await manager.load();
48
+ // Reuse the credentials while the stored session is the one they hold (they refresh it
49
+ // themselves); a new sign-in or a refresh by the CLI replaces it, a sign-out removes it.
50
+ if (this.person && stored && stored.access_token === this.person.current.access_token)
51
+ return this.person;
52
+ this.person = undefined;
53
+ this.person = (await resolveCredentials({ environment, env, manager, fetch, clock }));
54
+ return this.person;
55
+ }
56
+ async organizationId() {
57
+ return this.options.organizationId ?? (await this.options.config.organization(this.options.environment.name))?.id;
58
+ }
59
+ /**
60
+ * Refuses before any request when a person's session lacks a scope the operation needs, so a
61
+ * read-only session gets "sign in with --write" rather than an API 403. A machine credential's
62
+ * scopes are its own business: the API answers for them.
63
+ */
64
+ checkScopes(credentials, operation, tool) {
65
+ if (!(credentials instanceof UserCredentials))
66
+ return;
67
+ const granted = apiScopesOf(credentials.current.scope);
68
+ if (granted.length === 0)
69
+ return;
70
+ const missing = operation.scopes.filter((scope) => !covers(granted, scope));
71
+ if (missing.length === 0)
72
+ return;
73
+ const env = this.environment.name === "prod" ? "" : ` --env ${this.environment.name}`;
74
+ const writes = missing.filter((scope) => !isReadOnlyScope(scope));
75
+ const message = writes.length > 0
76
+ ? `${tool} changes data and needs the ${missing.join(", ")} scope, but this Tracken session is read-only (${granted.join(" ")}). ` +
77
+ `Ask the person to run \`tracken login --write${env}\` in a terminal (a write session stays signed in 24 hours unused, 7 days at most), then call ${tool} again.`
78
+ : `${tool} needs the ${missing.join(", ")} scope, which this Tracken session was not granted (${granted.join(" ")}). ` +
79
+ `Ask the person to run \`tracken login${env}\` in a terminal (read-only covers every read), then call ${tool} again.`;
80
+ throw new ScopeError(message, missing, granted);
81
+ }
82
+ /** `Tracken-Agent` for the API: the MCP client's own name and version, once it has said them. */
83
+ agent;
84
+ /** From `initialize`'s clientInfo (`claude-code/2.1.0`); the CLI's own label until then. */
85
+ useAgent(name, version) {
86
+ this.agent = agentLabel(name, version);
87
+ }
88
+ /** An API client for one call, with the given credentials (from `credentials()`) or the current ones. */
89
+ async client(credentials) {
90
+ credentials ??= await this.credentials();
91
+ const { environment, fetch, clock, language, debug } = this.options;
92
+ return new TrackenClient({
93
+ agent: this.agent,
94
+ baseUrl: environment.apiBaseUrl,
95
+ credentials,
96
+ organizationId: credentials.kind === "user" ? await this.organizationId() : undefined,
97
+ environmentName: environment.name,
98
+ fetch,
99
+ clock,
100
+ language,
101
+ debug,
102
+ });
103
+ }
104
+ }
105
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1,17 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/server";
2
+ import type { OperationSpec } from "../core/operations.js";
3
+ import { type FailureContext } from "./errors.js";
4
+ import type { McpSession } from "./session.js";
5
+ import type { McpToolSpec } from "./types.js";
6
+ export { LIVE_TOOLS } from "./live.js";
7
+ export type { ToolErrorPayload } from "./errors.js";
8
+ /** `wait=true` gives up after this long: a tool call should not hold the conversation for minutes. */
9
+ export declare const TOOL_WAIT_MS: number;
10
+ export interface ToolDeps {
11
+ session: McpSession;
12
+ readFile?: (path: string) => Promise<Uint8Array>;
13
+ }
14
+ type Args = Record<string, unknown>;
15
+ export declare function operationOf(tool: McpToolSpec): OperationSpec;
16
+ export declare function errorResult(error: unknown, context: FailureContext): CallToolResult;
17
+ export declare function callTool(tool: McpToolSpec, args: Args, deps: ToolDeps): Promise<CallToolResult>;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Calling a tool: its arguments become the operation's `OperationInput` (the same path the CLI's
3
+ * flags take), the request goes through `TrackenClient.send` (token, organization, idempotency,
4
+ * retries), and the answer comes back as structured content plus a short summary. Every failure,
5
+ * from "not signed in" to a 422 with field pointers, is a tool error the model can read and act
6
+ * on, never a protocol error.
7
+ */
8
+ import { readFile } from "node:fs/promises";
9
+ import { basename } from "node:path";
10
+ import { operationById } from "../core/catalog.js";
11
+ import { ApiError, JobFailedError, TrackenError, UsageError } from "../core/errors.js";
12
+ import { waitForJob } from "../core/jobs.js";
13
+ import { nextCursor } from "../core/pagination.js";
14
+ import { buildRequest } from "../core/request.js";
15
+ import { failureContext, failurePayload, failureText } from "./errors.js";
16
+ import { LIVE_TOOL_NAMES } from "./live.js";
17
+ export { LIVE_TOOLS } from "./live.js";
18
+ /** `wait=true` gives up after this long: a tool call should not hold the conversation for minutes. */
19
+ export const TOOL_WAIT_MS = 2 * 60_000;
20
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
21
+ export function operationOf(tool) {
22
+ const operation = operationById(tool.operationId);
23
+ // The two generated files come from one document; a mismatch means one was edited by hand.
24
+ if (!operation)
25
+ throw new Error(`MCP tool ${tool.name} names ${tool.operationId}, which is not a v1 operation; run \`npm run generate\`.`);
26
+ return operation;
27
+ }
28
+ async function toInput(tool, args, read) {
29
+ const input = {};
30
+ let wait = false;
31
+ for (const [argument, value] of Object.entries(args)) {
32
+ if (value === undefined)
33
+ continue;
34
+ const binding = tool.bindings[argument];
35
+ if (!binding)
36
+ throw new UsageError(`${tool.name} takes no argument ${argument}.`);
37
+ switch (binding.kind) {
38
+ case "path":
39
+ (input.path ??= {})[binding.name] = String(value);
40
+ break;
41
+ case "query":
42
+ (input.query ??= {})[binding.name] = value;
43
+ break;
44
+ case "header":
45
+ (input.headers ??= {})[binding.name] = String(value);
46
+ break;
47
+ case "data":
48
+ input.data = value;
49
+ break;
50
+ case "option":
51
+ (input.options ??= {})[binding.name] = value;
52
+ break;
53
+ case "form":
54
+ (input.form ??= {})[binding.name] = String(value);
55
+ break;
56
+ case "file": {
57
+ const path = String(value);
58
+ let bytes;
59
+ try {
60
+ bytes = await read(path);
61
+ }
62
+ catch (error) {
63
+ throw new UsageError(`Could not read ${path}: ${error.message}`);
64
+ }
65
+ (input.form ??= {})[binding.name] = new File([bytes], basename(path));
66
+ break;
67
+ }
68
+ case "wait":
69
+ wait = value === true;
70
+ break;
71
+ }
72
+ }
73
+ return { input, wait };
74
+ }
75
+ /** A few words that identify a record: its number, name or code, and its status. */
76
+ function label(record) {
77
+ const identity = ["number", "name", "code", "title"].map((key) => record[key]).find((value) => typeof value === "string" && value);
78
+ const parts = [typeof record.id === "string" ? record.id : undefined, identity, typeof record.status === "string" ? `status ${record.status}` : undefined];
79
+ return parts.filter(Boolean).join(", ");
80
+ }
81
+ /**
82
+ * How the model checks on background work it started: `get_job` for a `Job`, else the list tool of
83
+ * the record's collection (a billing run is its own job). Never "call this tool again": starting a
84
+ * billing run twice is `409 BILLING_RUN_IN_PROGRESS`, or a re-run of a finished period.
85
+ */
86
+ function followUp(tool, operation, data) {
87
+ const id = isRecord(data) && typeof data.id === "string" ? data.id : undefined;
88
+ if (isRecord(data) && typeof data.type === "string" && typeof data.status === "string" && id && LIVE_TOOL_NAMES.has("get_job")) {
89
+ return `Check it with get_job id="${id}"; do not call ${tool.name} again for it.`;
90
+ }
91
+ const collection = operation.path.replace(/:[^/]*$/, "").replace(/\/\{[^}]+\}$/, "").split("/")[1] ?? "";
92
+ const list = `list_${collection.replace(/-/g, "_")}`;
93
+ const where = LIVE_TOOL_NAMES.has(list) ? `Check it with ${list}${id ? ` (its id is ${id})` : ""}` : "Check on it later";
94
+ return `${where}; do not call ${tool.name} again for it.`;
95
+ }
96
+ function summarize(tool, operation, response, cursor) {
97
+ const body = response.body;
98
+ const data = isRecord(body) ? body.data : undefined;
99
+ if (response.status === 204 || body === undefined)
100
+ return `${operation.summary}: done.`;
101
+ if (Array.isArray(data)) {
102
+ const count = `${data.length} record${data.length === 1 ? "" : "s"}`;
103
+ if (!operation.paginated)
104
+ return `${operation.summary}: ${count}.`;
105
+ return cursor
106
+ ? `${operation.summary}: ${count} on this page; more exist. Call ${tool.name} again with the same arguments and cursor="${cursor}" for the next page.`
107
+ : `${operation.summary}: ${count}; that is all.`;
108
+ }
109
+ if (isRecord(data) && Array.isArray(data.rows)) {
110
+ const rows = `${data.rows.length} row${data.rows.length === 1 ? "" : "s"}`;
111
+ return cursor ? `${operation.summary}: ${rows} on this page; call ${tool.name} again with cursor="${cursor}" for more.` : `${operation.summary}: ${rows}.`;
112
+ }
113
+ if (response.status === 202) {
114
+ const job = isRecord(data) ? label(data) : "";
115
+ return `Accepted (${job || "background work"}): it continues in the background. ${followUp(tool, operation, data)}`;
116
+ }
117
+ return isRecord(data) ? `${operation.summary}: ${label(data) || "done"}.` : `${operation.summary}: done.`;
118
+ }
119
+ function successResult(tool, operation, response, dryRun, notes) {
120
+ const body = response.body;
121
+ const structured = isRecord(body) ? { ...body } : { data: body ?? null };
122
+ let cursor;
123
+ if (operation.paginated) {
124
+ cursor = nextCursor(body) ?? null;
125
+ structured.next_cursor = cursor;
126
+ }
127
+ const lines = [];
128
+ if (dryRun) {
129
+ structured.dry_run = response.dryRun;
130
+ lines.push(response.dryRun
131
+ ? "Dry run: the API checked the request and stored, posted and sent nothing."
132
+ : "Warning: the API did not confirm the dry run (no Tracken-Dry-Run header); check what it did before going on.");
133
+ }
134
+ lines.push(summarize(tool, operation, response, cursor), ...notes);
135
+ return {
136
+ content: [
137
+ { type: "text", text: lines.join("\n") },
138
+ // Clients that ignore structured content still give the model the data.
139
+ { type: "text", text: JSON.stringify(structured) },
140
+ ],
141
+ structuredContent: structured,
142
+ };
143
+ }
144
+ export function errorResult(error, context) {
145
+ const payload = failurePayload(error, context);
146
+ return { isError: true, content: [{ type: "text", text: failureText(error, payload, context) }], structuredContent: { error: payload } };
147
+ }
148
+ export async function callTool(tool, args, deps) {
149
+ let credentials;
150
+ try {
151
+ const operation = operationOf(tool);
152
+ const { input, wait } = await toInput(tool, args, deps.readFile ?? ((path) => readFile(path)));
153
+ const request = buildRequest(operation, input);
154
+ credentials = await deps.session.credentials();
155
+ deps.session.checkScopes(credentials, operation, tool.name);
156
+ const client = await deps.session.client(credentials);
157
+ const dryRun = input.query?.dry_run === true;
158
+ let response = await client.send(request);
159
+ const notes = [];
160
+ if (response.status === 202 && wait && !dryRun) {
161
+ try {
162
+ response = await waitForJob(client, response, request, {
163
+ timeoutMs: TOOL_WAIT_MS,
164
+ now: () => deps.session.clock.now(),
165
+ sleep: (ms) => deps.session.clock.sleep(ms),
166
+ });
167
+ }
168
+ catch (error) {
169
+ if (error instanceof JobFailedError || error instanceof ApiError || !(error instanceof TrackenError))
170
+ throw error;
171
+ // Still running after the wait, or nothing to poll: answer with what the API accepted.
172
+ notes.push(error.message.replace(/ Poll it with `tracken api GET [^`]+`\./, ""));
173
+ }
174
+ }
175
+ return successResult(tool, operation, response, dryRun, notes);
176
+ }
177
+ catch (error) {
178
+ return errorResult(error, failureContext(deps.session, `call ${tool.name} again`, credentials));
179
+ }
180
+ }
181
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1,25 @@
1
+ /** The shape of the generated MCP tool list (`src/generated/mcp-tools.ts`, made by `codegen/mcp.ts`). */
2
+ import type { Availability } from "../core/operations.js";
3
+ /** Where a tool argument goes in the request. */
4
+ export type McpBindingKind = "path" | "query" | "header" | "data" | "option" | "form" | "file" | "wait";
5
+ export interface McpBinding {
6
+ kind: McpBindingKind;
7
+ /** The wire name (`dry_run`, `If-Match`, `bank_account_id`, the form field `file`). */
8
+ name: string;
9
+ }
10
+ export interface McpToolSpec {
11
+ /** The document's `x-mcp` name: the operation id in snake_case. */
12
+ name: string;
13
+ operationId: string;
14
+ /** The operation's summary. */
15
+ title: string;
16
+ /** The `x-mcp` description, then what the server adds: dry runs, paging, background work, scopes. */
17
+ description: string;
18
+ /** `x-mcp` annotations as the document states them. */
19
+ annotations: Record<string, boolean>;
20
+ inputSchema: Record<string, unknown>;
21
+ /** Tool argument → request location; every property of `inputSchema` has one. */
22
+ bindings: Record<string, McpBinding>;
23
+ /** The server lists only `live` tools; `planned` ones wait for the API to serve them. */
24
+ availability: Exclude<Availability, "later">;
25
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tracken Technologies OÜ
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.
@@ -0,0 +1,76 @@
1
+ # @tracken/sdk
2
+
3
+ A typed TypeScript client for Tracken Accounts' public API, generated from its public document.
4
+ Every v1 operation is a method on its resource, named the way the `tracken` CLI names its commands;
5
+ inputs and answers are typed from the document, and every call shares the CLI's transport: the token,
6
+ retries, an automatic `Idempotency-Key` and the 303 download of a rendition.
7
+
8
+ Published on npm as `@tracken/sdk` (`npm i @tracken/sdk`, Node.js 22 or later); the API it calls is still a
9
+ draft, so a release may break a client; the `@tracken/cli` package's `CHANGELOG.md` lists every change.
10
+ MIT license (`LICENSE`).
11
+
12
+ ```ts
13
+ import { Tracken, isApiError } from "@tracken/sdk";
14
+
15
+ const tracken = new Tracken({
16
+ environment: "dev", // or "prod" (the default)
17
+ auth: { clientId: process.env.TRACKEN_CLIENT_ID!, clientSecret: process.env.TRACKEN_CLIENT_SECRET! },
18
+ });
19
+
20
+ // Lists: one page, or every record across pages.
21
+ const page = await tracken.salesInvoices.list({ query: { status: ["draft"], limit: 50 } });
22
+ for await (const invoice of tracken.paginate("listSalesInvoices", { query: { status: ["draft"] } })) {
23
+ // Actions after the colon are methods: POST /sales-invoices/{id}:issue
24
+ try {
25
+ await tracken.salesInvoices.issue({ path: { id: invoice.id } }, { idempotencyKey: `issue-${invoice.id}` });
26
+ } catch (error) {
27
+ if (isApiError(error, "INVOICE_NOT_DRAFT")) continue;
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ // A rendition: the file's bytes.
33
+ const pdf = await tracken.salesInvoices.get({ path: { id }, query: { format: "pdf" } });
34
+
35
+ // Concurrency: send the ETag of the version you read.
36
+ const contact = await tracken.contacts.get({ path: { id } });
37
+ await tracken.contacts.update({ path: { id }, body: { data: { name: "Acme AS" } } }, { ifMatch: contact });
38
+ ```
39
+
40
+ ## Conventions
41
+
42
+ - **Bodies** are the document's: the record inside `{"data": …}`, with operation options such as
43
+ `on_conflict` beside it. `body` of an upload is a `FormData` or an object of its fields (`Blob`s for files).
44
+ - **Money, prices and quantities are decimal strings** (`"1234.50"`), never numbers. The types say
45
+ `string`, and a JavaScript number where the document expects a decimal is refused before the request
46
+ is sent. `isDecimal`, `toMinorUnits` and `fromMinorUnits` (exact, with `bigint`) help with arithmetic.
47
+ - **Answers** are `{ body, status, headers, requestId, etag, location, dryRun }`; `body` is the
48
+ parsed JSON, the file's bytes for a rendition, and `undefined` for a `204`.
49
+ - **Errors** are `TrackenApiError`s, of the subclass the status names (`TrackenValidationError`,
50
+ `TrackenConflictError`, `TrackenPreconditionFailedError`, `TrackenRateLimitedError`, …), with the
51
+ stable `code`, every field problem in `details`, `existingId`, `context` and `requestId`.
52
+ `isApiError(error, "CODE")` narrows to one code. The client retries `429` (after `Retry-After`),
53
+ gateway errors and network failures; requests it refuses to send throw `TrackenUsageError`.
54
+ - **The subscription's refusals** are never retried. A `402` is a `TrackenPaymentRequiredError`
55
+ (`reason`, `exportUntil`). A `409 TRIAL_LIMIT_REACHED` is a `TrackenTrialLimitError`, still a
56
+ `TrackenConflictError`: a free trial's allowance is used, `limit` names it (an open list), `max` is
57
+ its number and `resetsOn` the day it resets; do not retry before then.
58
+ - **Idempotency**: every POST carries an `Idempotency-Key`, reused on the client's own retries; pass
59
+ `idempotencyKey` to make your own retries safe too.
60
+ - **Jobs**: an operation that answers `202` returns the job; `tracken.waitForJob(response)` polls it.
61
+ - **Sync**: read changes with `updated_since` (and `sort: "updated_at"`); each answer's `nextSince`
62
+ is where the next pass starts.
63
+ - **A 401 is never masked**: the client renews once (a fresh client-credentials token, or your
64
+ `Credentials.renew`) and retries; a second 401, or a renewal Tracken ID refuses, is thrown as the
65
+ API's own `TrackenUnauthenticatedError`, with the refusal as `renewalError`.
66
+ - **Tracken-Agent**: every request names the program acting (`tracken-sdk/<version>` by default;
67
+ pass `agent: agentLabel("acme-sync", "2.1")`), which Accounts records in its audit log.
68
+ - **Any operation** by id: `tracken.call("issueSalesInvoice", { path: { id } })`; raw requests through
69
+ `tracken.client.send(…)`, and the typed openapi-fetch client as `tracken.http`.
70
+
71
+ Auth: `{ clientId, clientSecret, scope? }` for a machine credential (exchanged at Tracken ID with the
72
+ client-credentials grant and renewed as it nears expiry), `{ accessToken }` for a token you obtained
73
+ yourself, or any `Credentials` object. A person's token acts in one organization: pass
74
+ `organizationId`.
75
+
76
+ `DOCUMENT` names the public document (and its commit) this version was generated from.
@@ -0,0 +1,10 @@
1
+ {
2
+ "repository": "Tracken-Technologies/tracken_accounts",
3
+ "path": "accounting-api/public_api/openapi.yaml",
4
+ "commit": "24e91d23078ce4360a7ce9477439358e90f8e553",
5
+ "ref": "24e91d230",
6
+ "dirty": false,
7
+ "document_version": "2026-11-09",
8
+ "sha256": "5c6a3a21654ee6eae6b0ced16f12106733c595f17f9c03306db6102c4100e5b4",
9
+ "synced_at": "2026-11-15T21:29:43Z"
10
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The transport every Tracken client shares (the SDK's typed methods, the CLI and its MCP server):
3
+ * requests go through openapi-fetch with the credential's bearer token, the organization header for a
4
+ * person, a User-Agent and `Tracken-Agent`, an automatic Idempotency-Key on every POST (the same key
5
+ * on the client's own retries), `Retry-After` on 429 and backoff on a gateway error. A rendition's 303
6
+ * is followed to its pre-signed link without any of those credentials.
7
+ *
8
+ * A 401 is never masked: the client renews once (a person's refresh, or a fresh client-credentials
9
+ * token) and retries; a second 401, or a renewal Tracken ID refuses, is thrown as the API's own 401
10
+ * (`TrackenUnauthenticatedError`, with the refusal as `renewalError`). The credentials a client is
11
+ * built with are the only ones it ever uses.
12
+ */
13
+ import { type Client } from "openapi-fetch";
14
+ import type { Credentials } from "./credentials.js";
15
+ import type { paths } from "./generated/schema.js";
16
+ import { type ApiRequest } from "./request.js";
17
+ import { type Clock, type Fetch } from "./runtime.js";
18
+ export interface ApiResponse {
19
+ status: number;
20
+ headers: Headers;
21
+ /** Parsed JSON; a `Uint8Array` for other content (a PDF, a KMD file); `undefined` for 204. */
22
+ body: unknown;
23
+ contentType: string;
24
+ binary: boolean;
25
+ requestId: string | undefined;
26
+ /** The API confirmed nothing was stored (`Tracken-Dry-Run: true`). */
27
+ dryRun: boolean;
28
+ }
29
+ export interface ClientOptions {
30
+ /** The API base including the major version (`https://accounts-api.tracken.ee/v1`). */
31
+ baseUrl: string;
32
+ credentials: Credentials;
33
+ /** The organization a person's requests act in (`X-Organization-ID`); a machine token names its own. */
34
+ organizationId?: string | undefined;
35
+ fetch?: Fetch;
36
+ clock?: Clock;
37
+ /** `et` or `en`: the language of error messages. */
38
+ language?: string | undefined;
39
+ /** Retries after 429, gateway errors and network failures (default 3). */
40
+ maxRetries?: number;
41
+ /** Sent as `User-Agent` (default `tracken-sdk/<version> (…)`). */
42
+ userAgent?: string;
43
+ /**
44
+ * Sent as `Tracken-Agent` (default `tracken-sdk/<version>`): the program acting with the token,
45
+ * which Accounts records in the audit log. Make it acceptable with `agentLabel(name, version)`.
46
+ */
47
+ agent?: string | undefined;
48
+ /**
49
+ * Whether an error `Credentials.renew` threw means Tracken ID refused the session or credential
50
+ * (the 401 is then thrown as the API's own); other errors propagate. Default: `TrackenAuthError`.
51
+ */
52
+ isRenewalRefusal?: (error: unknown) => boolean;
53
+ /** The message when a person's request needs an organization and none is set. */
54
+ missingOrganizationMessage?: string;
55
+ debug?: ((line: string) => void) | undefined;
56
+ }
57
+ /** The organization header is credentials, never a parameter: a person's token always names one. */
58
+ export declare const ORGANIZATION_HEADER = "X-Organization-ID";
59
+ /** A fresh `Idempotency-Key`: a random UUID, from the platform's Web Crypto. */
60
+ export declare function newIdempotencyKey(): string;
61
+ export declare class TrackenClient {
62
+ private readonly options;
63
+ /**
64
+ * The typed openapi-fetch client, for callers that know their operation at compile time: it adds
65
+ * the token, User-Agent and organization header, but neither retries nor renews; `send` does both.
66
+ */
67
+ readonly http: Client<paths>;
68
+ /** `send`'s own client: no middleware, since `send` sets every header itself per attempt. */
69
+ private readonly transport;
70
+ private readonly maxRetries;
71
+ private readonly clock;
72
+ private readonly userAgent;
73
+ private readonly agent;
74
+ constructor(options: ClientOptions);
75
+ get credentials(): Credentials;
76
+ get baseUrl(): string;
77
+ /** For `http` users: the token, User-Agent and organization header on every request. */
78
+ private authMiddleware;
79
+ private organizationFor;
80
+ private retryable;
81
+ private backoff;
82
+ /**
83
+ * Sends a request and answers its success, or throws a `TrackenApiError` for a non-2xx answer once
84
+ * retries are spent. `organization: null` leaves the organization header off.
85
+ */
86
+ send(request: ApiRequest): Promise<ApiResponse>;
87
+ /**
88
+ * A rendition (`format=pdf`) answers 303 with a short-lived pre-signed link to the file. The link
89
+ * carries its own signature, so it is fetched with neither the token nor the organization header
90
+ * (a storage service refuses a second credential, and the token must not leave the API). The link
91
+ * is itself a credential while it lives: messages name its origin only.
92
+ */
93
+ private download;
94
+ }