cc0-library-mcp 0.2.12 → 0.2.13

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/README.md CHANGED
@@ -46,7 +46,7 @@ Loading is progressive: a progress bar tracks four steps (finding works, floor a
46
46
  | Re-check before download | — | `get_asset` re-checks CC0 at the source |
47
47
  | "Looks free but isn't" list | — | Unsplash, Pixabay, Pexels, SMK (Public Domain Mark), NASA |
48
48
  | Asset types | Images, audio | Images, audio, video, HDRIs, textures, 3D models, artworks, whole collections |
49
- | AI assistant access | REST API | MCP server (`search_assets`, `get_asset`, `list_sources`) |
49
+ | AI assistant access | REST API | MCP server (`search_assets`, `get_asset`, `download_asset`, `list_sources`) |
50
50
 
51
51
  ### Who declared CC0?
52
52
 
@@ -142,8 +142,9 @@ claude mcp add cc0-library -- node "$PWD/dist/index.js"
142
142
 
143
143
  | Tool | Input | Returns |
144
144
  |---|---|---|
145
- | `search_assets` | `query`, `kind` (`image`·`audio`·`video`·`hdri`·`texture`·`model`·`artwork`·`collection`·`any`, default `any`; `any` excludes `collection`), `limit` 1–20, `page` 1–12, optional `providers` (e.g. `["iconify"]` for icons) | CC0 assets ranked by query words in title and tags, per-provider totals, per-provider errors |
145
+ | `search_assets` | `query`, `kind` (`image`·`audio`·`video`·`hdri`·`texture`·`model`·`artwork`·`collection`·`any`, default `any`; `any` excludes `collection`), `limit` 1–20, `page` 1–12, optional `providers` (e.g. `["iconify"]` for icons) | CC0 assets ranked by query words in title and tags, per-provider totals, per-provider errors, and `pending` sources that missed the 10 s deadline. Uploader-declared items that name a known franchise or brand, or say they are fan-made, carry `riskFlags` |
146
146
  | `get_asset` | `id` from `search_assets` (`openverse:image:<uuid>`, `openverse:audio:<uuid>`, `polyhaven:<slug>`, `ambientcg:<assetId>`, `cleveland:<number>`, `met:<number>`, `commons:<pageid>`, `archive:<identifier>`, `sketchfab:<uid>`, `wpphotos:<number>`, `inaturalist:<n>`, `gbif:<n>`, `phylopic:<uuid>`, `iconify:<set>:<icon>`, `zenodo:<n>`, `blenderkit:<uuid>`, `github:<owner>/<repo>`, `huggingface:<owner>/<dataset>`) | Details plus download URLs (Poly Haven: up to 60 map/resolution/format files; Sketchfab: model page only, because downloads need the user's own login) |
147
+ | `download_asset` | `id`, `dir` (folder to save into), `files` (exact labels from `get_asset`; optional when the asset has one file) | Saves the files under `<dir>/<asset id>/` with each model's companion files (glTF `.bin` and textures) at their relative paths, and writes `cc0.json` with the source, creator, license evidence, `riskFlags` and download time. Login-only pages (Sketchfab, BlenderKit, Freesound originals) are reported in `skipped`; zips are saved as-is |
147
148
  | `list_sources` | `kind` (optional) | Curated catalog, the non-CC0 list, and the pending-verification list |
148
149
 
149
150
  Results are ranked by how many query words appear in each item's title (weight 2) or tags (weight 1); ties alternate between providers. Loose matches, such as a GBIF record that mentions the word only in its locality, sink below exact ones.
@@ -247,6 +248,8 @@ See [CONTRIBUTING.md](CONTRIBUTING.md). In short:
247
248
  - 웹에서 바로 검색할 수 있습니다: https://sanghyole.github.io/cc0-library/
248
249
  - **CC0 미술관**: 주제어를 넣으면 CC0 그림·조각·바닥·조명·배경음으로 3D 전시실을 만들어 걸어 다닐 수 있습니다. WebGPU로 그리고, WebGPU가 없는 브라우저에서는 WebGL2로 자동 전환합니다. https://sanghyole.github.io/cc0-library/museum.html
249
250
  - `get_asset`은 다운로드 URL을 주기 전에 원본에서 CC0 여부를 다시 확인합니다.
251
+ - `download_asset`은 고른 파일을 `<dir>/<asset id>/`에 저장합니다. glTF의 `.bin`과 텍스처 같은 부속 파일도 제자리에 함께 받고, 출처·제작자·라이선스 근거·받은 시각을 `cc0.json`에 남깁니다.
252
+ - 업로더가 CC0라고만 선언한 항목 중 제목이나 태그에 유명 게임·영화·브랜드 이름이 있거나 팬아트라고 적힌 항목에는 `riskFlags`가 붙습니다. CC0 표시가 있어도 원작자의 권리는 남아 있다는 경고입니다.
250
253
  - `list_sources`는 검증한 CC0 자료원 681곳의 목록을 줍니다. 종류별로 이미지 323곳, 오디오 181곳, 3D 119곳, 데이터 컬렉션 110곳, 텍스처 48곳, 영상 37곳, 폰트 35곳, 미술품 29곳, HDRI 10곳입니다. CC0가 아닌 무료 사이트(Unsplash, Pixabay, Pexels, Pixnio, SMK, NASA, Coverr, Burst, Mixkit, Gratisography, Natural Earth)와 그 이유도 줍니다. 아직 검증하지 못한 후보도 따로 줍니다.
251
254
 
252
255
  - 매주 자동 점검이 목록의 라이선스 페이지를 다시 확인하고 새 후보를 찾습니다.
@@ -0,0 +1,178 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createWriteStream } from "node:fs";
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { Readable, Transform } from "node:stream";
6
+ import { pipeline } from "node:stream/promises";
7
+ /** Largest single file saved; Poly Haven 16K HDRIs are about 700 MB. */
8
+ export const MAX_FILE_BYTES = 1024 ** 3;
9
+ /** Most files one call may pick; a glTF's companions do not count. */
10
+ export const MAX_FILES_PER_CALL = 10;
11
+ export const RECEIPT_NAME = "cc0.json";
12
+ /** Thrown when the request cannot be served as asked; the message says what to change. */
13
+ export class DownloadRequestError extends Error {
14
+ }
15
+ /** Folder and file names: keep letters, digits, dot, dash and underscore. */
16
+ export function safeName(s) {
17
+ const name = s.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^[._]+/, "").slice(0, 120);
18
+ return name || "file";
19
+ }
20
+ /** A companion path from the source (e.g. "textures/door_diff_1k.jpg"), or null if it would leave the folder. */
21
+ export function safeRelativePath(p) {
22
+ if (!p || p.startsWith("/") || p.includes("\\") || /^[A-Za-z]:/.test(p))
23
+ return null;
24
+ const parts = p.split("/");
25
+ if (parts.some((x) => x === "" || x === "." || x === ".."))
26
+ return null;
27
+ return parts.map(safeName).join("/");
28
+ }
29
+ function fileNameFor(file) {
30
+ try {
31
+ const base = decodeURIComponent(new URL(file.url).pathname.split("/").pop() ?? "");
32
+ // ambientCG serves zips from /get?file=<name>.zip
33
+ const fromQuery = new URL(file.url).searchParams.get("file");
34
+ const name = /\.[A-Za-z0-9]{1,6}$/.test(base) ? base : fromQuery ?? "";
35
+ if (name)
36
+ return safeName(name);
37
+ }
38
+ catch {
39
+ // fall through to the label
40
+ }
41
+ return safeName(file.label);
42
+ }
43
+ /**
44
+ * Picks files by exact label. With no labels, an asset with exactly one file
45
+ * gets that file; otherwise the caller must choose, because sources like Poly
46
+ * Haven list dozens of resolutions and formats.
47
+ */
48
+ export function pickFiles(asset, labels) {
49
+ const list = (asset.files ?? []).map((f) => f.label);
50
+ const show = () => `Available files: ${list.slice(0, 40).map((l) => JSON.stringify(l)).join(", ")}${list.length > 40 ? `, … (${list.length} total)` : ""}`;
51
+ if (!asset.files?.length)
52
+ throw new DownloadRequestError(`${asset.id} lists no downloadable files. Use its landingUrl: ${asset.landingUrl}`);
53
+ if (!labels?.length) {
54
+ if (asset.files.length === 1)
55
+ return asset.files;
56
+ throw new DownloadRequestError(`${asset.id} has ${asset.files.length} files; pass \`files\` with one or more exact labels. ${show()}`);
57
+ }
58
+ if (labels.length > MAX_FILES_PER_CALL)
59
+ throw new DownloadRequestError(`Pick at most ${MAX_FILES_PER_CALL} files per call.`);
60
+ const unknown = labels.filter((l) => !list.includes(l));
61
+ if (unknown.length)
62
+ throw new DownloadRequestError(`Unknown file label(s): ${unknown.map((l) => JSON.stringify(l)).join(", ")}. ${show()}`);
63
+ return asset.files.filter((f) => labels.includes(f.label));
64
+ }
65
+ async function saveOne(download, url, target) {
66
+ let res;
67
+ try {
68
+ res = await download(url);
69
+ }
70
+ catch (e) {
71
+ return `request failed: ${e instanceof Error ? e.message : String(e)}`;
72
+ }
73
+ if (!res.ok)
74
+ return `HTTP ${res.status}`;
75
+ const type = res.headers.get("content-type") ?? "";
76
+ if (/^text\/html/i.test(type)) {
77
+ await res.body?.cancel();
78
+ return "the URL is a web page, not a file (the source needs a login or a browser download); open it from landingUrl";
79
+ }
80
+ const declared = Number(res.headers.get("content-length"));
81
+ if (declared > MAX_FILE_BYTES) {
82
+ await res.body?.cancel();
83
+ return `file is ${declared} bytes, over the ${MAX_FILE_BYTES}-byte limit`;
84
+ }
85
+ if (!res.body)
86
+ return "empty response";
87
+ const hash = createHash("sha256");
88
+ let bytes = 0;
89
+ const meter = new Transform({
90
+ transform(chunk, _enc, cb) {
91
+ bytes += chunk.length;
92
+ if (bytes > MAX_FILE_BYTES)
93
+ return cb(new Error(`over the ${MAX_FILE_BYTES}-byte limit`));
94
+ hash.update(chunk);
95
+ cb(null, chunk);
96
+ },
97
+ });
98
+ await mkdir(path.dirname(target), { recursive: true });
99
+ try {
100
+ await pipeline(Readable.fromWeb(res.body), meter, createWriteStream(target));
101
+ }
102
+ catch (e) {
103
+ await rm(target, { force: true });
104
+ return `download failed: ${e instanceof Error ? e.message : String(e)}`;
105
+ }
106
+ return { bytes, sha256: hash.digest("hex") };
107
+ }
108
+ /**
109
+ * Saves the chosen files of an already CC0-checked asset into `<dir>/<asset id>/`,
110
+ * with each file's companions (`includes`) at their relative paths, and writes a
111
+ * `cc0.json` receipt recording where each file came from and the license evidence
112
+ * at download time. Files that cannot be fetched are listed in `skipped`.
113
+ */
114
+ export async function downloadAsset(download, asset, dir, labels, now = () => new Date()) {
115
+ const chosen = pickFiles(asset, labels);
116
+ const folder = path.resolve(dir, safeName(asset.id.replace(/:/g, "_")));
117
+ await mkdir(folder, { recursive: true });
118
+ const saved = [];
119
+ const skipped = [];
120
+ const used = new Set();
121
+ const unique = (rel) => {
122
+ let out = rel;
123
+ for (let n = 2; used.has(out); n++)
124
+ out = rel.replace(/(\.[^./]+)?$/, `-${n}$1`);
125
+ used.add(out);
126
+ return out;
127
+ };
128
+ for (const file of chosen) {
129
+ const rel = unique(fileNameFor(file));
130
+ const r = await saveOne(download, file.url, path.join(folder, rel));
131
+ if (typeof r === "string") {
132
+ skipped.push({ label: file.label, url: file.url, reason: r });
133
+ continue;
134
+ }
135
+ saved.push({ label: file.label, path: rel, url: file.url, ...r });
136
+ for (const inc of file.includes ?? []) {
137
+ const incRel = safeRelativePath(inc.path);
138
+ const label = `${file.label} + ${inc.path}`;
139
+ if (!incRel) {
140
+ skipped.push({ label, url: inc.url, reason: "companion path would leave the asset folder" });
141
+ continue;
142
+ }
143
+ // Companions are shared between variants of one model (e.g. the .bin); save each path once.
144
+ if (used.has(incRel))
145
+ continue;
146
+ used.add(incRel);
147
+ const ri = await saveOne(download, inc.url, path.join(folder, incRel));
148
+ if (typeof ri === "string")
149
+ skipped.push({ label, url: inc.url, reason: ri });
150
+ else
151
+ saved.push({ label, path: incRel, url: inc.url, ...ri });
152
+ }
153
+ }
154
+ const receipt = path.join(folder, RECEIPT_NAME);
155
+ // A second call for the same asset adds to the receipt instead of replacing it.
156
+ const earlier = await readFile(receipt, "utf8").then((t) => JSON.parse(t), () => null);
157
+ const merged = new Map();
158
+ if (earlier?.id === asset.id)
159
+ for (const f of earlier.files ?? [])
160
+ merged.set(f.path, f);
161
+ for (const f of saved)
162
+ merged.set(f.path, f);
163
+ await writeFile(receipt, JSON.stringify({
164
+ id: asset.id,
165
+ title: asset.title,
166
+ creator: asset.creator,
167
+ landingUrl: asset.landingUrl,
168
+ provider: asset.provider,
169
+ origin: asset.origin,
170
+ license: asset.licenseEvidence,
171
+ ...(asset.riskFlags && { riskFlags: asset.riskFlags }),
172
+ servedBy: asset.servedBy,
173
+ checkedAt: now().toISOString(),
174
+ files: [...merged.values()],
175
+ ...(skipped.length && { skipped }),
176
+ }, null, 2) + "\n");
177
+ return { folder, saved, skipped, receipt };
178
+ }
package/dist/http.js CHANGED
@@ -2,8 +2,10 @@
2
2
  * Poly Haven's API terms require a User-Agent that names the calling app.
3
3
  * Openverse also asks clients to identify themselves.
4
4
  */
5
- export const USER_AGENT = "cc0-library-mcp/0.2.12 (+https://github.com/sanghyoLe/cc0-library)";
5
+ export const USER_AGENT = "cc0-library-mcp/0.2.13 (+https://github.com/sanghyoLe/cc0-library)";
6
6
  const TIMEOUT_MS = 15_000;
7
+ /** File downloads can be hundreds of MB, so they get far longer than API calls. */
8
+ const DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
7
9
  export class UpstreamError extends Error {
8
10
  provider;
9
11
  status;
@@ -17,6 +19,7 @@ export const defaultFetch = (url, init) => fetch(url, {
17
19
  headers: { "User-Agent": USER_AGENT, Accept: "application/json", ...init?.headers },
18
20
  signal: AbortSignal.timeout(TIMEOUT_MS),
19
21
  });
22
+ export const defaultDownload = (url) => fetch(url, { headers: { "User-Agent": USER_AGENT }, signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
20
23
  /** Gateway errors that upstreams (notably Openverse) return transiently under load. */
21
24
  const RETRYABLE = new Set([502, 503, 504]);
22
25
  const RETRY_DELAY_MS = 500;
@@ -40,6 +40,44 @@ export function toAsset(o) {
40
40
  servedBy: SERVED_BY,
41
41
  };
42
42
  }
43
+ /**
44
+ * The Met's API sits behind bot protection that stalls or rejects (without CORS
45
+ * headers) a burst of parallel object requests, so they go a few at a time.
46
+ * The detail phase also has a deadline: The Met can take 10-30 s per object,
47
+ * and objects still pending then are left out rather than holding the search open.
48
+ */
49
+ const MET_CONCURRENCY = 4;
50
+ const MET_DETAIL_DEADLINE_MS = 12_000;
51
+ /**
52
+ * Like Promise.allSettled over items.map(fn), with at most `limit` calls in flight; keeps input order.
53
+ * Items not settled within `deadlineMs` are reported as rejected and no new calls start after it.
54
+ */
55
+ export async function settleWithLimit(items, limit, fn, deadlineMs = Infinity) {
56
+ const out = new Array(items.length);
57
+ let next = 0;
58
+ let expired = false;
59
+ const worker = async () => {
60
+ while (!expired && next < items.length) {
61
+ const i = next++;
62
+ try {
63
+ out[i] = { status: "fulfilled", value: await fn(items[i]) };
64
+ }
65
+ catch (reason) {
66
+ out[i] = { status: "rejected", reason };
67
+ }
68
+ }
69
+ };
70
+ const all = Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
71
+ let timer;
72
+ if (Number.isFinite(deadlineMs)) {
73
+ await Promise.race([all, new Promise((r) => (timer = setTimeout(() => ((expired = true), r()), deadlineMs)))]);
74
+ clearTimeout(timer);
75
+ }
76
+ else {
77
+ await all;
78
+ }
79
+ return Array.from(out, (r) => r ?? { status: "rejected", reason: new Error("deadline passed") });
80
+ }
43
81
  const fetchObject = (fetchImpl, id) => getJson(fetchImpl, "The Met", `${OBJECT}/${id}`);
44
82
  export async function searchMet(fetchImpl, params) {
45
83
  const qs = new URLSearchParams({
@@ -50,7 +88,7 @@ export async function searchMet(fetchImpl, params) {
50
88
  });
51
89
  const search = await getJson(fetchImpl, "The Met", `${SEARCH}?${qs}`);
52
90
  const ids = (search.objectIDs ?? []).slice(0, params.limit);
53
- const objects = await Promise.allSettled(ids.map((id) => fetchObject(fetchImpl, id)));
91
+ const objects = await settleWithLimit(ids, MET_CONCURRENCY, (id) => fetchObject(fetchImpl, id), MET_DETAIL_DEADLINE_MS);
54
92
  const assets = objects.flatMap((r) => (r.status === "fulfilled" && isCc0(r.value) ? [toAsset(r.value)] : []));
55
93
  return { total: search.total, assets };
56
94
  }
@@ -57,11 +57,26 @@ export async function getOpenverse(fetchImpl, media, id) {
57
57
  if (!isCc0(item))
58
58
  return null;
59
59
  const asset = toAsset(media, item);
60
- return {
61
- ...asset,
62
- description: null,
63
- files: item.url
64
- ? [{ label: item.filetype ? `original (${item.filetype})` : "original", url: item.url, sizeBytes: item.filesize ?? null }]
65
- : [],
66
- };
60
+ return { ...asset, description: null, files: openverseFiles(item) };
61
+ }
62
+ /**
63
+ * Freesound items in Openverse point `url` at a lossy preview (cdn.freesound.org/previews/...).
64
+ * The uploaded original is only listed in `alt_files`, behind an OAuth API endpoint, so it is
65
+ * offered as the Freesound page, where a logged-in user can download it.
66
+ */
67
+ function openverseFiles(item) {
68
+ if (!item.url)
69
+ return [];
70
+ const isFreesoundPreview = /^https:\/\/cdn\.freesound\.org\/previews\//.test(item.url);
71
+ if (!isFreesoundPreview) {
72
+ return [{ label: item.filetype ? `original (${item.filetype})` : "original", url: item.url, sizeBytes: item.filesize ?? null }];
73
+ }
74
+ const ext = item.url.split(".").pop();
75
+ const preview = { label: `preview (${ext}, lossy)`, url: item.url, sizeBytes: null };
76
+ const originals = (item.alt_files ?? []).map((f) => ({
77
+ label: `original (${f.filetype ?? "file"}) — download on Freesound (login required)`,
78
+ url: item.foreign_landing_url,
79
+ sizeBytes: f.filesize ?? null,
80
+ }));
81
+ return [preview, ...originals];
67
82
  }
@@ -63,13 +63,24 @@ export async function searchPolyhaven(fetchImpl, kind, params) {
63
63
  .map((r) => toAsset(r.slug, index[r.slug]));
64
64
  return { total: search.total, assets };
65
65
  }
66
- /** Flattens the nested /files response into one row per downloadable file. */
66
+ /**
67
+ * Flattens the nested /files response into one row per downloadable file.
68
+ * A model file's `include` map (the glTF .bin, textures) stays on its row as
69
+ * `includes`: without them the main file does not open, and as separate rows
70
+ * they would push other formats past the reply's file cap.
71
+ */
67
72
  export function flattenFiles(node, path = []) {
68
73
  if (!node || typeof node !== "object")
69
74
  return [];
70
75
  const rec = node;
71
76
  if (typeof rec.url === "string") {
72
- return [{ label: path.join(" / "), url: rec.url, sizeBytes: typeof rec.size === "number" ? rec.size : null }];
77
+ const row = { label: path.join(" / "), url: rec.url, sizeBytes: typeof rec.size === "number" ? rec.size : null };
78
+ const include = rec.include && typeof rec.include === "object" ? Object.entries(rec.include) : [];
79
+ const includes = include.flatMap(([p, v]) => {
80
+ const f = v;
81
+ return f && typeof f.url === "string" ? [{ path: p, url: f.url, sizeBytes: typeof f.size === "number" ? f.size : null }] : [];
82
+ });
83
+ return [includes.length ? { ...row, includes } : row];
73
84
  }
74
85
  return Object.entries(rec).flatMap(([k, v]) => (k === "include" ? [] : flattenFiles(v, [...path, k])));
75
86
  }
package/dist/risk.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Warnings for items whose CC0 label was set by an uploader. A CC0 tag does not
3
+ * clear third-party rights: an uploader can tag a fan model of a game weapon or a
4
+ * cartoon character as CC0, yet the franchise owner still holds copyright and
5
+ * trademark in the design. These checks look only at the item's own title and
6
+ * tags, so they catch obvious cases and miss the rest; no flag does not mean safe.
7
+ *
8
+ * Studio (`library`) and museum (`institution`) declarations are not checked:
9
+ * the declarer made or holds the work.
10
+ */
11
+ /**
12
+ * Names of well-known commercial franchises, characters and brands, lowercased.
13
+ * Names that are also ordinary words or terms (halo, blizzard, fallout, marvel,
14
+ * joker, tesla, nike, half-life, ironman, minions) are left out: they flag too
15
+ * many unrelated photos.
16
+ * A name matches as whole words (multi-word names as a phrase); a trailing "*"
17
+ * also matches longer words, for names commonly misspelled or inflected
18
+ * ("frostmourn*" catches "Frostmourn" and "Frostmourne"). Multi-word names also
19
+ * match written as one word, as tags often are ("starwars", "darthvader").
20
+ */
21
+ const FRANCHISE_TERMS = [
22
+ // games and game characters
23
+ "pokemon", "pokémon", "pikachu", "nintendo", "mario", "luigi", "zelda", "hyrule", "kirby", "metroid", "donkey kong",
24
+ "sonic the hedgehog", "sega", "minecraft", "fortnite", "roblox", "among us", "overwatch", "warcraft",
25
+ "world of warcraft", "frostmourn*", "starcraft", "master chief", "call of duty",
26
+ "grand theft auto", "final fantasy", "kingdom hearts", "elden ring", "dark souls", "skyrim", "the witcher",
27
+ "cyberpunk 2077", "assassin's creed", "resident evil", "genshin", "league of legends", "valorant", "dota",
28
+ "counter-strike", "portal gun", "tetris", "pac-man", "street fighter", "mortal kombat",
29
+ "playstation", "xbox", "animal crossing", "splatoon", "undertale",
30
+ // film, TV, comics, toys
31
+ "star wars", "darth vader", "lightsaber", "stormtrooper", "clone trooper", "yoda", "jedi", "sith", "boba fett", "mandalor*",
32
+ "x-wing", "tie fighter", "death star", "millennium falcon", "star trek", "avengers",
33
+ "spider-man", "batman", "superman", "dc comics", "harry potter", "hogwarts",
34
+ "lord of the rings", "gandalf", "hobbit", "game of thrones", "disney", "mickey mouse", "frozen elsa", "pixar",
35
+ "toy story", "shrek", "simpsons", "spongebob", "transformers", "optimus prime", "lego", "barbie",
36
+ "hello kitty", "studio ghibli", "totoro", "naruto", "dragon ball", "goku", "one piece", "sailor moon",
37
+ "evangelion", "gundam", "doctor who", "tardis", "jurassic park", "godzilla", "ghostbusters", "james bond",
38
+ "pirates of the caribbean", "indiana jones", "teenage mutant ninja turtles",
39
+ // brands and logos
40
+ "coca-cola", "pepsi", "mcdonald's", "adidas", "apple logo", "ferrari", "lamborghini",
41
+ "porsche", "bmw", "mercedes-benz", "rolex", "louis vuitton", "gucci", "red bull",
42
+ ];
43
+ /** Words in a title or tags that say the item copies someone else's work. */
44
+ const DERIVATIVE_TERMS = ["fan art", "fan made", "ripped", "sprite rip", "replica", "inspired by"];
45
+ /** Lowercase words separated by single spaces; hyphens count as spaces ("fan-art" = "fan art"). */
46
+ function normalize(text) {
47
+ return ` ${text.toLowerCase().replace(/[^\p{L}\p{N}'*]+/gu, " ").trim()} `;
48
+ }
49
+ function matches(haystack, term) {
50
+ if (term.endsWith("*"))
51
+ return new RegExp(`(^|\\s)${escape(term.slice(0, -1))}`, "u").test(haystack);
52
+ const t = normalize(term).trim();
53
+ if (haystack.includes(` ${t} `))
54
+ return true;
55
+ const joined = t.replace(/ /g, "");
56
+ return joined !== t && haystack.includes(` ${joined} `);
57
+ }
58
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59
+ /** Flags for one asset; empty when nothing matched or the declarer is not an uploader. */
60
+ export function riskFlags(asset) {
61
+ if (asset.licenseEvidence.declaredBy !== "uploader")
62
+ return [];
63
+ const text = normalize([asset.title, ...asset.tags].join(" "));
64
+ const flags = [];
65
+ const franchise = FRANCHISE_TERMS.filter((t) => matches(text, t));
66
+ if (franchise.length)
67
+ flags.push(`franchise-name: ${franchise.map((t) => t.replace(/\*$/, "")).join(", ")}`);
68
+ const derivative = DERIVATIVE_TERMS.filter((t) => matches(text, t));
69
+ if (derivative.length)
70
+ flags.push(`derivative-wording: ${derivative.join(", ")}`);
71
+ return flags;
72
+ }
73
+ /** Returns the asset with `riskFlags` set when any check matched, otherwise unchanged. */
74
+ export function withRiskFlags(asset) {
75
+ const flags = riskFlags(asset);
76
+ return flags.length ? { ...asset, riskFlags: flags } : asset;
77
+ }
package/dist/search.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * Provider fan-out and id routing. Has no Node-only imports, so the same code
3
3
  * runs in the MCP server and in the browser gallery (web/).
4
4
  */
5
+ import { withRiskFlags } from "./risk.js";
5
6
  import { getOpenverse, searchOpenverse } from "./providers/openverse.js";
6
7
  import { getPolyhaven, searchPolyhaven } from "./providers/polyhaven.js";
7
8
  import { getAmbientcg, searchAmbientcg } from "./providers/ambientcg.js";
@@ -76,20 +77,42 @@ export async function search(fetchImpl, query, kind, limit, page, options = {})
76
77
  const id = j.name.split(":")[0];
77
78
  return !skip.has(id) && (!only || only.has(id));
78
79
  });
79
- const settled = await Promise.allSettled(run.map((j) => j.run()));
80
+ // Slots keep provider order, so the interleave is the same however the calls finish.
80
81
  const totals = {};
81
- const errors = [];
82
- const lists = [];
83
- settled.forEach((s, i) => {
84
- if (s.status === "fulfilled") {
85
- totals[run[i].name] = s.value.total;
86
- lists.push(s.value.assets);
82
+ const errorSlots = new Array(run.length);
83
+ const listSlots = new Array(run.length);
84
+ const done = new Array(run.length).fill(false);
85
+ const snapshot = () => {
86
+ const lists = listSlots.filter((l) => !!l);
87
+ const errors = errorSlots.filter((e) => !!e);
88
+ const waiting = run.filter((_, i) => !done[i]).map((j) => j.name);
89
+ const assets = rank(query, interleave(lists)).slice(0, limit).map(withRiskFlags);
90
+ return { query, kind, page, assets, totals: { ...totals }, errors, pending: waiting };
91
+ };
92
+ let pending = run.length;
93
+ const settled = Promise.all(run.map(async (j, i) => {
94
+ try {
95
+ const r = await j.run();
96
+ totals[j.name] = r.total;
97
+ listSlots[i] = r.assets;
87
98
  }
88
- else {
89
- errors.push(`${run[i].name}: ${s.reason instanceof Error ? s.reason.message : String(s.reason)}`);
99
+ catch (e) {
100
+ errorSlots[i] = `${j.name}: ${e instanceof Error ? e.message : String(e)}`;
90
101
  }
91
- });
92
- return { query, kind, page, assets: rank(query, interleave(lists)).slice(0, limit), totals, errors };
102
+ done[i] = true;
103
+ pending--;
104
+ if (pending > 0)
105
+ options.onProgress?.(snapshot(), pending);
106
+ }));
107
+ if (options.deadlineMs === undefined) {
108
+ await settled;
109
+ }
110
+ else {
111
+ let timer;
112
+ await Promise.race([settled, new Promise((r) => (timer = setTimeout(r, options.deadlineMs)))]);
113
+ clearTimeout(timer);
114
+ }
115
+ return snapshot();
93
116
  }
94
117
  /** Words of two or more letters or digits, lowercased; works for any script. */
95
118
  function words(text) {
@@ -146,6 +169,10 @@ export function interleave(lists) {
146
169
  * `github:<owner>/<repo>`, `huggingface:<owner>/<dataset>`, `blenderkit:<uuid>`.
147
170
  */
148
171
  export async function getAsset(fetchImpl, id) {
172
+ const asset = await getAssetUnflagged(fetchImpl, id);
173
+ return asset && withRiskFlags(asset);
174
+ }
175
+ async function getAssetUnflagged(fetchImpl, id) {
149
176
  const parts = id.split(":");
150
177
  const [provider, a, b] = parts;
151
178
  if (parts.length === 3 && provider === "openverse" && (a === "image" || a === "audio") && b)
package/dist/server.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
- import { defaultFetch } from "./http.js";
3
+ import { DownloadRequestError, MAX_FILES_PER_CALL, RECEIPT_NAME, downloadAsset } from "./download.js";
4
+ import { defaultDownload, defaultFetch } from "./http.js";
4
5
  import { getAsset, loadCatalog, search } from "./library.js";
5
6
  import { ASSET_KINDS, CATALOG_KINDS, PROVIDER_IDS } from "./types.js";
7
+ /** One slow source (The Met can take 30 s) must not hold every reply; it is reported in `pending`. */
8
+ const SEARCH_DEADLINE_MS = 10_000;
6
9
  /** Poly Haven textures can list 100+ map/resolution/format files; keep replies readable. */
7
10
  const MAX_FILES_IN_REPLY = 60;
8
11
  const KIND_HELP = "Asset type. image: Openverse, Wikimedia Commons, Internet Archive, WordPress Photo Directory, iNaturalist and GBIF " +
@@ -40,11 +43,21 @@ const assetShape = {
40
43
  origin: z.string().describe("Site the item originally came from (e.g. flickr, freesound, metmuseum.org)"),
41
44
  licenseEvidence: licenseEvidenceSchema,
42
45
  servedBy: z.string().describe("Credit line required by the serving API's terms; show it next to results"),
46
+ riskFlags: z
47
+ .array(z.string())
48
+ .optional()
49
+ .describe("Present only on uploader-declared items whose title or tags name a known franchise, character or brand, or say the work is fan-made or copied " +
50
+ "(e.g. 'franchise-name: star wars'). CC0 from an uploader does not clear the franchise owner's rights: tell the user before suggesting it. " +
51
+ "Absence does not mean the item is safe"),
43
52
  };
44
53
  const fileSchema = z.object({
45
54
  label: z.string().describe("Variant, e.g. '2K-JPG (zip)', 'hdri / 4k / exr', 'primary'"),
46
55
  url: z.string().describe("Direct download URL (Sketchfab: model page, login required)"),
47
56
  sizeBytes: z.number().nullable().describe("File size in bytes when the source reports it"),
57
+ includes: z
58
+ .array(z.object({ path: z.string(), url: z.string(), sizeBytes: z.number().nullable() }))
59
+ .optional()
60
+ .describe("Companion files (a glTF's .bin and textures). Save each at `path` relative to the main file, or the main file will not open"),
48
61
  });
49
62
  const nameReason = z.object({
50
63
  name: z.string(),
@@ -58,6 +71,9 @@ const searchOutput = {
58
71
  assets: z.array(z.object(assetShape)).describe("CC0 results, at most `limit`; may be fewer when sources drop non-CC0 items"),
59
72
  totals: z.record(z.string(), z.number()).describe("Upstream match count per source job (before CC0 re-checks); useful to decide whether to page"),
60
73
  errors: z.array(z.string()).describe("Sources that failed this time, e.g. 'met: The Met returned HTTP 503'; other sources still returned results"),
74
+ pending: z
75
+ .array(z.string())
76
+ .describe(`Sources that had not answered within ${SEARCH_DEADLINE_MS / 1000} s and were left out; search again (or narrow with providers) to include them`),
61
77
  };
62
78
  const getOutput = {
63
79
  ...assetShape,
@@ -87,17 +103,34 @@ const result = (value) => ({
87
103
  content: [{ type: "text", text: JSON.stringify(value, null, 2) }],
88
104
  });
89
105
  const fail = (message) => ({ content: [{ type: "text", text: message }], isError: true });
90
- export function createServer(fetchImpl = defaultFetch) {
91
- const server = new McpServer({ name: "cc0-library", version: "0.2.12" });
106
+ const savedFileSchema = z.object({
107
+ label: z.string().describe("File label from get_asset; companions read '<main label> + <path>'"),
108
+ path: z.string().describe("Path relative to `folder`"),
109
+ url: z.string().describe("Where it was downloaded from"),
110
+ bytes: z.number(),
111
+ sha256: z.string(),
112
+ });
113
+ const downloadOutput = {
114
+ folder: z.string().describe("Absolute path of the folder created for this asset"),
115
+ saved: z.array(savedFileSchema).describe("Files written, including each model's companion files at their relative paths"),
116
+ skipped: z
117
+ .array(z.object({ label: z.string(), url: z.string(), reason: z.string() }))
118
+ .describe("Files not saved and why, e.g. a page that needs the user's login; tell the user and give them landingUrl"),
119
+ receipt: z.string().describe(`Absolute path of ${RECEIPT_NAME}: id, title, creator, source URLs, license evidence, riskFlags and download time`),
120
+ };
121
+ export function createServer(fetchImpl = defaultFetch, downloadImpl = defaultDownload) {
122
+ const server = new McpServer({ name: "cc0-library", version: "0.2.13" });
92
123
  server.registerTool("search_assets", {
93
124
  title: "Search CC0 assets across 17 sources",
94
125
  description: "Find CC0 1.0 (public-domain dedication) images, audio, video, HDRIs, textures, 3D models and museum artworks by keyword, " +
95
126
  "returning only items whose CC0 status was checked. " +
96
127
  "Use it first to discover candidates; then call get_asset for download files and a fresh license re-check. " +
97
128
  "Use list_sources instead to answer which sites are CC0. Do not use it for CC BY, CC BY-SA or other 'free' licenses: they are filtered out. " +
98
- "Behavior: read-only, no API key, live HTTPS calls to each source (usually 2-10 s). A failing source is listed in `errors` while the others still return. " +
129
+ `Behavior: read-only, no API key, live HTTPS calls to each source; replies within ${SEARCH_DEADLINE_MS / 1000} s. ` +
130
+ "A failing source is listed in `errors` and a source still running at the deadline in `pending`, while the others still return. " +
99
131
  "Results from uploader-driven sites (Openverse, Commons, Internet Archive, Sketchfab, WordPress Photo Directory, iNaturalist, PhyloPic, Zenodo, BlenderKit, GitHub, Hugging Face) carry licenseEvidence.declaredBy='uploader': " +
100
- "tell the user to confirm the uploader owns the work. Show each item's servedBy credit with the results.",
132
+ "tell the user to confirm the uploader owns the work; items with riskFlags name a franchise or brand and need that warning most. " +
133
+ "Show each item's servedBy credit with the results.",
101
134
  inputSchema: {
102
135
  query: z.string().min(1).max(200).describe("Keywords in any language, matched against titles and tags, e.g. 'rainy street' or 'brick wall'"),
103
136
  kind: z.enum([...ASSET_KINDS, "any"]).default("any").describe(KIND_HELP),
@@ -126,7 +159,7 @@ export function createServer(fetchImpl = defaultFetch) {
126
159
  },
127
160
  outputSchema: searchOutput,
128
161
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
129
- }, async ({ query, kind, limit, page, providers }) => result(await search(fetchImpl, query, kind, limit, page, { providers })));
162
+ }, async ({ query, kind, limit, page, providers }) => result(await search(fetchImpl, query, kind, limit, page, { providers, deadlineMs: SEARCH_DEADLINE_MS })));
130
163
  server.registerTool("get_asset", {
131
164
  title: "Get one CC0 asset with download files",
132
165
  description: "Fetch one asset's details and download files by an id from search_assets, re-checking at the source that it is still CC0. " +
@@ -157,6 +190,46 @@ export function createServer(fetchImpl = defaultFetch) {
157
190
  ...(truncated && { filesNote: `${asset.files.length - MAX_FILES_IN_REPLY} more files omitted; see landingUrl.` }),
158
191
  });
159
192
  });
193
+ server.registerTool("download_asset", {
194
+ title: "Download a CC0 asset with a license receipt",
195
+ description: "Save chosen files of one asset to a local folder, re-checking at the source that it is still CC0 first. " +
196
+ "Creates <dir>/<asset id>/, saves each file there with its companions (a glTF's .bin and textures) at the relative paths the main file expects, " +
197
+ `and writes ${RECEIPT_NAME} recording the source, creator, license evidence, riskFlags and download time, so the project keeps proof of where the asset came from. ` +
198
+ "Use it after search_assets (and get_asset when the asset has several files, to read their labels) when the user wants the asset in their project; " +
199
+ "use get_asset instead when they only want links. " +
200
+ "Pages that need the user's login (Sketchfab, BlenderKit, Freesound originals) are not downloaded and come back in `skipped`. " +
201
+ "Zip packs (ambientCG) are saved as-is, not extracted. " +
202
+ "Behavior: writes files under `dir` only, overwriting same-named files from an earlier download of the same asset; live HTTPS downloads, up to 1 GB per file.",
203
+ inputSchema: {
204
+ id: z.string().min(1).max(120).describe("Asset id exactly as returned by search_assets"),
205
+ dir: z
206
+ .string()
207
+ .min(1)
208
+ .max(1024)
209
+ .describe("Folder to save into, normally inside the user's project (e.g. 'assets/cc0'). A subfolder named after the asset id is created. Relative paths resolve against the server's working directory"),
210
+ files: z
211
+ .array(z.string().min(1).max(200))
212
+ .min(1)
213
+ .max(MAX_FILES_PER_CALL)
214
+ .optional()
215
+ .describe("Exact file labels from get_asset, e.g. ['gltf / 1k / gltf'] or ['1K-JPG (zip)']. Leave out only when the asset has a single file; " +
216
+ "otherwise the call fails and lists the labels"),
217
+ },
218
+ outputSchema: downloadOutput,
219
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
220
+ }, async ({ id, dir, files }) => {
221
+ const asset = await getAsset(fetchImpl, id);
222
+ if (!asset)
223
+ return fail(`No CC0 asset found for id "${id}". The id may be malformed, removed upstream, or no longer CC0.`);
224
+ try {
225
+ return result(await downloadAsset(downloadImpl, asset, dir, files));
226
+ }
227
+ catch (e) {
228
+ if (e instanceof DownloadRequestError)
229
+ return fail(e.message);
230
+ throw e;
231
+ }
232
+ });
160
233
  server.registerTool("list_sources", {
161
234
  title: "List verified CC0 source sites",
162
235
  description: "List the curated catalog of CC0 asset sites, each with its license page, scope and dated evidence, " +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc0-library-mcp",
3
- "version": "0.2.12",
3
+ "version": "0.2.13",
4
4
  "mcpName": "io.github.sanghyoLe/cc0-library",
5
5
  "description": "MCP server and web gallery for CC0-only assets (images, audio, video, HDRIs, textures, 3D models, museum art) from 8 sources, with license evidence per result.",
6
6
  "license": "MIT",