UNPKG

@withpica/mcp-server

Version:

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

322 lines • 11.5 kB
// Copyright (c) 2025-2026 Withpica Ltd. All rights reserved. import { webOrigin } from "./relationships.js"; /** The five entity types `fetch` reads, and where each one's page is. */ export const FETCH_TYPES = { work: "works", person: "people", recording: "recordings", release: "releases", agreement: "agreements", }; const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** Parse `<type>:<uuid>`; null for anything else. */ export function parseFetchId(id) { if (typeof id !== "string") return null; const at = id.indexOf(":"); if (at < 1) return null; const type = id.slice(0, at); const uuid = id.slice(at + 1); if (!(type in FETCH_TYPES) || !UUID_RE.test(uuid)) return null; return { type: type, uuid }; } /** The entity a chain match is about, when it is one `fetch` can read. */ export function searchHit(r) { switch (r.match_type) { case "work": return r.work?.id ? { type: "work", id: r.work.id, title: r.work.primary_artist ? `${r.work.title ?? "untitled"} (${r.work.primary_artist})` : (r.work.title ?? "untitled"), } : null; case "person": return r.person?.id ? { type: "person", id: r.person.id, title: r.person.name ?? "unnamed" } : null; case "recording": return r.recording?.id ? { type: "recording", id: r.recording.id, title: r.recording.artist_name ? `${r.recording.recording_title ?? "untitled"} (${r.recording.artist_name})` : (r.recording.recording_title ?? "untitled"), } : null; case "release": return r.release?.id ? { type: "release", id: r.release.id, title: r.release.title ?? "untitled", } : null; case "agreement": { const a = r.standalone_agreement ?? r.agreement; return a?.id ? { type: "agreement", id: a.id, title: a.title ?? "untitled" } : null; } default: return null; } } /** * Human labels for the fields a summary reads, in reading order: column * names of each table's row as its GET route returns it (lib/db/database.types.ts; * pinned by realistic fixtures in openai-curated-surface.test.ts). No money * field is read. `cae_ipi_number` and `isni` on a person are shown when the * route adds them. */ const SUMMARY_FIELDS = { work: [ ["primary_artist", "artist"], ["iswc", "ISWC"], ["work_status", "status"], ["work_type", "type"], ["genre", "genre"], ["publisher_name", "publisher"], ], person: [ ["stage_names", "stage names"], ["roles", "roles"], ["cae_ipi_number", "IPI"], ["isni", "ISNI"], ["pro_name", "society"], ["biography", "about"], ], recording: [ ["artist_name", "artist"], ["isrc", "ISRC"], ["version_type", "version"], ["duration_ms", "length"], ["recorded_at", "recorded"], ["studio_name", "studio"], ], release: [ ["release_type", "type"], ["release_format", "format"], ["release_date", "released"], ["upc", "UPC"], ["catalog_number", "catalogue number"], ["parent_label", "label"], ], agreement: [ ["agreement_type", "type"], ["status", "status"], ["other_party_name", "with"], ["start_date", "starts"], ["end_date", "ends"], ], }; const TITLE_FIELDS = { work: ["title"], person: ["name", "full_name", "display_name"], recording: ["recording_title", "title"], release: ["title"], agreement: ["title", "name"], }; function show(value) { if (value === null || value === undefined || value === "") return null; if (Array.isArray(value)) { const parts = value.filter((v) => typeof v === "string" || typeof v === "number"); return parts.length ? parts.join(", ") : null; } if (typeof value === "string" || typeof value === "number") return String(value); if (typeof value === "boolean") return value ? "yes" : "no"; return null; } /** 215000 → "3:35". */ function minutesSeconds(ms) { if (typeof ms !== "number" || !Number.isFinite(ms) || ms <= 0) return null; const total = Math.round(ms / 1000); return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`; } /** A plain-English summary of one entity, built from its known fields. */ export function summarise(type, entity) { const title = TITLE_FIELDS[type].map((f) => show(entity[f])).find(Boolean) ?? "untitled"; const metadata = {}; const lines = [`${title} (${type})`]; for (const [field, label] of SUMMARY_FIELDS[type]) { const v = field === "duration_ms" ? minutesSeconds(entity[field]) : show(entity[field]); if (v) { lines.push(`${label}: ${v}`); metadata[field] = v; } } return { title, text: lines.join("\n"), metadata }; } /** * The entity's own row from its read: the SDK already unwraps the * `{success, data}` envelope the works, people, recordings and releases * routes answer; the agreements route answers `{success, agreement, …}`. */ export function unwrap(type, entity) { const row = type === "agreement" ? entity.agreement : (entity.data ?? entity); return row && typeof row === "object" ? row : null; } function both(payload) { return { content: [{ type: "text", text: JSON.stringify(payload) }], structuredContent: payload, }; } function notFound(id) { return { content: [ { type: "text", text: JSON.stringify({ error: "NOT_FOUND", message: `nothing to fetch for ${JSON.stringify(id)}. use an id that search returned, like work:<uuid>.`, }), }, ], isError: true, }; } export class OpenAiSearchFetchTools { pica; origin; constructor(pica, apiUrl) { this.pica = pica; this.origin = webOrigin(apiUrl); } url(type, id) { return `${this.origin}/inspect/${FETCH_TYPES[type]}/${id}`; } getTools() { return [ { definition: { name: "search", scope: "read:catalog", audiences: ["http"], hosts: ["openai"], tier: "read", description: "Search the user's catalogue: works, people, recordings, releases and agreements, by name, title, ISWC, ISRC or IPI. " + "Returns results with an id, a title and a link to the record. Pass a result's id to fetch for the full record.", workflows: "infrastructure", vernacular_kind: "specialist", vernacular_reason: "Named and shaped by the host's deep-research contract (search/fetch), not by a creator question.", annotations: { title: "search the catalogue" }, inputSchema: { type: "object", properties: { query: { type: "string", description: "what to look for: a title, a name or a code", }, }, required: ["query"], }, }, executor: this.search.bind(this), }, { definition: { name: "fetch", scope: "read:catalog", audiences: ["http"], hosts: ["openai"], tier: "read", description: "Read one record from the user's catalogue by an id that search returned (work:<uuid>, person:<uuid>, recording:<uuid>, release:<uuid> or agreement:<uuid>). " + "Returns its title, a readable summary and a link to it.", workflows: "infrastructure", vernacular_kind: "specialist", vernacular_reason: "Named and shaped by the host's deep-research contract (search/fetch), not by a creator question.", annotations: { title: "read a record" }, inputSchema: { type: "object", properties: { id: { type: "string", description: "an id from search, like work:<uuid>", }, }, required: ["id"], }, }, executor: this.fetch.bind(this), }, ]; } async search(args) { const query = typeof args.query === "string" ? args.query.trim() : ""; if (!query) return both({ results: [] }); const found = (await this.pica.chain.search({ q: query, limit: 20 })); const seen = new Set(); const results = []; for (const r of found.results ?? []) { const hit = searchHit(r); if (!hit) continue; const id = `${hit.type}:${hit.id}`; if (seen.has(id)) continue; seen.add(id); results.push({ id, title: hit.title, url: this.url(hit.type, hit.id) }); } return both({ results }); } async fetch(args) { const parsed = parseFetchId(args.id); if (!parsed) return notFound(args.id); const { type, uuid } = parsed; let entity; try { entity = await this.read(type, uuid); } catch { // Not this org's, not readable with this credential, or gone: one // answer, so nothing about another organisation leaks. return notFound(args.id); } if (!entity || typeof entity !== "object") return notFound(args.id); const record = unwrap(type, entity); if (!record) return notFound(args.id); const { title, text, metadata } = summarise(type, record); return both({ id: `${type}:${uuid}`, title, text, url: this.url(type, uuid), metadata, }); } read(type, id) { switch (type) { case "work": return this.pica.works.get(id); case "person": return this.pica.people.get(id); case "recording": return this.pica.recordings.get(id); case "release": return this.pica.releases.get(id); case "agreement": return this.pica.agreements.get(id); } } } //# sourceMappingURL=openai-search-fetch.js.map