@labelgrid/mcp 0.3.0 → 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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,17 @@ All notable changes to `@labelgrid/mcp` are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.3.1] - 2026-07-20
9
+
10
+ ### Changed
11
+
12
+ - Internal restructure: the repository is now an npm workspace and the shared
13
+ LabelGrid API client (HTTP transport, uploads, content types, the
14
+ catalog-entity registry, and redacting logging) moved into the
15
+ `@labelgrid/core` package, which this server now depends on. No behavior
16
+ change — the tool catalog, gating, toolsets, resources and responses are
17
+ identical to 0.3.0.
18
+
8
19
  ## [0.3.0] - 2026-07-16
9
20
 
10
21
  ### Changed
package/dist/config.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * full-write access is doubly opt-in (flag + an exact acknowledgment sentence).
8
8
  * A read-only override wins over everything.
9
9
  */
10
- import { log } from './log.js';
10
+ import { log } from '@labelgrid/core';
11
11
  export const DEFAULT_BASE_URL = 'https://api.labelgrid.com/api/public';
12
12
  /** The exact sentence a user must set in LABELGRID_FULL_WRITES_ACK to arm full writes. */
13
13
  export const FULL_WRITES_ACK = 'I accept responsibility for AI-driven distribution actions';
package/dist/index.js CHANGED
@@ -6,12 +6,11 @@
6
6
  * to stderr and exits 1. Otherwise the server connects over the stdio
7
7
  * transport; stdout carries the MCP protocol only, all logging goes to stderr.
8
8
  */
9
+ import { LabelGridClient, log } from '@labelgrid/core';
9
10
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
- import { LabelGridClient } from './api/http.js';
11
11
  import { ConfigError, loadConfig } from './config.js';
12
12
  import { isToolEnabled } from './gating.js';
13
13
  import { FULL_WRITES_NOTICE, LEGAL_SUMMARY } from './legal.js';
14
- import { log } from './log.js';
15
14
  import { buildServer } from './server.js';
16
15
  import { allTools } from './tools/all.js';
17
16
  import { VERSION } from './version.js';
@@ -23,7 +23,7 @@
23
23
  * Projection is presentation-only — it never transforms values. The 400K
24
24
  * toToolResult cap stays as the backstop for anything projection cannot tame.
25
25
  */
26
- import type { ApiResult } from './api/http.js';
26
+ import type { ApiResult } from '@labelgrid/core';
27
27
  /** Per-tool concise-mode field allowlists, keyed by tool name. */
28
28
  export declare const CONCISE_ALLOWLISTS: Record<string, readonly string[]>;
29
29
  /**
@@ -9,8 +9,8 @@
9
9
  * resources are still registered (so introspection shows what the server
10
10
  * offers) but reads return the NOT_CONNECTED guidance JSON instead of data.
11
11
  */
12
+ import type { LabelGridClient } from '@labelgrid/core';
12
13
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
- import type { LabelGridClient } from './api/http.js';
14
14
  import type { Config } from './config.js';
15
15
  /** The reference dataset types as a tuple, for the tool's zod enum. */
16
16
  export declare const REFERENCE_TYPES: readonly ["genres", "genre_categories", "languages", "contributor_roles", "instruments", "distro_outlets", "territories", "issue_definitions", "webhook_event_types"];
package/dist/server.d.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  * result via {@link toToolResult} (API errors become isError results, never
9
9
  * protocol errors).
10
10
  */
11
+ import { type LabelGridClient } from '@labelgrid/core';
11
12
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
12
- import type { LabelGridClient } from './api/http.js';
13
13
  import { type Config } from './config.js';
14
14
  import { type ToolDef } from './tools/types.js';
15
15
  export declare function buildServer(config: Config, client: LabelGridClient, tools: ToolDef[]): McpServer;
package/dist/server.js CHANGED
@@ -8,11 +8,11 @@
8
8
  * result via {@link toToolResult} (API errors become isError results, never
9
9
  * protocol errors).
10
10
  */
11
+ import { log } from '@labelgrid/core';
11
12
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
12
13
  import { defaultExcludedToolsets } from './config.js';
13
14
  import { isToolEnabled } from './gating.js';
14
15
  import { DATA_HANDLING_NOTE, FULL_WRITES_NOTICE, LEGAL_SUMMARY } from './legal.js';
15
- import { log } from './log.js';
16
16
  import { registerReferenceResources } from './resources.js';
17
17
  import { setupTools } from './tools/setup.js';
18
18
  import { toToolResult } from './tools/types.js';
@@ -3,7 +3,7 @@
3
3
  * delete across labels, artists, writers, publishers, releases and tracks),
4
4
  * image uploads, and the asset read (`get_asset`).
5
5
  *
6
- * Every tool selects its entity via the registry in `src/entities.ts`.
6
+ * Every tool selects its entity via the entity registry in `@labelgrid/core`.
7
7
  * Create/update forward a permissive `fields` object straight to the API,
8
8
  * which owns all validation — this keeps each tool a thin wrapper and lets the
9
9
  * full documented field set through without re-declaring it here. The two
@@ -3,7 +3,7 @@
3
3
  * delete across labels, artists, writers, publishers, releases and tracks),
4
4
  * image uploads, and the asset read (`get_asset`).
5
5
  *
6
- * Every tool selects its entity via the registry in `src/entities.ts`.
6
+ * Every tool selects its entity via the entity registry in `@labelgrid/core`.
7
7
  * Create/update forward a permissive `fields` object straight to the API,
8
8
  * which owns all validation — this keeps each tool a thin wrapper and lets the
9
9
  * full documented field set through without re-declaring it here. The two
@@ -11,9 +11,8 @@
11
11
  * `response_format: 'detailed'` returning the verbatim API response.
12
12
  */
13
13
  import { statSync } from 'node:fs';
14
+ import { ENTITIES, ENTITY_NAMES, assertAllowedExtension, } from '@labelgrid/core';
14
15
  import { z } from 'zod';
15
- import { assertAllowedExtension } from '../api/content-types.js';
16
- import { ENTITIES, ENTITY_NAMES } from '../entities.js';
17
16
  import { applyProjection } from '../projection.js';
18
17
  /** Accepted image extensions for the catalog image uploads. */
19
18
  const IMAGE_EXTS = ['.jpg', '.jpeg', '.png', '.webp', '.tif', '.tiff'];
@@ -9,9 +9,8 @@
9
9
  * distribute/takedown actions, the Preflight-QC confirm-review step, and
10
10
  * one-time Beatport onboarding.
11
11
  */
12
+ import { assertAllowedExtension, uploadViaPresignedUrl } from '@labelgrid/core';
12
13
  import { z } from 'zod';
13
- import { assertAllowedExtension } from '../api/content-types.js';
14
- import { uploadViaPresignedUrl } from '../api/upload.js';
15
14
  /** Per-target upload extension allow-lists: an upload tool never reads an arbitrary file. */
16
15
  const TRACK_UPLOAD_EXTS = {
17
16
  track_stereo: ['.wav', '.flac', '.aif', '.aiff'],
@@ -7,8 +7,8 @@
7
7
  * into a registered MCP tool. This keeps every tool a thin wrapper: one HTTP
8
8
  * call, no client-side business logic.
9
9
  */
10
+ import type { ApiResult, LabelGridClient } from '@labelgrid/core';
10
11
  import type { z } from 'zod';
11
- import type { ApiResult, LabelGridClient } from '../api/http.js';
12
12
  import type { Config } from '../config.js';
13
13
  import type { Gate } from '../gating.js';
14
14
  export type ToolAnnotations = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@labelgrid/mcp",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "mcpName": "io.github.labelgrid/labelgrid-mcp",
5
5
  "description": "Official LabelGrid MCP server — connect your AI client to your LabelGrid account",
6
6
  "type": "module",
@@ -12,33 +12,23 @@
12
12
  "files": ["dist", "README.md", "CHANGELOG.md", "LICENSE", "server.json"],
13
13
  "scripts": {
14
14
  "build": "tsc",
15
- "build:mcpb": "npm run build && node scripts/build-mcpb.mjs",
16
15
  "start": "node dist/index.js",
17
16
  "dev": "tsc --watch",
18
17
  "test": "vitest run --exclude 'test/contract/**'",
19
- "test:contract": "vitest run test/contract",
20
- "lint": "biome check .",
21
- "leak-guard": "node scripts/leak-guard.mjs",
22
- "check-coverage": "node scripts/check-api-coverage.mjs",
23
- "gen-docs": "node scripts/gen-tool-docs.mjs",
24
- "measure-tokens": "node scripts/measure-tool-tokens.mjs"
18
+ "test:contract": "vitest run test/contract"
25
19
  },
26
20
  "repository": {
27
21
  "type": "git",
28
- "url": "git+https://github.com/labelgrid/labelgrid-mcp.git"
22
+ "url": "git+https://github.com/labelgrid/labelgrid-mcp.git",
23
+ "directory": "packages/mcp"
29
24
  },
30
25
  "license": "MIT",
31
26
  "engines": {
32
27
  "node": ">=20"
33
28
  },
34
29
  "dependencies": {
30
+ "@labelgrid/core": "0.1.0",
35
31
  "@modelcontextprotocol/sdk": "^1.12.0",
36
32
  "zod": "^3.24.0"
37
- },
38
- "devDependencies": {
39
- "@biomejs/biome": "^1.9.0",
40
- "@types/node": "^22.0.0",
41
- "typescript": "^5.7.0",
42
- "vitest": "^3.0.0"
43
33
  }
44
34
  }
package/server.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.labelgrid/labelgrid-mcp",
4
4
  "description": "Official LabelGrid MCP server — manage your music catalog, releases, analytics and distribution.",
5
- "version": "0.3.0",
5
+ "version": "0.3.1",
6
6
  "websiteUrl": "https://labelgrid.com",
7
7
  "repository": {
8
8
  "url": "https://github.com/labelgrid/labelgrid-mcp",
@@ -12,7 +12,7 @@
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "@labelgrid/mcp",
15
- "version": "0.3.0",
15
+ "version": "0.3.1",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  },
@@ -1,33 +0,0 @@
1
- /**
2
- * Shared file content-type inference and the upload extension allow-list guard.
3
- *
4
- * CONTENT_TYPES (moved here from upload.ts) infers a best-effort MIME type from
5
- * a file extension — used for the presigned PUT and the multipart Blob.
6
- * assertAllowedExtension is the per-tool guard: each file-accepting tool
7
- * declares exactly which extensions it accepts, and the guard rejects anything
8
- * else BEFORE the file is read or any HTTP call is made, so an upload tool can
9
- * never be pointed at an arbitrary local file.
10
- */
11
- import type { ApiError } from './http.js';
12
- /** Best-effort Content-Type inferred from a file extension. */
13
- export declare const CONTENT_TYPES: Record<string, string>;
14
- /** Best-effort Content-Type for a file path (default application/octet-stream). */
15
- export declare function contentType(filePath: string): string;
16
- /**
17
- * Rejects a file whose extension is not in `allowed` (case-insensitive), before
18
- * any read or HTTP call, and resolves the path to its real target. The supplied
19
- * path's extension is checked first (the fast path); then the path is resolved
20
- * with realpathSync and the REAL target's extension is checked too, so a symlink
21
- * named `cover.jpg` that points at an arbitrary local file cannot slip past the
22
- * guard. On success it returns `{ realPath }` — the resolved canonical path,
23
- * which the caller MUST use as the path it reads/uploads (never the original
24
- * argument), so a symlink retargeted after validation cannot redirect the read
25
- * (the resolved target is what gets uploaded). On failure it returns `{ error }`
26
- * — a structured FILE_TYPE_NOT_ALLOWED, or FILE_NOT_FOUND if the path does not
27
- * resolve.
28
- */
29
- export declare function assertAllowedExtension(filePath: string, allowed: string[]): {
30
- error: ApiError;
31
- } | {
32
- realPath: string;
33
- };
@@ -1,87 +0,0 @@
1
- /**
2
- * Shared file content-type inference and the upload extension allow-list guard.
3
- *
4
- * CONTENT_TYPES (moved here from upload.ts) infers a best-effort MIME type from
5
- * a file extension — used for the presigned PUT and the multipart Blob.
6
- * assertAllowedExtension is the per-tool guard: each file-accepting tool
7
- * declares exactly which extensions it accepts, and the guard rejects anything
8
- * else BEFORE the file is read or any HTTP call is made, so an upload tool can
9
- * never be pointed at an arbitrary local file.
10
- */
11
- import { realpathSync } from 'node:fs';
12
- import { extname } from 'node:path';
13
- /** Best-effort Content-Type inferred from a file extension. */
14
- export const CONTENT_TYPES = {
15
- '.wav': 'audio/wav',
16
- '.flac': 'audio/flac',
17
- '.aif': 'audio/aiff',
18
- '.aiff': 'audio/aiff',
19
- '.mp3': 'audio/mpeg',
20
- '.lrc': 'text/plain',
21
- '.txt': 'text/plain',
22
- '.jpg': 'image/jpeg',
23
- '.jpeg': 'image/jpeg',
24
- '.png': 'image/png',
25
- '.webp': 'image/webp',
26
- '.tif': 'image/tiff',
27
- '.tiff': 'image/tiff',
28
- '.pdf': 'application/pdf',
29
- '.mp4': 'video/mp4',
30
- '.mov': 'video/quicktime',
31
- };
32
- /** Best-effort Content-Type for a file path (default application/octet-stream). */
33
- export function contentType(filePath) {
34
- return CONTENT_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream';
35
- }
36
- /**
37
- * Rejects a file whose extension is not in `allowed` (case-insensitive), before
38
- * any read or HTTP call, and resolves the path to its real target. The supplied
39
- * path's extension is checked first (the fast path); then the path is resolved
40
- * with realpathSync and the REAL target's extension is checked too, so a symlink
41
- * named `cover.jpg` that points at an arbitrary local file cannot slip past the
42
- * guard. On success it returns `{ realPath }` — the resolved canonical path,
43
- * which the caller MUST use as the path it reads/uploads (never the original
44
- * argument), so a symlink retargeted after validation cannot redirect the read
45
- * (the resolved target is what gets uploaded). On failure it returns `{ error }`
46
- * — a structured FILE_TYPE_NOT_ALLOWED, or FILE_NOT_FOUND if the path does not
47
- * resolve.
48
- */
49
- export function assertAllowedExtension(filePath, allowed) {
50
- const isAllowed = (candidate) => allowed.some((a) => a.toLowerCase() === candidate);
51
- const ext = extname(filePath).toLowerCase();
52
- // Fast path: reject a plainly-disallowed extension before touching the disk.
53
- if (!isAllowed(ext)) {
54
- return {
55
- error: {
56
- code: 'FILE_TYPE_NOT_ALLOWED',
57
- message: `This tool only accepts ${allowed.join(', ')} files (got "${ext || 'no extension'}").`,
58
- status: 0,
59
- },
60
- };
61
- }
62
- // The supplied name is allowed; resolve symlinks and re-check the real target.
63
- let realPath;
64
- try {
65
- realPath = realpathSync(filePath);
66
- }
67
- catch {
68
- return {
69
- error: {
70
- code: 'FILE_NOT_FOUND',
71
- message: `No readable file at ${filePath}.`,
72
- status: 0,
73
- },
74
- };
75
- }
76
- const realExt = extname(realPath).toLowerCase();
77
- if (!isAllowed(realExt)) {
78
- return {
79
- error: {
80
- code: 'FILE_TYPE_NOT_ALLOWED',
81
- message: `The file resolves to a "${realExt || 'no extension'}" file; this tool only accepts ${allowed.join(', ')}.`,
82
- status: 0,
83
- },
84
- };
85
- }
86
- return { realPath };
87
- }
@@ -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
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * The catalog-entity registry: the six entity kinds the consolidated catalog
3
- * tools operate on, each with its endpoint path and the reviewed documentation
4
- * fragments (list filters, create/update fields, delete refusals) the tool
5
- * descriptions are assembled from.
6
- *
7
- * This is data, not behavior — the catalog tools stay thin wrappers and the
8
- * API owns all validation. The wording here carries the caveats from the
9
- * per-entity tool descriptions it replaces (recording_country on track create,
10
- * RELEASE_LOCKED_FIELDS on release update, the delete refusals).
11
- */
12
- export type EntityName = 'label' | 'artist' | 'writer' | 'publisher' | 'release' | 'track';
13
- /** The entity names as a tuple, for zod enum inputs. */
14
- export declare const ENTITY_NAMES: readonly ["label", "artist", "writer", "publisher", "release", "track"];
15
- export type EntitySpec = {
16
- /** The collection endpoint path, e.g. '/labels'. */
17
- path: string;
18
- /** One-line doc of the useful list filters for search_catalog. */
19
- filtersDoc: string;
20
- /** One-line doc of required + common create/update fields. */
21
- fieldsDoc: string;
22
- /** One-line doc of the server-side delete refusals. */
23
- deleteNote: string;
24
- };
25
- export declare const ENTITIES: Record<EntityName, EntitySpec>;
package/dist/entities.js DELETED
@@ -1,51 +0,0 @@
1
- /**
2
- * The catalog-entity registry: the six entity kinds the consolidated catalog
3
- * tools operate on, each with its endpoint path and the reviewed documentation
4
- * fragments (list filters, create/update fields, delete refusals) the tool
5
- * descriptions are assembled from.
6
- *
7
- * This is data, not behavior — the catalog tools stay thin wrappers and the
8
- * API owns all validation. The wording here carries the caveats from the
9
- * per-entity tool descriptions it replaces (recording_country on track create,
10
- * RELEASE_LOCKED_FIELDS on release update, the delete refusals).
11
- */
12
- /** The entity names as a tuple, for zod enum inputs. */
13
- export const ENTITY_NAMES = ['label', 'artist', 'writer', 'publisher', 'release', 'track'];
14
- export const ENTITIES = {
15
- label: {
16
- path: '/labels',
17
- filtersDoc: 'label: no documented filters — paginate with page/per_page.',
18
- fieldsDoc: 'label — required: name, default_email; optional: support email, website/platform URLs, default copyright lines, isrc_base.',
19
- deleteNote: 'label: refused while the label still has releases — remove or reassign its releases first.',
20
- },
21
- artist: {
22
- path: '/artists',
23
- filtersDoc: 'artist: artist_name (filter by artist name).',
24
- fieldsDoc: 'artist — required: artist_name; optional: full_name, email, location, bios, isni, default_language, platform profile URLs.',
25
- deleteNote: 'artist: refused while still referenced by releases or tracks.',
26
- },
27
- writer: {
28
- path: '/writers',
29
- filtersDoc: 'writer: name (writer name), ipi (IPI number).',
30
- fieldsDoc: 'writer — required: first_name, last_name; optional: middle_name, display_credits, email, country, pro, ipi, isni, publisher_id (or publisher_name/publisher_pro/publisher_ipi).',
31
- deleteNote: 'writer: refused while still referenced by tracks.',
32
- },
33
- publisher: {
34
- path: '/publishers',
35
- filtersDoc: 'publisher: name (publisher name), ipi (IPI number).',
36
- fieldsDoc: 'publisher — required: name; optional: ipi, pro, isni, controlled_publisher.',
37
- deleteNote: 'publisher: refused while still referenced by writers.',
38
- },
39
- release: {
40
- path: '/releases',
41
- filtersDoc: 'release: label_id (owning label id), is_live (1 = live/distributed only), barcode_number (UPC/EAN), cat (catalog number).',
42
- fieldsDoc: 'release — required on create: content_type, label_id, artists, titles, cat (catalog number), artwork_ai_usage, primary_genre_id; many optional fields (dates, copyright lines, genres, per-outlet URLs). Once submitted or distributed some fields are locked — changing one returns a 403 with code RELEASE_LOCKED_FIELDS naming exactly which fields cannot change.',
43
- deleteNote: 'release: only a never-submitted draft can be deleted.',
44
- },
45
- track: {
46
- path: '/tracks',
47
- filtersDoc: 'track: release_id (one release’s tracks), isrc (filter by ISRC).',
48
- fieldsDoc: 'track — required on create: release_id, disc, track_num, composition_type, artists, audio_ai_usage, composition_ai_usage, commercial_samples, audio_language, contributors, and recording_country (ISO 3166-1 alpha-2, e.g. "US"); optional: titles, isrc, iswc, writers, publishers, splits, and more.',
49
- deleteNote: 'track: allowed while the parent release is an editable draft; refused once submitted or distributed.',
50
- },
51
- };
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
- }