@muqian/xiangsu-mcp-plus 0.6.1 → 0.7.0

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.
@@ -65,7 +65,7 @@ const methods = {
65
65
  return raw.panelKey === SQUARE_PANEL ? this.squareKind(raw) : 'package';
66
66
  },
67
67
 
68
- async squareList({ category_id, cursor = 0, count = 30 }) {
68
+ async squareList({ category_id, cursor = 0, count = 20 }) {
69
69
  this.ensureCompatible('square');
70
70
  const catBody = await this.mod(M.aiCategory).getAIAssetCategory({ cursor: 0, count: 50, panelKey: SQUARE_PANEL });
71
71
  if (!catBody || catBody.statusCode !== 0) throw Error(`GET_CATEGORY_FAILED: statusCode=${catBody && catBody.statusCode} message=${(catBody && catBody.message) || ''}`);
@@ -108,7 +108,7 @@ const methods = {
108
108
  const uris = squareParts(item).ai.resPictureUri;
109
109
  const res = await this.mod(M.aiEffectApi).getDYEHFileUrls({ uriList: uris });
110
110
  if (!res || res.code !== 0) throw Error(`GET_IMAGE_URLS_FAILED: code=${res && res.code} message=${(res && res.message) || ''}`);
111
- return uris.map((uri, i) => ({ image_index: i, url: (res.data && res.data[uri] && res.data[uri].url) || null }));
111
+ return uris.map((uri, i) => ({ image_index: i, image_url: (res.data && res.data[uri] && res.data[uri].url) || null }));
112
112
  },
113
113
 
114
114
  // Applies a square card through the asset library instance, then waits for the objects its callbacks add.
@@ -84,8 +84,8 @@ const methods = {
84
84
  return { categories, sorts: Object.keys(SORT) };
85
85
  },
86
86
 
87
- async worksCategory(category_id) {
88
- const { categories } = await this.worksNav();
87
+ async worksCategory(category_id, nav) {
88
+ const { categories } = nav || (await this.worksNav());
89
89
  if (category_id === undefined) return categories[0];
90
90
  const hit = categories.find((c) => c.id === String(category_id));
91
91
  if (!hit) throw Error(`INVALID_CATEGORY_ID: ${category_id}; valid: ${categories.map((c) => `${c.id}(${c.name})`).join(', ')}`);
@@ -101,16 +101,17 @@ const methods = {
101
101
  return { items: raw.map((t) => slimWork(t, transform)), raw, next, has_more: !!next };
102
102
  },
103
103
 
104
- async worksList({ category_id, cursor, count = 30, sort } = {}) {
104
+ async worksList({ category_id, cursor, count = 20, sort } = {}) {
105
105
  const ranker = sortValue(sort);
106
106
  const state = decodeCursor(cursor);
107
- const category = await this.worksCategory(category_id);
107
+ const nav = await this.worksNav();
108
+ const category = await this.worksCategory(category_id, nav);
108
109
  const data = body(
109
110
  await this.mod(M.worksCategory).apiTemplatesCategory({ ...state, count, panelKey: PANEL_KEY, categoryId: category.id, ranker, getCollectStatus: true }),
110
111
  'GET_WORKS_LIST',
111
112
  );
112
113
  const { next, ...page } = this.worksPage(data.dataInfos || {});
113
- return { category, ...page, next_cursor: encodeCursor(next) };
114
+ return { category, categories: nav.categories, ...page, next_cursor: encodeCursor(next) };
114
115
  },
115
116
 
116
117
  // Same request the homepage search box sends, scoped to one category; `state` is where the page starts.
@@ -158,7 +159,7 @@ const methods = {
158
159
  // Matched on the project name, like the homepage search box's default 特效名称 option. Without a
159
160
  // category every category is searched; works are merged in the order 推荐 returns them, then the
160
161
  // ones only other categories have, category by category (sort applies within each category).
161
- async worksSearch({ query, queries, category_id, offset = 0, count = 30, sort } = {}) {
162
+ async worksSearch({ query, queries, category_id, offset = 0, count = 20, sort } = {}) {
162
163
  if (query !== undefined && queries !== undefined) throw Error('INVALID_QUERY: pass query or queries, not both');
163
164
  const list = queries !== undefined ? queries : query !== undefined ? [query] : [];
164
165
  if (!Array.isArray(list) || !list.length || list.length > MAX_TERMS) throw Error(`INVALID_QUERY: pass query, or 1-${MAX_TERMS} queries`);
@@ -280,7 +281,6 @@ const methods = {
280
281
  };
281
282
 
282
283
  const METHODS = {
283
- works_nav: 'worksNav',
284
284
  works_list: 'worksList',
285
285
  works_search: 'worksSearch',
286
286
  works_by_effect: 'worksByEffect',
@@ -42,9 +42,12 @@ module.exports = {
42
42
  slim: assets.slim,
43
43
  REQUIRED: assets.REQUIRED,
44
44
  MENU_DENY: menu.MENU_DENY,
45
+ MAX_MENU_PREVIEW: menu.MAX_MENU_PREVIEW,
45
46
  WORK_SORTS: works.SORT,
46
47
  MAX_WORK_EFFECTS: works.MAX_EFFECTS,
47
- PICK_KINDS: community.PICK_KINDS,
48
+ INNOVATION_KINDS: community.INNOVATION_KINDS,
48
49
  SUBJECT_KINDS: community.SUBJECT_KINDS,
50
+ RANK_TYPES: community.RANK_TYPES,
51
+ RANK_FILTERS: community.RANK_FILTERS,
49
52
  CONFIG_PATH: dev.CONFIG_PATH,
50
53
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@muqian/xiangsu-mcp-plus",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "mcpName": "io.github.Muqian-Sun/xiangsu-mcp-plus",
5
5
  "type": "module",
6
6
  "description": "Unofficial MCP server for Douyin AR (像塑) on macOS: proxies the official MCP and adds the official asset library, add-object menu, AI combine workflows, delivery (icon, effect checks, submit window, phone preview), Douyin music, inspirations, tasks and rank boards, review status, FaceWarpX intensity and project windows. For learning and personal creation only; do not use it to copy other creators' works.",
package/src/bridge.mjs CHANGED
@@ -54,7 +54,27 @@ async function post(instance, method, params, timeoutMs) {
54
54
  return body.value;
55
55
  }
56
56
 
57
- // Selects the plugin instance by pid, or by the project path open in that window.
57
+ // statusMs is picked: a window that does not answer its status in this long is passed over.
58
+ export const BRIDGE_TIMING = { statusMs: 5000 };
59
+ // The window each project (real path) was last found in, asked first next time. Every window is asked only
60
+ // when that one no longer shows the project, so a hung or closing window costs nothing until then.
61
+ const lastSeen = new Map();
62
+
63
+ const realPath = (p) => {
64
+ try {
65
+ return fs.realpathSync(p);
66
+ } catch {
67
+ return null;
68
+ }
69
+ };
70
+
71
+ async function projectOf(instance) {
72
+ const st = await post(instance, 'status', {}, BRIDGE_TIMING.statusMs);
73
+ return st.projectPath ? realPath(st.projectPath) : null;
74
+ }
75
+
76
+ // Selects the plugin instance by pid, or by the project path open in that window. Windows are asked
77
+ // together, and one that does not answer (hung, closing) does not keep the others from being found.
58
78
  export async function resolveInstance({ pid, projectPath } = {}) {
59
79
  const live = listInstances();
60
80
  if (pid) {
@@ -67,13 +87,16 @@ export async function resolveInstance({ pid, projectPath } = {}) {
67
87
  throw Error(`AMBIGUOUS_INSTANCE: ${live.length} plugin instances; pass project_path`);
68
88
  }
69
89
  const want = fs.realpathSync(projectPath);
70
- const matches = [];
71
- for (const s of live) {
72
- const st = await post(s, 'status', {}, 5000);
73
- if (st.projectPath && fs.realpathSync(st.projectPath) === want) matches.push(s);
90
+ const known = live.find((s) => s.pid === lastSeen.get(want));
91
+ if (known && (await projectOf(known).catch(() => null)) === want) return known;
92
+ const answers = await Promise.allSettled(live.map(projectOf));
93
+ const matches = live.filter((s, i) => answers[i].status === 'fulfilled' && answers[i].value === want);
94
+ if (matches.length === 1) {
95
+ lastSeen.set(want, matches[0].pid);
96
+ return matches[0];
74
97
  }
75
- if (matches.length !== 1) throw Error(`NO_UNIQUE_PLUGIN_INSTANCE for ${projectPath}: ${matches.length} matches`);
76
- return matches[0];
98
+ const silent = live.flatMap((s, i) => (answers[i].status === 'rejected' ? [`${s.pid} (${answers[i].reason.message})`] : []));
99
+ throw Error(`NO_UNIQUE_PLUGIN_INSTANCE for ${projectPath}: ${matches.length} matches${silent.length ? `; windows that did not answer: ${silent.join(', ')}` : ''}`);
77
100
  }
78
101
 
79
102
  export async function callPlugin(method, params = {}, { pid, projectPath, timeoutMs = 120000 } = {}) {
@@ -0,0 +1,32 @@
1
+ // One JSON line per tool call (name, duration, error) and per crash of this server, kept in the state
2
+ // directory so a failure an agent only paraphrased can be looked up afterwards.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ // Picked: a few days of heavy use; the older half moves to server.log.1 when the file grows past it.
8
+ const MAX_BYTES = 5 * 1024 * 1024;
9
+ // Picked: long enough for any error message the tools produce, short enough to keep lines readable.
10
+ const MAX_TEXT = 500;
11
+
12
+ export class CallLog {
13
+ constructor({ stateDir = process.env.XIANGSU_MCP_EXT_STATE || path.join(os.homedir(), '.xiangsu-mcp-ext'), now = () => new Date() } = {}) {
14
+ this.file = path.join(stateDir, 'logs', 'server.log');
15
+ this.now = now;
16
+ }
17
+
18
+ write(entry) {
19
+ try {
20
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
21
+ if (fs.existsSync(this.file) && fs.statSync(this.file).size > MAX_BYTES) fs.renameSync(this.file, `${this.file}.1`);
22
+ fs.appendFileSync(this.file, `${JSON.stringify({ at: this.now().toISOString(), pid: process.pid, ...entry })}\n`);
23
+ } catch (_) {
24
+ // Logging must never fail a tool call.
25
+ }
26
+ }
27
+
28
+ call({ tool, ms, result, error, progress }) {
29
+ const text = error ?? (result && result.isError ? result.content?.[0]?.text : undefined);
30
+ this.write({ tool, ms, ok: text === undefined, ...(text === undefined ? {} : { error: String(text).slice(0, MAX_TEXT) }), progress });
31
+ }
32
+ }
@@ -0,0 +1,122 @@
1
+ // How answers carry bulk data. Lists hand out short refs instead of media addresses (a signed CDN
2
+ // address runs to hundreds of characters and most of a list item, measured), which image_view turns
3
+ // back into the address; an answer too long to read in one go is written to a file and replaced by
4
+ // an outline of it.
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+
10
+ // Picked, not measured: far more refs than a session's lists hand out (a page of 20 holds about 40);
11
+ // past it the least recently handed out are forgotten, and image_view says to list again.
12
+ const MAX_REFS = 20000;
13
+ const PREFIX = { image: 'img', video: 'video', audio: 'audio' };
14
+ export const REF_PATTERN = /^(img|video|audio):\d+$/;
15
+
16
+ export class MediaRefs {
17
+ constructor({ max = MAX_REFS } = {}) {
18
+ this.max = max;
19
+ this.byKey = new Map();
20
+ this.byRef = new Map();
21
+ this.next = 1;
22
+ }
23
+
24
+ add(url, kind) {
25
+ const key = `${kind} ${url}`;
26
+ let ref = this.byKey.get(key);
27
+ if (ref) this.byRef.delete(ref);
28
+ else ref = `${PREFIX[kind]}:${this.next++}`;
29
+ this.byKey.set(key, ref);
30
+ this.byRef.set(ref, { url, kind });
31
+ while (this.byRef.size > this.max) {
32
+ const [old, hit] = this.byRef.entries().next().value;
33
+ this.byRef.delete(old);
34
+ this.byKey.delete(`${hit.kind} ${hit.url}`);
35
+ }
36
+ return ref;
37
+ }
38
+
39
+ get(ref) {
40
+ return this.byRef.get(ref) ?? null;
41
+ }
42
+ }
43
+
44
+ // Media fields are named by what they hold: video_url / videos are videos, preview_url and audio_url
45
+ // audio, every other *_url and images pictures. Other links (review and task page links) are named
46
+ // url or link and stay as they are.
47
+ const kindOf = (key) => (key.startsWith('video') ? 'video' : key.startsWith('preview') || key.startsWith('audio') ? 'audio' : 'image');
48
+ const isAddress = (v) => typeof v === 'string' && /^https?:\/\//.test(v);
49
+
50
+ export function withRefs(value, refs) {
51
+ if (Array.isArray(value)) return value.map((v) => withRefs(v, refs));
52
+ if (!value || typeof value !== 'object') return value;
53
+ const out = {};
54
+ for (const [key, v] of Object.entries(value)) {
55
+ if (key.endsWith('_url') && (typeof v === 'string' || v === null)) {
56
+ out[`${key.slice(0, -4)}_ref`] = isAddress(v) ? refs.add(v, kindOf(key)) : null;
57
+ } else if ((key === 'images' || key === 'videos') && Array.isArray(v) && v.every((x) => typeof x === 'string')) {
58
+ out[`${key.slice(0, -1)}_refs`] = v.filter(isAddress).map((u) => refs.add(u, kindOf(key)));
59
+ } else {
60
+ out[key] = withRefs(v, refs);
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+
66
+ // Derived: task_detail answered 48K characters (measured), most of it media addresses and page
67
+ // markup, and agents read such answers in pieces or not at all; picked a round number below it.
68
+ export const SPILL_CHARS = 30000;
69
+ // Picked: long enough to read the file within the session that asked for it.
70
+ const SPILL_TTL_MS = 24 * 60 * 60 * 1000;
71
+ // Picked: enough of a text answer (scene trees) to see what it is.
72
+ const TEXT_HEAD = 2000;
73
+
74
+ function outline(value) {
75
+ if (Array.isArray(value)) {
76
+ const first = value.find((v) => v && typeof v === 'object' && !Array.isArray(v));
77
+ return first ? { items: value.length, item_keys: Object.keys(first) } : { items: value.length };
78
+ }
79
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, outline(v)]));
80
+ if (typeof value === 'string' && value.length > 200) return `${value.slice(0, 200)}…(共 ${value.length} 字)`;
81
+ return value;
82
+ }
83
+
84
+ export class Spill {
85
+ constructor({ stateDir = process.env.XIANGSU_MCP_EXT_STATE || path.join(os.homedir(), '.xiangsu-mcp-ext'), now = Date.now, limit = SPILL_CHARS } = {}) {
86
+ this.dir = path.join(stateDir, 'outputs');
87
+ this.now = now;
88
+ this.limit = limit;
89
+ }
90
+
91
+ prune() {
92
+ if (!fs.existsSync(this.dir)) return;
93
+ for (const name of fs.readdirSync(this.dir)) {
94
+ const file = path.join(this.dir, name);
95
+ if (this.now() - fs.statSync(file).mtimeMs > SPILL_TTL_MS) fs.rmSync(file, { force: true });
96
+ }
97
+ }
98
+
99
+ // A text-only answer over the limit goes to a file; errors and answers with images pass unchanged.
100
+ apply(tool, result) {
101
+ if (!result || result.isError || !result.content.every((c) => c.type === 'text')) return result;
102
+ const body = result.content.map((c) => c.text).join('\n');
103
+ if (body.length <= this.limit) return result;
104
+ this.prune();
105
+ let parsed;
106
+ try {
107
+ parsed = JSON.parse(body);
108
+ } catch (_) {
109
+ parsed = undefined;
110
+ }
111
+ fs.mkdirSync(this.dir, { recursive: true });
112
+ const file = path.join(this.dir, `${tool}-${new Date(this.now()).toISOString().replace(/[:.]/g, '-')}-${crypto.randomBytes(3).toString('hex')}.${parsed === undefined ? 'txt' : 'json'}`);
113
+ fs.writeFileSync(file, body);
114
+ const summary = {
115
+ spilled_to: file,
116
+ chars: body.length,
117
+ note: `回答有 ${body.length} 字,超过 ${this.limit} 字,全文写进了 spilled_to(24 小时后删除):用读文件的工具按需读取,或用分页参数分几次取`,
118
+ ...(parsed === undefined ? { head: body.slice(0, TEXT_HEAD) } : { outline: outline(parsed) }),
119
+ };
120
+ return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] };
121
+ }
122
+ }