@labelgrid/mcp 0.2.2 → 0.3.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 (62) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +132 -100
  3. package/dist/config.d.ts +15 -0
  4. package/dist/config.js +38 -6
  5. package/dist/coverage.js +79 -79
  6. package/dist/gating.d.ts +1 -1
  7. package/dist/gating.js +5 -1
  8. package/dist/index.js +1 -2
  9. package/dist/projection.d.ts +40 -0
  10. package/dist/projection.js +145 -0
  11. package/dist/resources.d.ts +29 -0
  12. package/dist/resources.js +107 -0
  13. package/dist/server.d.ts +2 -2
  14. package/dist/server.js +24 -4
  15. package/dist/tools/account.d.ts +3 -0
  16. package/dist/tools/account.js +32 -0
  17. package/dist/tools/all.js +12 -20
  18. package/dist/tools/catalog.d.ts +14 -0
  19. package/dist/tools/catalog.js +266 -0
  20. package/dist/tools/distribution.d.ts +13 -0
  21. package/dist/tools/distribution.js +265 -0
  22. package/dist/tools/finance.d.ts +12 -0
  23. package/dist/tools/finance.js +311 -0
  24. package/dist/tools/insights.d.ts +7 -0
  25. package/dist/tools/insights.js +139 -0
  26. package/dist/tools/reference.js +9 -24
  27. package/dist/tools/releases.d.ts +11 -0
  28. package/dist/tools/releases.js +177 -0
  29. package/dist/tools/setup.js +1 -1
  30. package/dist/tools/types.d.ts +1 -1
  31. package/dist/tools/webhooks.d.ts +3 -3
  32. package/dist/tools/webhooks.js +73 -105
  33. package/package.json +5 -14
  34. package/server.json +3 -3
  35. package/dist/api/content-types.d.ts +0 -33
  36. package/dist/api/content-types.js +0 -87
  37. package/dist/api/http.d.ts +0 -74
  38. package/dist/api/http.js +0 -392
  39. package/dist/api/upload.d.ts +0 -26
  40. package/dist/api/upload.js +0 -104
  41. package/dist/log.d.ts +0 -16
  42. package/dist/log.js +0 -35
  43. package/dist/tools/accounting.d.ts +0 -12
  44. package/dist/tools/accounting.js +0 -386
  45. package/dist/tools/analytics.d.ts +0 -3
  46. package/dist/tools/analytics.js +0 -62
  47. package/dist/tools/catalog-read.d.ts +0 -10
  48. package/dist/tools/catalog-read.js +0 -145
  49. package/dist/tools/catalog-write.d.ts +0 -12
  50. package/dist/tools/catalog-write.js +0 -206
  51. package/dist/tools/delivery.d.ts +0 -6
  52. package/dist/tools/delivery.js +0 -40
  53. package/dist/tools/files-read.d.ts +0 -7
  54. package/dist/tools/files-read.js +0 -86
  55. package/dist/tools/full-writes.d.ts +0 -12
  56. package/dist/tools/full-writes.js +0 -248
  57. package/dist/tools/identity.d.ts +0 -3
  58. package/dist/tools/identity.js +0 -28
  59. package/dist/tools/release-write.d.ts +0 -12
  60. package/dist/tools/release-write.js +0 -184
  61. package/dist/tools/review-read.d.ts +0 -7
  62. package/dist/tools/review-read.js +0 -78
@@ -1,74 +0,0 @@
1
- /**
2
- * The single typed HTTP client for the LabelGrid public API.
3
- *
4
- * Every tool goes through this client. It owns transport, header injection,
5
- * query serialization, optional idempotency keys and — critically — error
6
- * normalization: HTTP failures are turned into a structured {@link ApiError}
7
- * and returned, never thrown. Business rules live server-side; this file is
8
- * transport only (no retries, no queues).
9
- */
10
- export type ApiError = {
11
- code: string;
12
- message: string;
13
- status: number;
14
- field?: string;
15
- suggestion?: string;
16
- retry_after_seconds?: number;
17
- errors?: unknown;
18
- /** Structured validation detail passed through verbatim from the API (422). */
19
- errors_structured?: unknown;
20
- };
21
- export type ApiResult<T = unknown> = {
22
- data: T;
23
- } | {
24
- error: ApiError;
25
- };
26
- export declare class LabelGridClient {
27
- private readonly baseUrl;
28
- private readonly token;
29
- private readonly fetchFn;
30
- private readonly version;
31
- private readonly timeoutMs;
32
- private readonly rawTimeoutMs;
33
- constructor(opts: {
34
- baseUrl: string;
35
- token: string;
36
- fetchFn?: typeof fetch;
37
- version: string;
38
- /** API request timeout (default 60s) — a hung call must never hang a tool. */
39
- timeoutMs?: number;
40
- /** Timeout for raw transfers like presigned uploads (default 10min). */
41
- rawTimeoutMs?: number;
42
- });
43
- private authHeaders;
44
- private send;
45
- /**
46
- * Reads a response body with the byte ceiling enforced mid-stream. Returns
47
- * the decoded text, or the supplied too-large error result when the ceiling
48
- * is crossed. Abort/timeout rejections propagate to the caller for mapping.
49
- */
50
- private readBody;
51
- get<T>(path: string, query?: Record<string, unknown>): Promise<ApiResult<T>>;
52
- post<T>(path: string, body?: unknown, opts?: {
53
- idempotency?: boolean;
54
- idempotencyKey?: string;
55
- }): Promise<ApiResult<T>>;
56
- patch<T>(path: string, body?: unknown): Promise<ApiResult<T>>;
57
- put<T>(path: string, body?: unknown, opts?: {
58
- idempotency?: boolean;
59
- idempotencyKey?: string;
60
- }): Promise<ApiResult<T>>;
61
- delete<T>(path: string): Promise<ApiResult<T>>;
62
- /**
63
- * Sends a multipart/form-data POST with a single file field plus optional
64
- * extra string fields. A missing/unreadable file yields a FILE_NOT_FOUND
65
- * error result rather than throwing.
66
- */
67
- postMultipart<T>(path: string, filePath: string, fieldName: string, extra?: Record<string, string>): Promise<ApiResult<T>>;
68
- /**
69
- * Performs a raw request with NO Authorization header — used for presigned
70
- * upload PUTs, where the signed URL is already the credential and an extra
71
- * Bearer token would break the signature.
72
- */
73
- raw(url: string, init: RequestInit): Promise<Response>;
74
- }
package/dist/api/http.js DELETED
@@ -1,392 +0,0 @@
1
- /**
2
- * The single typed HTTP client for the LabelGrid public API.
3
- *
4
- * Every tool goes through this client. It owns transport, header injection,
5
- * query serialization, optional idempotency keys and — critically — error
6
- * normalization: HTTP failures are turned into a structured {@link ApiError}
7
- * and returned, never thrown. Business rules live server-side; this file is
8
- * transport only (no retries, no queues).
9
- */
10
- import { randomUUID } from 'node:crypto';
11
- import { readFile } from 'node:fs/promises';
12
- import { basename } from 'node:path';
13
- import { contentType } from './content-types.js';
14
- /** Hard ceiling on a single response body, in bytes/characters. */
15
- const MAX_RESPONSE_BYTES = 10_000_000;
16
- const TOKEN_SUGGESTION = 'Check LABELGRID_API_TOKEN — create a new token in your dashboard under Profile → API Tokens.';
17
- /**
18
- * Serializes a query object into a URL search string, supporting nested
19
- * `filter[label_id]=5` objects and repeated `metrics[]=a&metrics[]=b` arrays.
20
- * Null/undefined values are skipped. Bracket structure is kept literal; only
21
- * key names and values are percent-encoded.
22
- */
23
- function buildQuery(query) {
24
- if (!query)
25
- return '';
26
- const parts = [];
27
- const push = (rawKey, value) => {
28
- if (value === undefined || value === null)
29
- return;
30
- parts.push(`${rawKey}=${encodeURIComponent(String(value))}`);
31
- };
32
- for (const [key, value] of Object.entries(query)) {
33
- if (value === undefined || value === null)
34
- continue;
35
- const ek = encodeURIComponent(key);
36
- if (Array.isArray(value)) {
37
- for (const item of value)
38
- push(`${ek}[]`, item);
39
- }
40
- else if (typeof value === 'object') {
41
- for (const [subKey, subValue] of Object.entries(value)) {
42
- const esk = encodeURIComponent(subKey);
43
- if (Array.isArray(subValue)) {
44
- for (const item of subValue)
45
- push(`${ek}[${esk}][]`, item);
46
- }
47
- else {
48
- push(`${ek}[${esk}]`, subValue);
49
- }
50
- }
51
- }
52
- else {
53
- push(ek, value);
54
- }
55
- }
56
- return parts.length > 0 ? `?${parts.join('&')}` : '';
57
- }
58
- /**
59
- * Extracts a code/message/errors triple from any of the four backend error body
60
- * shapes: `{message}`, `{error: string}`, `{errors}`, `{error: {code, message}}`.
61
- */
62
- function extractServerError(body) {
63
- if (typeof body === 'string') {
64
- return { message: body };
65
- }
66
- if (body === null || typeof body !== 'object') {
67
- return {};
68
- }
69
- const record = body;
70
- const errors = record.errors;
71
- const errorsStructured = record.errors_structured;
72
- // Shape: { error: { code, message } }
73
- if (record.error !== null && typeof record.error === 'object') {
74
- const nested = record.error;
75
- return {
76
- code: typeof nested.code === 'string' ? nested.code : undefined,
77
- message: typeof nested.message === 'string'
78
- ? nested.message
79
- : typeof nested.error === 'string'
80
- ? nested.error
81
- : undefined,
82
- errors,
83
- errors_structured: errorsStructured,
84
- };
85
- }
86
- // Shape: { error: 'string' }
87
- if (typeof record.error === 'string') {
88
- return {
89
- code: typeof record.code === 'string' ? record.code : undefined,
90
- message: record.error,
91
- errors,
92
- errors_structured: errorsStructured,
93
- };
94
- }
95
- // Shapes: { message } and/or { errors } and/or top-level { code }
96
- const parts = {
97
- code: typeof record.code === 'string' ? record.code : undefined,
98
- message: typeof record.message === 'string' ? record.message : undefined,
99
- field: typeof record.field === 'string' ? record.field : undefined,
100
- errors,
101
- errors_structured: errorsStructured,
102
- };
103
- // Derive a message from the first validation error when none was given.
104
- if (parts.message === undefined && errors !== null && typeof errors === 'object') {
105
- const first = Object.values(errors)[0];
106
- if (Array.isArray(first) && typeof first[0] === 'string') {
107
- parts.message = first[0];
108
- }
109
- else if (typeof first === 'string') {
110
- parts.message = first;
111
- }
112
- }
113
- return parts;
114
- }
115
- function parseRetryAfter(res) {
116
- const raw = res.headers.get('Retry-After');
117
- if (raw === null)
118
- return undefined;
119
- const seconds = Number.parseInt(raw, 10);
120
- return Number.isNaN(seconds) ? undefined : seconds;
121
- }
122
- /** Normalizes a non-2xx HTTP response into a structured {@link ApiError}. */
123
- function normalizeError(res, body) {
124
- const server = extractServerError(body);
125
- const status = res.status;
126
- const withCommon = (code, message, extra = {}) => ({
127
- code,
128
- message,
129
- status,
130
- ...(server.field !== undefined ? { field: server.field } : {}),
131
- ...(server.errors !== undefined ? { errors: server.errors } : {}),
132
- ...extra,
133
- });
134
- switch (status) {
135
- case 401:
136
- return withCommon('TOKEN_INVALID', server.message ?? 'Your API token was rejected.', {
137
- suggestion: TOKEN_SUGGESTION,
138
- });
139
- case 403:
140
- return withCommon(server.code ?? 'FORBIDDEN', server.message ?? 'Forbidden.');
141
- case 404:
142
- return withCommon('NOT_FOUND', server.message ?? 'The requested resource was not found.');
143
- case 409:
144
- return withCommon(server.code ?? 'CONFLICT', server.message ?? 'The request conflicts with the current state.');
145
- case 422:
146
- return withCommon('VALIDATION_FAILED', server.message ?? 'The submitted data was invalid.', {
147
- ...(server.errors_structured !== undefined
148
- ? { errors_structured: server.errors_structured }
149
- : {}),
150
- });
151
- case 429: {
152
- const retryAfter = parseRetryAfter(res);
153
- return withCommon('RATE_LIMITED', server.message ?? 'Rate limit exceeded.', {
154
- ...(retryAfter !== undefined ? { retry_after_seconds: retryAfter } : {}),
155
- });
156
- }
157
- default:
158
- if (status >= 500) {
159
- return withCommon('SERVER_ERROR', server.message ?? 'The server encountered an error.');
160
- }
161
- return withCommon(server.code ?? 'ERROR', server.message ?? `Request failed with status ${status}.`);
162
- }
163
- }
164
- export class LabelGridClient {
165
- baseUrl;
166
- token;
167
- fetchFn;
168
- version;
169
- timeoutMs;
170
- rawTimeoutMs;
171
- constructor(opts) {
172
- this.baseUrl = opts.baseUrl.replace(/\/+$/, '');
173
- this.token = opts.token;
174
- this.fetchFn = opts.fetchFn ?? fetch;
175
- this.version = opts.version;
176
- this.timeoutMs = opts.timeoutMs ?? 60_000;
177
- this.rawTimeoutMs = opts.rawTimeoutMs ?? 600_000;
178
- }
179
- authHeaders() {
180
- return {
181
- Authorization: `Bearer ${this.token}`,
182
- Accept: 'application/json',
183
- 'User-Agent': `labelgrid-mcp/${this.version}`,
184
- };
185
- }
186
- async send(method, path, opts = {}) {
187
- const url = `${this.baseUrl}${path}${buildQuery(opts.query)}`;
188
- const headers = { ...this.authHeaders(), ...opts.headers };
189
- if (opts.idempotency) {
190
- // A caller-supplied key is used verbatim (so a caller can dedupe a retry
191
- // across separate tool calls); otherwise a fresh UUID is generated.
192
- headers['Idempotency-Key'] = opts.idempotencyKey ?? randomUUID();
193
- }
194
- const init = { method, headers, signal: AbortSignal.timeout(this.timeoutMs) };
195
- if (opts.rawBody !== undefined) {
196
- init.body = opts.rawBody;
197
- }
198
- else if (opts.body !== undefined) {
199
- headers['Content-Type'] = 'application/json';
200
- init.body = JSON.stringify(opts.body);
201
- }
202
- let res;
203
- try {
204
- res = await this.fetchFn(url, init);
205
- }
206
- catch (err) {
207
- if (err instanceof DOMException &&
208
- (err.name === 'TimeoutError' || err.name === 'AbortError')) {
209
- return {
210
- error: {
211
- code: 'TIMEOUT',
212
- message: `The request timed out after ${Math.round(this.timeoutMs / 1000)} seconds. Try again, or narrow the request.`,
213
- status: 0,
214
- },
215
- };
216
- }
217
- return {
218
- error: {
219
- code: 'NETWORK_ERROR',
220
- message: err instanceof Error ? err.message : 'Network request failed.',
221
- status: 0,
222
- },
223
- };
224
- }
225
- // Cheap pre-check: bound the response before reading when the length is known.
226
- const declaredLength = Number.parseInt(res.headers.get('Content-Length') ?? '', 10);
227
- if (!Number.isNaN(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
228
- return {
229
- error: {
230
- code: 'RESPONSE_TOO_LARGE',
231
- message: `The response is ${declaredLength} bytes, over the ${MAX_RESPONSE_BYTES}-byte limit. Narrow the request with pagination or filters.`,
232
- status: res.status,
233
- },
234
- };
235
- }
236
- const tooLarge = {
237
- error: {
238
- code: 'RESPONSE_TOO_LARGE',
239
- message: `The response body exceeds the ${MAX_RESPONSE_BYTES}-byte limit. Narrow the request with pagination or filters.`,
240
- status: res.status,
241
- },
242
- };
243
- // A chunked/streamed response carries no Content-Length, so bound it AS we
244
- // read: accumulate chunks with a running byte counter and abort the moment
245
- // the counter crosses the ceiling — never buffering the whole oversized body.
246
- // The request timeout keeps running while the body streams, so a read can
247
- // also abort here — map that to the same structured TIMEOUT.
248
- let text;
249
- try {
250
- text = await this.readBody(res, tooLarge);
251
- }
252
- catch (err) {
253
- if (err instanceof DOMException &&
254
- (err.name === 'TimeoutError' || err.name === 'AbortError')) {
255
- return {
256
- error: {
257
- code: 'TIMEOUT',
258
- message: `The request timed out after ${Math.round(this.timeoutMs / 1000)} seconds while reading the response. Try again, or narrow the request.`,
259
- status: 0,
260
- },
261
- };
262
- }
263
- return {
264
- error: {
265
- code: 'NETWORK_ERROR',
266
- message: err instanceof Error ? err.message : 'Reading the response failed.',
267
- status: 0,
268
- },
269
- };
270
- }
271
- if (typeof text !== 'string') {
272
- return text; // the bounded reader returned the too-large error result
273
- }
274
- let body = null;
275
- if (text.length > 0) {
276
- try {
277
- body = JSON.parse(text);
278
- }
279
- catch {
280
- body = text;
281
- }
282
- }
283
- if (res.ok) {
284
- return { data: body };
285
- }
286
- return { error: normalizeError(res, body) };
287
- }
288
- /**
289
- * Reads a response body with the byte ceiling enforced mid-stream. Returns
290
- * the decoded text, or the supplied too-large error result when the ceiling
291
- * is crossed. Abort/timeout rejections propagate to the caller for mapping.
292
- */
293
- async readBody(res, tooLarge) {
294
- if (res.body) {
295
- const reader = res.body.getReader();
296
- const chunks = [];
297
- let total = 0;
298
- for (;;) {
299
- const { done, value } = await reader.read();
300
- if (done)
301
- break;
302
- if (value) {
303
- total += value.byteLength;
304
- if (total > MAX_RESPONSE_BYTES) {
305
- // cancel() can reject (e.g. an already-errored stream); swallow it so
306
- // an oversized response ALWAYS returns RESPONSE_TOO_LARGE.
307
- try {
308
- await reader.cancel();
309
- }
310
- catch {
311
- // best-effort cleanup — the size bound is what matters here.
312
- }
313
- return tooLarge;
314
- }
315
- chunks.push(value);
316
- }
317
- }
318
- const merged = new Uint8Array(total);
319
- let offset = 0;
320
- for (const chunk of chunks) {
321
- merged.set(chunk, offset);
322
- offset += chunk.byteLength;
323
- }
324
- return new TextDecoder('utf-8').decode(merged);
325
- }
326
- // No readable stream (some test stubs) — fall back to text() and measure
327
- // the true byte length as a backstop (multi-byte chars exceed char count).
328
- const text = await res.text();
329
- if (Buffer.byteLength(text, 'utf8') > MAX_RESPONSE_BYTES) {
330
- return tooLarge;
331
- }
332
- return text;
333
- }
334
- get(path, query) {
335
- return this.send('GET', path, { query });
336
- }
337
- post(path, body, opts) {
338
- return this.send('POST', path, {
339
- body,
340
- idempotency: opts?.idempotency,
341
- idempotencyKey: opts?.idempotencyKey,
342
- });
343
- }
344
- patch(path, body) {
345
- return this.send('PATCH', path, { body });
346
- }
347
- put(path, body, opts) {
348
- return this.send('PUT', path, {
349
- body,
350
- idempotency: opts?.idempotency,
351
- idempotencyKey: opts?.idempotencyKey,
352
- });
353
- }
354
- delete(path) {
355
- return this.send('DELETE', path);
356
- }
357
- /**
358
- * Sends a multipart/form-data POST with a single file field plus optional
359
- * extra string fields. A missing/unreadable file yields a FILE_NOT_FOUND
360
- * error result rather than throwing.
361
- */
362
- async postMultipart(path, filePath, fieldName, extra) {
363
- let bytes;
364
- try {
365
- bytes = await readFile(filePath);
366
- }
367
- catch (err) {
368
- return {
369
- error: {
370
- code: 'FILE_NOT_FOUND',
371
- message: `Could not read file at ${filePath}: ${err instanceof Error ? err.message : 'unknown error'}`,
372
- status: 0,
373
- },
374
- };
375
- }
376
- const form = new FormData();
377
- form.append(fieldName, new Blob([new Uint8Array(bytes)], { type: contentType(filePath) }), basename(filePath));
378
- for (const [key, value] of Object.entries(extra ?? {})) {
379
- form.append(key, value);
380
- }
381
- // Let fetch set the multipart Content-Type boundary; do not override it.
382
- return this.send('POST', path, { rawBody: form });
383
- }
384
- /**
385
- * Performs a raw request with NO Authorization header — used for presigned
386
- * upload PUTs, where the signed URL is already the credential and an extra
387
- * Bearer token would break the signature.
388
- */
389
- raw(url, init) {
390
- return this.fetchFn(url, { signal: AbortSignal.timeout(this.rawTimeoutMs), ...init });
391
- }
392
- }
@@ -1,26 +0,0 @@
1
- /**
2
- * Presigned-URL upload helper.
3
- *
4
- * A large binary asset is never streamed through the LabelGrid API. Instead the
5
- * flow is three steps:
6
- * 1. POST the upload-url endpoint (with the filename) to mint a short-lived
7
- * presigned storage URL and its object key.
8
- * 2. PUT the file bytes straight to that presigned URL. This request carries
9
- * NO Authorization header — the signature in the URL is the credential, and
10
- * an extra Bearer token would break it.
11
- * 3. PUT the commit endpoint with the returned object key (with an idempotency
12
- * key) so the API records the finalized file.
13
- *
14
- * A failure at step 2 aborts before the commit, so a half-uploaded object is
15
- * never finalized. Business rules (format checks, transcoding) stay server-side.
16
- */
17
- import type { ApiResult, LabelGridClient } from './http.js';
18
- export type UploadOptions = {
19
- /** The endpoint that mints the presigned URL, e.g. /tracks/42/files/stereo/upload-url. */
20
- uploadUrlPath: string;
21
- /** The endpoint that records the finalized file, e.g. /tracks/42/files/stereo. */
22
- commitPath: string;
23
- /** Absolute or relative local path to the file to upload. */
24
- filePath: string;
25
- };
26
- export declare function uploadViaPresignedUrl(client: LabelGridClient, opts: UploadOptions): Promise<ApiResult<unknown>>;
@@ -1,104 +0,0 @@
1
- /**
2
- * Presigned-URL upload helper.
3
- *
4
- * A large binary asset is never streamed through the LabelGrid API. Instead the
5
- * flow is three steps:
6
- * 1. POST the upload-url endpoint (with the filename) to mint a short-lived
7
- * presigned storage URL and its object key.
8
- * 2. PUT the file bytes straight to that presigned URL. This request carries
9
- * NO Authorization header — the signature in the URL is the credential, and
10
- * an extra Bearer token would break it.
11
- * 3. PUT the commit endpoint with the returned object key (with an idempotency
12
- * key) so the API records the finalized file.
13
- *
14
- * A failure at step 2 aborts before the commit, so a half-uploaded object is
15
- * never finalized. Business rules (format checks, transcoding) stay server-side.
16
- */
17
- import { statSync } from 'node:fs';
18
- import { readFile } from 'node:fs/promises';
19
- import { basename } from 'node:path';
20
- import { log } from '../log.js';
21
- import { contentType } from './content-types.js';
22
- /** True only for an existing regular file. */
23
- function isReadableFile(p) {
24
- try {
25
- return statSync(p).isFile();
26
- }
27
- catch {
28
- return false;
29
- }
30
- }
31
- export async function uploadViaPresignedUrl(client, opts) {
32
- // Fail fast and locally: never touch the network for a file we cannot read.
33
- if (!isReadableFile(opts.filePath)) {
34
- const error = {
35
- code: 'FILE_NOT_FOUND',
36
- message: `No readable file at ${opts.filePath}.`,
37
- status: 0,
38
- };
39
- return { error };
40
- }
41
- // Step 1: mint the presigned URL.
42
- const minted = await client.post(opts.uploadUrlPath, {
43
- filename: basename(opts.filePath),
44
- });
45
- if ('error' in minted)
46
- return minted;
47
- const uploadUrl = minted.data?.upload_url;
48
- const key = minted.data?.key;
49
- if (typeof uploadUrl !== 'string' || typeof key !== 'string') {
50
- const error = {
51
- code: 'UPLOAD_URL_INVALID',
52
- message: 'The upload-url response did not contain a usable upload_url and key.',
53
- status: 0,
54
- };
55
- return { error };
56
- }
57
- // Step 2: PUT the bytes directly to storage — NO auth header (the URL is signed).
58
- // The file passed isReadableFile above, but it can vanish before this read
59
- // (a TOCTOU race); a structured FILE_NOT_FOUND is the contract, not a throw.
60
- let bytes;
61
- try {
62
- bytes = await readFile(opts.filePath);
63
- }
64
- catch {
65
- const error = {
66
- code: 'FILE_NOT_FOUND',
67
- message: `The file at ${opts.filePath} could not be read.`,
68
- status: 0,
69
- };
70
- return { error };
71
- }
72
- let putRes;
73
- try {
74
- putRes = await client.raw(uploadUrl, {
75
- method: 'PUT',
76
- headers: { 'Content-Type': contentType(opts.filePath) },
77
- body: new Uint8Array(bytes),
78
- });
79
- }
80
- catch (err) {
81
- // Never surface err.message raw to the log — it can embed the signed URL,
82
- // and `reason` is not a redacted key. Strip any URL before logging.
83
- log('error', 'presigned upload PUT failed', {
84
- reason: err instanceof Error ? err.message.replace(/https?:\/\/\S+/gi, '[url]') : 'network error',
85
- });
86
- const error = {
87
- code: 'UPLOAD_FAILED',
88
- message: 'Uploading the file to storage failed.',
89
- status: 0,
90
- };
91
- return { error };
92
- }
93
- if (!putRes.ok) {
94
- // Abort BEFORE the commit — a half-uploaded object is never finalized.
95
- const error = {
96
- code: 'UPLOAD_FAILED',
97
- message: `Uploading the file to storage failed with status ${putRes.status}.`,
98
- status: putRes.status,
99
- };
100
- return { error };
101
- }
102
- // Step 3: commit the object key (idempotent — a retried commit will not duplicate).
103
- return client.put(opts.commitPath, { s3_key: key }, { idempotency: true });
104
- }
package/dist/log.d.ts DELETED
@@ -1,16 +0,0 @@
1
- /**
2
- * stderr-only structured logging with secret redaction.
3
- *
4
- * stdout is reserved for the MCP protocol stream, so every log line goes to
5
- * stderr. Any structured metadata is passed through {@link redactSecrets}
6
- * first so tokens, passwords and signed URLs never reach the log.
7
- */
8
- /**
9
- * Deep-clones a value, replacing the value of any object key whose name looks
10
- * like a secret with a fixed mask. Non-secret values, arrays and primitives are
11
- * preserved (arrays and nested objects are walked recursively).
12
- */
13
- export declare function redactSecrets(v: unknown): unknown;
14
- export type LogLevel = 'info' | 'warn' | 'error';
15
- /** Writes a single redacted log line to stderr (never stdout). */
16
- export declare function log(level: LogLevel, msg: string, meta?: unknown): void;
package/dist/log.js DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * stderr-only structured logging with secret redaction.
3
- *
4
- * stdout is reserved for the MCP protocol stream, so every log line goes to
5
- * stderr. Any structured metadata is passed through {@link redactSecrets}
6
- * first so tokens, passwords and signed URLs never reach the log.
7
- */
8
- const SECRET_KEY = /token|password|secret|nonce|authorization|key/i;
9
- const MASK = '***REDACTED***';
10
- /**
11
- * Deep-clones a value, replacing the value of any object key whose name looks
12
- * like a secret with a fixed mask. Non-secret values, arrays and primitives are
13
- * preserved (arrays and nested objects are walked recursively).
14
- */
15
- export function redactSecrets(v) {
16
- if (Array.isArray(v)) {
17
- return v.map((item) => redactSecrets(item));
18
- }
19
- if (v !== null && typeof v === 'object') {
20
- const out = {};
21
- for (const [key, value] of Object.entries(v)) {
22
- out[key] = SECRET_KEY.test(key) ? MASK : redactSecrets(value);
23
- }
24
- return out;
25
- }
26
- return v;
27
- }
28
- /** Writes a single redacted log line to stderr (never stdout). */
29
- export function log(level, msg, meta) {
30
- let line = `[${level}] ${msg}`;
31
- if (meta !== undefined) {
32
- line += ` ${JSON.stringify(redactSecrets(meta))}`;
33
- }
34
- process.stderr.write(`${line}\n`);
35
- }
@@ -1,12 +0,0 @@
1
- /**
2
- * Accounting toolset: statements, transactions, royalty breakdowns,
3
- * artificial-streaming records, and the account summary. All read-only.
4
- *
5
- * Two tools (`download_statement_csv`, `download_statement_invoice`) fetch a
6
- * file body. They validate the caller-supplied `save_to_path` and write ONLY
7
- * there; a CSV without a save path is returned inline, truncated at 100KB.
8
- * These downloads use an authenticated raw GET (the shared client's JSON path
9
- * would corrupt binary PDFs), with the same auth headers the client sends.
10
- */
11
- import type { ToolDef } from './types.js';
12
- export declare const accountingTools: ToolDef[];