UNPKG

@withpica/mcp-server

Version:

MCP Server for withPICA — enables AI assistants to interact with your withPICA music catalog

474 lines • 21 kB
// Copyright (c) 2025-2026 Withpica Ltd. All rights reserved. /** * Write tools that need the two-step confirmation token only for SOME calls. * * A destructive tool, or one with previewMode "two_step_token", is always * gated in ToolRegistry.execute. A tool listed here is gated only when its * check returns a preview; a null preview runs the call with no extra step. * The token is the same one (generateConfirmationToken / * validateAndConsumeToken), bound to the call's arguments AND to `bind`, so * if what the call would do changes between the two calls, the token stops * matching and the caller is asked again. * * pica_credits_update (founder rulings 2026-11-20): it replaces every * composition credit on a work, so a list that leaves a writer out removes * them. Confirm only when the list removes a writer or cuts someone's share * to 0% or unknown. * * pica_catalog_health_fix (H8, 8b's MCP safety tally 2026-11-20): confirm * when the call accepts a merge or delete (a destructive plan action). A * delegated agent is also held for the owner's approval by the REST route; * this token is the step for the organisation's own key. * * pica_works_bulk_copy_credits in `replace` mode (H5, 2026-11-20): each * target's writers become exactly the source's, so a target loses whoever * the source lacks. Confirm when any target would lose a writer, or a kept * writer's role or share would change. `skip` only fills songs with no * writers, and a target with no writers loses nothing, so neither asks. * * pica_works_update, pica_people_update, pica_agreements_update (8b's review, * "saving a list replaces it whole"): confirm when the call would drop a * stored mood tag, metadata key, contact detail, tag or agreed term. * pica_recordings_bulk_reassign_artist, pica_works_bulk_link_artist: confirm * when a record would lose the artist it has now, naming each. The checks * and why each field is in or out: list-replace-confirms.ts. */ import { ApiError } from "@withpica/mcp-sdk"; import { typedError } from "./error-envelope.js"; import { agreementsUpdateCheck, linkArtistCheck, peopleUpdateCheck, reassignArtistCheck, worksUpdateCheck, } from "./list-replace-confirms.js"; /** * Mirrors PUBLISHING_ROLES in CreditsTools.updateCredits: the roles that go * to /collaborators, the set that call replaces. Same first-role reading * ("writer, composer" → "writer"), so this check and the save agree on * whether the call touches the composition set at all. */ const COMPOSITION_ROLES = new Set([ "writer", "composer", "lyricist", "arranger", "publisher", "sub-publisher", ]); const firstRole = (role) => String(role || "writer") .split(", ")[0] .trim(); const shareOf = (v) => typeof v === "number" && Number.isFinite(v) ? v : null; /** * What the call would do that needs the user's yes (founder rulings * 2026-11-20), judged per person across their composition entries: * - a REMOVAL: a person with a composition credit now and no composition * entry in the new list. A role change keeps them on the song, so it is * not a removal. * - a SHARE CUT to 0% or unknown: a person whose composition shares now * total more than 0, and whose new entries carry no share above 0. Other * share changes don't ask; the song's history can undo them. * A call with no composition entries leaves the set alone (updateCredits * only calls /collaborators when there are some), so it is not checked. */ export const creditsUpdateCheck = async (pica, args) => { const workId = typeof args.work_id === "string" ? args.work_id : ""; const entries = Array.isArray(args.credits) ? args.credits : []; // person → their new shares on composition entries (null = unknown) const next = new Map(); for (const e of entries) { if (!e || typeof e !== "object") continue; const entry = e; if (COMPOSITION_ROLES.has(firstRole(entry.role)) && typeof entry.person_id === "string") { const shares = next.get(entry.person_id) ?? []; shares.push(shareOf(entry.splits ?? entry.split_percentage)); next.set(entry.person_id, shares); } } if (!workId || next.size === 0) return { kind: "ok", confirm: null }; let rows; try { rows = await pica.credits.listRowsForWork(workId); } catch { // Fail closed: without the current writers we cannot say who would go. return { kind: "refuse", result: typedError("CREDITS_REMOVAL_CHECK_FAILED", "Nothing was saved: PICA couldn't read this work's current writers to check whether this list removes anyone or cuts a share. Try again in a minute. To change one credit, use pica_credit_update, pica_credit_add or pica_credit_remove where you have them; they need no check."), }; } const current = Array.isArray(rows?.credits) ? rows.credits : []; const people = new Map(); for (const row of current) { if (row.grain !== "composition") continue; const p = people.get(row.person_id) ?? { person_id: row.person_id, name: row.person_name || row.person_id, roles: [], share: 0, }; if (!p.roles.includes(row.role)) p.roles.push(row.role); p.share += shareOf(row.split_percentage) ?? 0; people.set(row.person_id, p); } const byId = (a, b) => a.person_id.localeCompare(b.person_id); const removes = []; const share_cuts = []; for (const p of people.values()) { const shares = next.get(p.person_id); if (!shares) { removes.push({ person_id: p.person_id, name: p.name, roles: p.roles }); continue; } if (p.share > 0 && !shares.some((v) => v !== null && v > 0)) { share_cuts.push({ person_id: p.person_id, name: p.name, from: p.share, to: shares.every((v) => v === null) ? "unknown" : "0%", }); } } if (removes.length === 0 && share_cuts.length === 0) { return { kind: "ok", confirm: null }; } removes.sort(byId); share_cuts.sort(byId); const lines = []; if (removes.length > 0) { lines.push(`this removes ${removes.map((r) => r.name).join(", ")} from the song's writers, because the list leaves ${removes.length === 1 ? "them" : "them all"} out.`); } for (const c of share_cuts) { lines.push(c.to === "unknown" ? `this leaves ${c.name}'s share unknown (it was ${c.from}%).` : `this cuts ${c.name}'s share from ${c.from}% to 0%.`); } lines.push("check with the user that this is what they mean. the song's history keeps the change and can undo it."); return { kind: "ok", confirm: { preview: { action: "replace the writers on this work", target: workId, warning: lines.join(" "), display_name: "set credits", removes, share_cuts, }, bind: [ ...removes.map((r) => `remove:${r.person_id}`), ...share_cuts.map((c) => `cut:${c.person_id}:${c.to}`), ], }, }; }; /** JSON with object keys sorted, so the same action binds the same way. */ function canonical(value) { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (value && typeof value === "object") { const entries = Object.entries(value) .filter(([, v]) => v !== undefined) .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`; } return JSON.stringify(value ?? null); } const ALL_SAFE_AUTO = "all_safe_auto"; const MERGE_OR_DELETE = { merge_pair: "merge duplicates (keeps one record, deletes the others)", delete_empty_release: "delete an empty release", fold_version_work: "fold a version into its original song (deletes the version's work)", }; /** * The accepted ids, as the fix route expands them (destructive.ts * expandAccepted): named ids, every selection's id, and for the shorthand * every auto action that is not destructive. */ function acceptedIds(actions, args) { const accept = Array.isArray(args.accept) ? args.accept.filter((x) => typeof x === "string") : []; const ids = new Set(accept.filter((id) => id !== ALL_SAFE_AUTO)); if (accept.includes(ALL_SAFE_AUTO)) { for (const a of actions) { if (a.disposition === "auto" && a.destructive !== true && typeof a.actionId === "string") ids.add(a.actionId); } } if (Array.isArray(args.selections)) { for (const s of args.selections) { const id = s?.actionId; if (typeof id === "string") ids.add(id); } } return ids; } /** * Ask before a fix call merges or deletes. The token is bound to the call's * arguments (planToken, accept, selections) and to what each accepted * destructive action does, so a token for {A} cannot apply {A, B}, dropping * B asks again, and a merge that changed between the two calls asks again. * Fails closed: a plan that cannot be read, or one whose builders failed * while the call names ids the plan does not hold, is refused. */ export const catalogHealthFixCheck = async (pica, args) => { const refuse = (detail) => ({ kind: "refuse", result: typedError("CATALOG_FIX_DESTRUCTIVE_CHECK_FAILED", `Nothing was applied: PICA couldn't check whether these fixes merge or delete records (${detail}). Try again in a minute, or call pica_catalog_health_plan again and pass the new planToken.`), }); // No named id and no selection: only the all_safe_auto shorthand (or // nothing), which never takes a destructive action, so there is nothing // to ask about and no plan to read. The call goes on to the route, which // answers for itself (a client-catalogue refusal keeps its own words). const named = (Array.isArray(args.accept) && args.accept.some((id) => typeof id === "string" && id !== ALL_SAFE_AUTO)) || (Array.isArray(args.selections) && args.selections.length > 0); if (!named) return { kind: "ok", confirm: null }; let plan; try { plan = (await pica.health.catalogHealthPlan({})); } catch (err) { // Keep the plan route's own reason (a refused catalogue says so). const why = err instanceof Error && err.message ? `: ${err.message}` : ""; return refuse(`the plan could not be read${why}`.slice(0, 400)); } const actions = Array.isArray(plan?.actions) ? plan.actions : null; if (!actions) return refuse("the plan came back empty"); const ids = acceptedIds(actions, args); const known = new Set(actions.map((a) => a.actionId)); const builderFailed = Array.isArray(plan.residual) && plan.residual.some((r) => r?.reason === "builder_failed"); if (builderFailed && [...ids].some((id) => !known.has(id))) { return refuse("part of the plan could not be built"); } const destructive = actions .filter((a) => a.destructive === true && typeof a.actionId === "string" && ids.has(a.actionId)) .sort((a, b) => String(a.actionId).localeCompare(String(b.actionId))); if (destructive.length === 0) return { kind: "ok", confirm: null }; const kinds = destructive.map((a) => MERGE_OR_DELETE[String(a.actionKind)] ?? String(a.actionKind)); const counts = new Map(); for (const k of kinds) counts.set(k, (counts.get(k) ?? 0) + 1); const lines = [...counts].map(([k, n]) => (n === 1 ? k : `${n}× ${k}`)); return { kind: "ok", confirm: { preview: { action: "merge or delete records to fix the catalogue", target: `${destructive.length} action${destructive.length === 1 ? "" : "s"}: ${lines.join("; ")}`, warning: "check with the user that they want these merges or deletes. a merge keeps one record and deletes the others.", display_name: "apply catalog health fix actions", destructive_actions: destructive.map((a) => ({ actionId: a.actionId, actionKind: a.actionKind, entityRefs: a.entityRefs, })), }, bind: destructive.map((a) => `destructive:${String(a.actionId)}:${canonical({ actionKind: a.actionKind, entityRefs: a.entityRefs, preview: a.preview, })}`), }, }; }; /** Songs named in a bulk preview's text; the rest are counted. */ const SONGS_SHOWN = 20; const rowKey = (r) => `${r.person_id}\u0000${r.role}`; const pct = (v) => (v === null ? "unknown" : `${v}%`); /** * What a `replace` copy would take from each target, judged per row keyed on * (person, role) — the key replace_work_collaborators diffs on: * - a REMOVAL: a person with writer rows on the target and none in the * source; * - a CHANGE: a kept person whose role or share differs. A role change is * a removal of the old (person, role) row plus an insert, so it counts. * Reads fail closed: without the rows we cannot say what would go. * A song with a locked split is skipped by the route, unchanged; PICA * can't see locks from here, so the preview says so instead of naming them. */ export const bulkCopyCreditsCheck = async (pica, args) => { if (args.conflict_mode !== "replace" || args.dry_run === true) { return { kind: "ok", confirm: null }; } const sourceId = typeof args.source_work_id === "string" ? args.source_work_id : ""; const targets = [ ...new Set((Array.isArray(args.target_work_ids) ? args.target_work_ids : []).filter((t) => typeof t === "string" && t !== sourceId)), ].sort(); if (!sourceId || targets.length === 0) return { kind: "ok", confirm: null }; const refuse = () => ({ kind: "refuse", result: typedError("BULK_COPY_CHECK_FAILED", 'Nothing was copied: PICA couldn\'t read the writers on these songs to check what replace would remove or change. Try again in a minute, or use conflict_mode "skip", which only fills songs with no writers.'), }); // null: no such work in this organisation (404). The route drops such a // target and copies the rest, so it is left unchecked rather than // refusing the whole call; any other read error fails closed. const writersOf = async (workId) => { try { const rows = await pica.credits.listRowsForWork(workId); return (Array.isArray(rows?.credits) ? rows.credits : []).filter((r) => r.grain === "composition"); } catch (err) { if (err instanceof ApiError && err.status === 404) return null; throw err; } }; let found; const current = new Map(); try { found = await writersOf(sourceId); for (let i = 0; i < targets.length; i += 10) { const batch = targets.slice(i, i + 10); const read = await Promise.all(batch.map(writersOf)); batch.forEach((t, j) => { const rows = read[j]; if (rows) current.set(t, rows); }); } } catch { return refuse(); } if (!found) { return { kind: "refuse", result: typedError("SOURCE_WORK_NOT_FOUND", "Nothing was copied: the source work isn't in this catalogue. Check source_work_id with pica_works_query."), }; } const source = found; // A source with no writers is refused by the route before anything runs. if (source.length === 0) return { kind: "ok", confirm: null }; const sourcePeople = new Set(source.map((r) => r.person_id)); const sourceByKey = new Map(source.map((r) => [rowKey(r), r])); const removes = []; const changes = []; const bind = [ `source:${sourceId}`, ...targets.map((t) => `target:${t}`), ]; for (const target of targets) { const rows = current.get(target) ?? []; const gone = new Map(); for (const r of rows) { if (!sourcePeople.has(r.person_id)) { const g = gone.get(r.person_id) ?? { name: r.person_name || r.person_id, roles: [], }; if (!g.roles.includes(r.role)) g.roles.push(r.role); gone.set(r.person_id, g); continue; } const next = sourceByKey.get(rowKey(r)); const name = r.person_name || r.person_id; if (!next) { changes.push({ target, text: `${name}'s role "${r.role}" goes (the source credits them as ${source .filter((x) => x.person_id === r.person_id) .map((x) => x.role) .join(", ")})`, bind: `role:${target}:${r.person_id}:${r.role}`, }); } else if (next.split_percentage !== r.split_percentage) { changes.push({ target, text: `${name}'s share ${pct(r.split_percentage)} → ${pct(next.split_percentage)}`, bind: `share:${target}:${r.person_id}:${r.role}:${r.split_percentage}>${next.split_percentage}`, }); } } for (const [person_id, g] of [...gone].sort(([a], [b]) => a.localeCompare(b))) { removes.push({ person_id, name: g.name, roles: g.roles, work_id: target, }); bind.push(`remove:${target}:${person_id}`); } } if (removes.length === 0 && changes.length === 0) { return { kind: "ok", confirm: null }; } bind.push(...changes.map((c) => c.bind)); // Per song, in target order, so the user sees which songs lose whom. // Titles are read for the affected songs only; a title that can't be read // shows the id (it's display, not the decision, so it doesn't fail closed). const affected = targets.filter((t) => removes.some((r) => r.work_id === t) || changes.some((c) => c.target === t)); const titles = new Map(); await Promise.all(affected.slice(0, SONGS_SHOWN).map(async (t) => { const work = await pica.works.get(t).catch(() => null); titles.set(t, work?.title || t); })); const songs = affected.map((t) => ({ work_id: t, title: titles.get(t) ?? t, removes: removes .filter((r) => r.work_id === t) .map((r) => `${r.name} (${r.roles.join(", ")})`), changes: changes.filter((c) => c.target === t).map((c) => c.text), })); for (const r of removes) r.work_title = titles.get(r.work_id ?? ""); const lines = [ `this replaces the writers on ${affected.length} of ${targets.length} song${targets.length === 1 ? "" : "s"} with the source's.`, ]; for (const song of songs.slice(0, SONGS_SHOWN)) { const parts = [ ...(song.removes.length ? [`removes ${song.removes.join(", ")}`] : []), ...song.changes, ]; lines.push(`${song.title}: ${parts.join("; ")}.`); } if (songs.length > SONGS_SHOWN) { lines.push(`+${songs.length - SONGS_SHOWN} more songs.`); } lines.push("songs with a locked split are skipped and keep their writers. check with the user that this is what they mean. each song's history keeps the change and can undo it."); return { kind: "ok", confirm: { preview: { action: "replace the writers on these works with the source's", target: targets.join(","), warning: lines.join(" "), display_name: "copy credits", removes, share_cuts: [], songs, }, bind, }, }; }; export const CONDITIONAL_CONFIRMS = { pica_credits_update: creditsUpdateCheck, pica_catalog_health_fix: catalogHealthFixCheck, pica_works_bulk_copy_credits: bulkCopyCreditsCheck, // Saving a field whole (8b's review): checks in list-replace-confirms.ts. pica_works_update: worksUpdateCheck, pica_people_update: peopleUpdateCheck, pica_agreements_update: agreementsUpdateCheck, pica_recordings_bulk_reassign_artist: reassignArtistCheck, pica_works_bulk_link_artist: linkArtistCheck, }; //# sourceMappingURL=conditional-confirm.js.map