@withpica/mcp-server
Version:
MCP Server for withPICA — enables AI assistants to interact with your withPICA music catalog
455 lines • 18.3 kB
JavaScript
// Copyright (c) 2025-2026 Withpica Ltd. All rights reserved.
/**
* Write tools that save a field WHOLE, so a shorter value drops what was
* there (8b's MCP review, medium "saving a list replaces it whole"). The
* founder's 2026-11-20 credits rule: ask first when something real is lost;
* otherwise keep the old value so the change can be undone.
*
* Each check below returns a preview only when the call would drop or
* change something already stored. A call that only adds, or fills an empty
* field, runs at once. The ask is the same server-side two-step token as
* pica_credits_update (conditional-confirm.ts), bound to the call AND to
* what would be lost, so a token for one loss never confirms another.
*
* Which tool gets what, and why:
* - pica_works_update `mood` (tags on the primary recording, not a works
* column, so the song's history can't keep it) and `metadata` (one JSON
* object saved whole: a missing key is gone). `genre` needs no ask: it is
* a catalogue value field, so the history keeps the old list.
* - pica_people_update `emails`, `social_media`, `tags`, `origin_countries`:
* personal fields, which the history records by name only (founder
* decision 2026-09-29, lib/config/edit-value-fields.ts PERSONAL_FIELDS).
* So the preview names only what kind of thing goes and how many, and the
* binding is a hash of the removed values, never the values. stage_names
* and roles are catalogue value fields, undoable from history.
* - pica_agreements_update: the money and term fields. Changing or clearing
* a stored term asks; setting an empty one doesn't. The preview names the
* fields, never the amounts.
*
* Every read here fails closed: if PICA can't read what is stored, nothing
* is saved and the caller is told to try again. A record that isn't found
* is left to the route, which answers not-found itself.
*/
import { createHash } from "node:crypto";
import { ApiError } from "@withpica/mcp-sdk";
import { typedError } from "./error-envelope.js";
/** JSON with object keys sorted, so the same value hashes 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);
}
/** A short hash of a value: binds what is lost without carrying it. */
function digest(value) {
return createHash("sha256")
.update(canonical(value))
.digest("hex")
.slice(0, 16);
}
const isNotFound = (err) => err instanceof ApiError && err.status === 404;
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
/** Strings from a list, trimmed, case-folded for comparing. */
function stringSet(value) {
const out = new Map();
if (!Array.isArray(value))
return out;
for (const v of value) {
if (typeof v !== "string")
continue;
const t = v.trim();
if (t)
out.set(t.toLowerCase(), t);
}
return out;
}
/** What `before` holds that `after` doesn't, by case-folded value. */
function droppedStrings(before, after) {
const a = stringSet(after);
return [...stringSet(before)]
.filter(([k]) => !a.has(k))
.map(([, v]) => v)
.sort();
}
function refuse(code, what) {
return {
kind: "refuse",
result: typedError(code, `Nothing was saved: PICA couldn't read ${what} to check whether this change removes anything. Try again in a minute.`),
};
}
// ---------------------------------------------------------------------------
// pica_works_update
// ---------------------------------------------------------------------------
export const worksUpdateCheck = async (pica, args) => {
const id = typeof args.id === "string" ? args.id : "";
// Any value sent counts, as the save reads it: null clears, and a string
// mood becomes a one-tag list (validateStringArrayFields).
const sendsMood = args.mood !== undefined;
const sendsMetadata = args.metadata !== undefined;
if (!id || (!sendsMood && !sendsMetadata))
return { kind: "ok", confirm: null };
let work;
try {
work = (await pica.works.get(id));
}
catch (err) {
if (isNotFound(err))
return { kind: "ok", confirm: null };
return refuse("WORK_REPLACE_CHECK_FAILED", "this song as it is now");
}
const nextMood = typeof args.mood === "string" ? [args.mood] : (args.mood ?? []);
const moodsLost = sendsMood ? droppedStrings(work.mood, nextMood) : [];
const before = work.metadata &&
typeof work.metadata === "object" &&
!Array.isArray(work.metadata)
? work.metadata
: {};
const after = args.metadata &&
typeof args.metadata === "object" &&
!Array.isArray(args.metadata)
? args.metadata
: {};
const keysLost = sendsMetadata
? Object.keys(before)
.filter(
// A key sent as null is cleared, the same as one left out.
(k) => before[k] !== undefined && before[k] !== null && after[k] == null)
.sort()
: [];
if (moodsLost.length === 0 && keysLost.length === 0) {
return { kind: "ok", confirm: null };
}
const lines = [];
if (moodsLost.length > 0)
lines.push(`this removes the mood ${moodsLost.length === 1 ? "tag" : "tags"} ${moodsLost.map((m) => `"${m}"`).join(", ")}, because the list leaves ${moodsLost.length === 1 ? "it" : "them"} out.`);
if (keysLost.length > 0)
lines.push(`metadata is saved whole, so this drops ${plural(keysLost.length, "stored key")} (${keysLost.join(", ")}). to keep ${keysLost.length === 1 ? "it" : "them"}, send the full metadata with your change.`);
lines.push("check with the user that this is what they mean; it can't be undone from the song's history.");
return {
kind: "ok",
confirm: {
preview: {
action: "replace a song's mood tags or metadata",
target: id,
warning: lines.join(" "),
display_name: "update song",
moods_removed: moodsLost,
metadata_keys_removed: keysLost,
},
bind: [
...moodsLost.map((m) => `mood:${m.toLowerCase()}`),
...keysLost.map((k) => `metadata:${k}:${digest(before[k])}`),
],
},
};
};
// ---------------------------------------------------------------------------
// pica_people_update
// ---------------------------------------------------------------------------
/** An email entry's address, case-folded; entries may be strings or objects. */
function emailsOf(value) {
if (!Array.isArray(value))
return [];
const out = [];
for (const e of value) {
const addr = typeof e === "string"
? e
: e && typeof e === "object"
? e.email
: null;
if (typeof addr === "string" && addr.trim())
out.push(addr.trim().toLowerCase());
}
return out;
}
/** Social links as "platform=handle", for comparing. */
function socialsOf(value) {
if (!value || typeof value !== "object" || Array.isArray(value))
return [];
return Object.entries(value)
.filter(([, v]) => typeof v === "string" && v.trim() !== "")
.map(([k, v]) => `${k.toLowerCase()}=${v.trim().toLowerCase()}`);
}
const PERSONAL_LISTS = [
{
field: "emails",
kind: ["email address", "email addresses"],
read: emailsOf,
},
{
field: "social_media",
kind: ["social link", "social links"],
read: socialsOf,
},
{
field: "tags",
kind: ["tag", "tags"],
read: (v) => [...stringSet(v).keys()],
},
{
field: "origin_countries",
kind: ["country", "countries"],
read: (v) => [...stringSet(v).keys()],
},
];
export const peopleUpdateCheck = async (pica, args) => {
const id = typeof args.id === "string" ? args.id : "";
const sent = PERSONAL_LISTS.filter((l) => args[l.field] !== undefined);
if (!id || sent.length === 0)
return { kind: "ok", confirm: null };
let person;
try {
person = (await pica.people.get(id));
}
catch (err) {
if (isNotFound(err))
return { kind: "ok", confirm: null };
return refuse("PERSON_REPLACE_CHECK_FAILED", "this person as they are now");
}
const losses = [];
const bind = [];
for (const l of sent) {
const next = new Set(args[l.field] === null ? [] : l.read(args[l.field]));
const gone = [...new Set(l.read(person[l.field]))]
.filter((v) => !next.has(v))
.sort();
if (gone.length === 0)
continue;
losses.push({
field: l.field,
kind: gone.length === 1 ? l.kind[0] : l.kind[1],
count: gone.length,
});
// The removed set, hashed: a token for these never confirms others.
bind.push(`${l.field}:${digest(gone)}`);
}
if (losses.length === 0)
return { kind: "ok", confirm: null };
const what = losses.map((x) => `${x.count} ${x.kind}`).join(", ");
return {
kind: "ok",
confirm: {
preview: {
action: "replace a person's contact details or tags",
target: id,
// Kind and count only: these are personal details, kept by name only.
warning: `this list is saved whole, so it removes ${what} this person has now. check with the user that this is what they mean; PICA keeps no copy of the old details, so it can't be undone. to add one, send the full list with it.`,
display_name: "update person",
removes: losses,
},
bind,
},
};
};
// ---------------------------------------------------------------------------
// pica_agreements_update
// ---------------------------------------------------------------------------
/** The money and term fields of an agreement (write-schemas AGREEMENTS_WRITE_PROPERTIES). */
export const AGREEMENT_TERM_FIELDS = [
"advance_amount",
"advance_currency",
"is_recoupable",
"financial_terms",
"agreement_terms",
"termination_notice_period_days",
"include_future_works",
"start_date",
"end_date",
"expires_at",
"renewal_date",
"termination_date",
];
const isEmpty = (v) => v === undefined ||
v === null ||
v === "" ||
(Array.isArray(v) && v.length === 0) ||
(typeof v === "object" &&
!Array.isArray(v) &&
Object.keys(v).length === 0);
export const agreementsUpdateCheck = async (pica, args) => {
const id = typeof args.id === "string" ? args.id : "";
const sent = AGREEMENT_TERM_FIELDS.filter((f) => args[f] !== undefined);
if (!id || sent.length === 0)
return { kind: "ok", confirm: null };
let agreement;
try {
agreement = (await pica.agreements.get(id));
}
catch (err) {
if (isNotFound(err))
return { kind: "ok", confirm: null };
return refuse("AGREEMENT_TERMS_CHECK_FAILED", "this agreement's terms as they are now");
}
const changed = [];
const cleared = [];
for (const f of sent) {
const was = agreement[f];
// A term withheld from this caller reads as absent: the route refuses
// the write itself (FINANCE_ACCESS_REQUIRED), so nothing is asked here.
if (isEmpty(was))
continue;
if (isEmpty(args[f]))
cleared.push(f);
else if (canonical(was) !== canonical(args[f]))
changed.push(f);
}
if (changed.length === 0 && cleared.length === 0) {
return { kind: "ok", confirm: null };
}
changed.sort();
cleared.sort();
const lines = [];
if (changed.length > 0)
lines.push(`this changes ${plural(changed.length, "agreed term")}: ${changed.join(", ")}.`);
if (cleared.length > 0)
lines.push(`this clears ${plural(cleared.length, "agreed term")}: ${cleared.join(", ")}.`);
lines.push("these are what the agreement says, so check with the user, and with the other side where it was signed, before saving.");
return {
kind: "ok",
confirm: {
preview: {
action: "change an agreement's terms",
target: id,
warning: lines.join(" "),
display_name: "update agreement",
terms_changed: changed,
terms_cleared: cleared,
},
bind: [
...changed.map((f) => `change:${f}:${digest(agreement[f])}`),
...cleared.map((f) => `clear:${f}:${digest(agreement[f])}`),
],
},
};
};
// ---------------------------------------------------------------------------
// pica_recordings_bulk_reassign_artist, pica_works_bulk_link_artist
// ---------------------------------------------------------------------------
/** Records named in a re-link preview's text; the rest are counted. */
const RECORDS_SHOWN = 20;
/** The dry run's `replaces`, or null when the answer doesn't carry it. */
function lossesOf(preview) {
const p = preview;
if (!p || !Array.isArray(p.replaces))
return null;
const losses = p.replaces.filter((l) => l && typeof l.id === "string");
const count = typeof p.replaces_count === "number" ? p.replaces_count : losses.length;
// The digest covers every lost record, listed or not (8b). Without it a
// capped list can't pin the whole set, so the check can't vouch for it.
if (typeof p.replaces_digest === "string") {
return { losses, count, digest: p.replaces_digest };
}
return count > losses.length
? null
: {
losses,
count,
digest: digest(losses.map((l) => [l.id, l.from_person_id, l.from_name])),
};
}
function artistConfirm(input) {
const { losses, count } = input;
const named = losses
.slice(0, RECORDS_SHOWN)
.map((l) => `${l.title || l.id}: loses ${l.from_name || "its artist"}.`);
const more = count - named.length;
const warning = [
`this changes the artist on ${plural(count, input.kind[0], input.kind[1])} that already ${count === 1 ? "has" : "have"} one, to ${input.to}.`,
...named,
...(more > 0 ? [`+${more} more.`] : []),
"PICA keeps no history of these links yet, so check with the user before going on.",
].join(" ");
return {
kind: "ok",
confirm: {
preview: {
action: input.action,
target: input.target,
warning,
display_name: input.display_name,
replaces: losses,
replaces_count: count,
},
// Every lost record and what it loses, through the dry run's digest.
bind: [`count:${count}`, `losses:${input.digest}`],
},
};
}
export const reassignArtistCheck = async (pica, args) => {
if (args.dry_run === true)
return { kind: "ok", confirm: null };
const ids = Array.isArray(args.recording_ids)
? args.recording_ids.filter((x) => typeof x === "string")
: [];
const from = typeof args.from_person_id === "string" ? args.from_person_id : "";
// A malformed selector is the executor's to refuse.
if ((ids.length === 0) === !from)
return { kind: "ok", confirm: null };
const to = typeof args.to_person_id === "string" ? args.to_person_id : null;
let preview;
try {
preview = await pica.bulk.reassignRecordingArtist({
recordingIds: ids.length > 0 ? ids : undefined,
fromPersonId: from || undefined,
toPersonId: to,
dryRun: true,
});
}
catch (err) {
if (err instanceof ApiError && err.status < 500)
return { kind: "ok", confirm: null };
return refuse("REASSIGN_CHECK_FAILED", "these recordings' artists");
}
const found = lossesOf(preview?.data ?? preview);
if (!found)
return refuse("REASSIGN_CHECK_FAILED", "these recordings' artists");
if (found.count === 0)
return { kind: "ok", confirm: null };
return artistConfirm({
kind: ["recording", "recordings"],
target: ids.length > 0 ? ids.slice().sort().join(",") : `from:${from}`,
action: "change the artist on recordings",
display_name: "reassign artist",
to: to ? `person ${to}` : "no artist",
...found,
});
};
export const linkArtistCheck = async (pica, args) => {
if (args.dry_run === true)
return { kind: "ok", confirm: null };
const ids = Array.isArray(args.work_ids)
? args.work_ids.filter((x) => typeof x === "string")
: [];
const person = typeof args.person_id === "string" ? args.person_id : "";
const name = typeof args.artist_name === "string" ? args.artist_name : "";
if (ids.length === 0 || !person || !name)
return { kind: "ok", confirm: null };
let preview;
try {
preview = await pica.bulk.linkArtist(ids, person, name, true);
}
catch (err) {
if (err instanceof ApiError && err.status < 500)
return { kind: "ok", confirm: null };
return refuse("LINK_ARTIST_CHECK_FAILED", "these songs' artists");
}
const found = lossesOf(preview?.data ?? preview);
if (!found)
return refuse("LINK_ARTIST_CHECK_FAILED", "these songs' artists");
if (found.count === 0)
return { kind: "ok", confirm: null };
return artistConfirm({
kind: ["song", "songs"],
target: ids.slice().sort().join(","),
action: "change the artist on songs",
display_name: "link artist",
to: name,
...found,
});
};
//# sourceMappingURL=list-replace-confirms.js.map