dsh-lovart-mcp 0.13.1 → 0.14.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.
package/README.md CHANGED
@@ -26,6 +26,7 @@ dsh plugin install dsh-lovart-mcp
26
26
  | 想做的事 | 工具 |
27
27
  |---|---|
28
28
  | 生成图片或视频 | `lovart_generate` |
29
+ | 取回产物(图片 / 视频 URL) | `lovart_task` |
29
30
  | 先看会用多少积分 | `lovart_quote` |
30
31
  | 查支持的模型 | `lovart_catalog` |
31
32
  | 改图、放大、抠图、分层、上传、查任务、管项目 | `lovart_tool` |
@@ -39,6 +40,23 @@ dsh plugin install dsh-lovart-mcp
39
40
 
40
41
  提交生成前会先给出积分报价,确认后才执行。
41
42
 
43
+ ## 生成模式
44
+
45
+ `lovart_generate` 会自己判断模式,返回里的 `mode` 会告诉你用的是哪一种:
46
+
47
+ | 模式 | 怎么触发 | 说明 |
48
+ | --- | --- | --- |
49
+ | 文生图 | 只给 prompt | 默认 1K Relax 模型,通常 0 积分 |
50
+ | 参考图生图 | `ref_images` | 传 `count` 可以一次出多张 |
51
+ | 文生视频 | prompt + `duration` | 视频模型多为会员专属,先用 `lovart_quote` 看积分 |
52
+ | 首帧生视频 | `first_frame` | 首帧用 Lovart 托管的 URL |
53
+ | 首尾帧生视频 | `first_frame` + `last_frame` | 只在支持首尾帧的模型上有效 |
54
+ | 参考图 / 参考视频生视频 | `ref_images` / `ref_video` | 参考视频用于跟随运动 |
55
+
56
+ **参考图必须由 Lovart 托管。** 本地截图、关键帧先 `lovart_tool(tool:"upload_asset")` 上传,拿到 URL 再传进来;直接传外部链接会被网关以 `InvalidParameter.FormatUnsupported` 拒绝。插件会对非 lovart.ai 的链接给出提示。
57
+
58
+ 生成是异步的:`lovart_generate` 只负责提交,返回 `task_ids`。要产物就再调 `lovart_task(task_ids: "...", wait: "true")`,它会轮询到完成,并把最终的图片或视频 URL 直接给你。传 `project_id` 可以把结果放进已有项目。
59
+
42
60
  ## 模型与能力
43
61
 
44
62
  面板底部有一块「模型与能力」:能力按生成、编辑、素材、项目、任务、模型目录、账户、评估分组,模型按厂商(openai、vertex、seedance……)分组。
package/client.js CHANGED
@@ -447,6 +447,22 @@ window.__ModuleLoader__.load({
447
447
  if (board === null) {
448
448
  return h('div', { style: { fontSize: '12px', opacity: 0.6 } }, error || '模型与能力加载中…')
449
449
  }
450
+ if (!board || !Array.isArray(board.groups)) {
451
+ return h('div', {
452
+ style: {
453
+ display: 'flex',
454
+ flexDirection: 'column',
455
+ gap: '4px',
456
+ border: '1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,.3))',
457
+ borderRadius: '10px',
458
+ padding: '10px 12px',
459
+ },
460
+ },
461
+ h('div', { style: { fontSize: '13px', fontWeight: 600 } }, '模型与能力'),
462
+ note(error || board.error || '开关看板没拿到数据,刷新页面再试;账号卡片不受影响。', 'danger'),
463
+ )
464
+ }
465
+ const totals = board.totals || { tools: 0, models: 0, disabledItems: 0, disabledGroups: 0 }
450
466
  const chip = (item) => h('button', {
451
467
  key: `${item.kind}:${item.id}`,
452
468
  type: 'button',
@@ -510,8 +526,8 @@ window.__ModuleLoader__.load({
510
526
  '点名字可单独开关,点「关闭整组」可一次关掉一组。关闭后对应的 MCP 工具会从 DSH 里消失,模型也不能被用于生成。'),
511
527
  error ? note(error, 'danger') : null,
512
528
  h('div', { style: { display: 'flex', gap: '16px', flexWrap: 'wrap', fontSize: '11px', opacity: 0.6 } },
513
- h('span', null, `能力 ${board.totals.tools} 项 · 已关 ${board.totals.disabledItems}`),
514
- h('span', null, `模型 ${board.totals.models} 项 · 组 ${board.totals.disabledGroups}`),
529
+ h('span', null, `能力 ${totals.tools} 项 · 已关 ${totals.disabledItems}`),
530
+ h('span', null, `模型 ${totals.models} 项 · 组 ${totals.disabledGroups}`),
515
531
  ),
516
532
  h('div', { style: { fontSize: '12px', fontWeight: 600, marginTop: '4px' } }, '能力'),
517
533
  toolGroups.map(groupRow),
package/lib/index.js CHANGED
@@ -26,12 +26,13 @@ import { homedir } from 'node:os'
26
26
  import { join } from 'node:path'
27
27
  import { fileURLToPath } from 'node:url'
28
28
  import { callTool } from './mcp-call.mjs'
29
- import { extractTaskHandles, readCredits, readModels, readProjects, readTasks } from './account-data.mjs'
29
+ import { extractTaskHandles, readCredits, readModels, readProjects, readTasks, summarizeTask } from './account-data.mjs'
30
30
  import { applyTaskStatus, listAssets, listTasks, loadLedger, recordAsset, recordTasks, saveLedger } from './ledger.mjs'
31
31
  import { buildState, mergeState, parseState } from './state.mjs'
32
32
  import { CONFIRM_THRESHOLD_CREDITS, FREE_TOOLS, catalog, quote, quoteExtra } from './pricing.mjs'
33
33
  import { createBundlePayload, newKey, open as openBundle, seal } from './vault.mjs'
34
34
  import { TOOL_GROUPS, applyToggle, expandToolNames, isModelDisabled, isToolDisabled, normalizeDisabled, switchBoard } from './catalog.mjs'
35
+ import { buildGeneratePayload } from './payload.mjs'
35
36
 
36
37
  export const name = 'lovart-mcp'
37
38
  export const inject = ['tools', 'credentials', 'mcpManager']
@@ -801,6 +802,11 @@ export async function apply(ctx, config = {}) {
801
802
  aspect_ratio: { type: 'string', description: 'Aspect ratio such as 1:1, 16:9, 9:16.' },
802
803
  duration: { type: 'string', description: 'Video length in seconds.' },
803
804
  count: { type: 'string', description: 'Number of outputs; images map to "n".' },
805
+ ref_images: { type: 'string', description: 'Reference image URLs for image editing or video conditioning. Lovart must host them: upload with lovart_tool(tool:"upload_asset") first. Accepts one URL, a comma-separated list, or a JSON array.' },
806
+ first_frame: { type: 'string', description: 'Video only: URL of the opening frame (Lovart-hosted). Turns the call into image-to-video.' },
807
+ last_frame: { type: 'string', description: 'Video only: URL of the closing frame for models that interpolate between two frames.' },
808
+ ref_video: { type: 'string', description: 'Video only: URL of a video whose motion should be followed (Lovart-hosted).' },
809
+ project_id: { type: 'string', description: 'Optional Lovart project to add the artifacts to; omit and one is created.' },
804
810
  confirm_credits: { type: 'string', description: 'Set to "true" to accept the quoted cost and submit.' },
805
811
  options: { type: 'string', description: 'Optional JSON object with extra model parameters.' },
806
812
  },
@@ -839,19 +845,28 @@ export async function apply(ctx, config = {}) {
839
845
  return 'options must be a JSON object, for example {"quality":"medium"}'
840
846
  }
841
847
  }
842
- const params = { ...extra }
843
- const payload = { prompt: args.prompt, model: priced.model }
844
- if (kind === 'video') {
845
- if (typeof args.aspect_ratio === 'string') payload.aspect_ratio = args.aspect_ratio
846
- if (typeof args.duration === 'string') payload.duration = Number(args.duration)
847
- if (typeof args.resolution === 'string') params.resolution = String(args.resolution).toLowerCase()
848
- } else {
849
- if (typeof args.aspect_ratio === 'string') payload.aspect_ratio = args.aspect_ratio
850
- if (typeof args.count === 'string' && Number(args.count) > 1) payload.n = Number(args.count)
851
- if (typeof args.resolution === 'string') params.resolution = args.resolution
852
- if (typeof args.size === 'string') params.size = args.size
848
+ let built
849
+ try {
850
+ built = buildGeneratePayload({
851
+ kind,
852
+ prompt: args.prompt,
853
+ model: priced.model,
854
+ aspectRatio: typeof args.aspect_ratio === 'string' ? args.aspect_ratio : undefined,
855
+ resolution: typeof args.resolution === 'string' ? args.resolution : undefined,
856
+ size: typeof args.size === 'string' ? args.size : undefined,
857
+ duration: typeof args.duration === 'string' ? args.duration : undefined,
858
+ count: typeof args.count === 'string' ? args.count : 1,
859
+ refImages: args.ref_images,
860
+ firstFrame: typeof args.first_frame === 'string' ? args.first_frame : undefined,
861
+ lastFrame: typeof args.last_frame === 'string' ? args.last_frame : undefined,
862
+ refVideo: typeof args.ref_video === 'string' ? args.ref_video : undefined,
863
+ projectId: typeof args.project_id === 'string' ? args.project_id : undefined,
864
+ options: extra,
865
+ })
866
+ } catch (error) {
867
+ return `Cannot build the ${kind} request: ${error instanceof Error ? error.message : String(error)}`
853
868
  }
854
- if (Object.keys(params).length > 0) payload.params = params
869
+ const payload = built.payload
855
870
  const toolName = kind === 'video' ? 'generate_video' : 'generate_image'
856
871
  try {
857
872
  const result = await callTool(access, toolName, payload)
@@ -870,6 +885,8 @@ export async function apply(ctx, config = {}) {
870
885
  estimatedUsd: priced.usd,
871
886
  relaxEligible: priced.relax.eligible,
872
887
  trackedTasks: recorded,
888
+ mode: built.mode,
889
+ warnings: built.warnings,
873
890
  result,
874
891
  }, null, 2)
875
892
  } catch (error) {
@@ -878,6 +895,75 @@ export async function apply(ctx, config = {}) {
878
895
  },
879
896
  })))
880
897
 
898
+ disposers.push(ctx.tools.register(defineTool({
899
+ name: 'lovart_task',
900
+ description: 'Read Lovart tasks and hand back the artifacts — the final image or video URLs — once they finish. Pass the task ids that lovart_generate returned; set wait:"true" to poll until every task settles.',
901
+ parameters: {
902
+ account: { type: 'string', description: 'Account id; defaults to the first configured account.' },
903
+ task_ids: { type: 'string', description: 'One task id, a comma-separated list, or a JSON array.' },
904
+ wait: { type: 'string', description: 'Set to "true" to block until the tasks complete.' },
905
+ timeout_seconds: { type: 'string', description: 'Polling budget in seconds, default 120, max 900.' },
906
+ },
907
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
908
+ async execute(args) {
909
+ const account = findAccount(String(args.account ?? ''))
910
+ if (account === undefined) return `Unknown account "${args.account}". Known: ${accounts.map((entry) => entry.id).join(', ')}`
911
+ const access = await readValue(credentials, account.refs.access)
912
+ if (access === undefined) return `lovart-${account.id} is not authorized. Run lovart_login(account: "${account.id}") first.`
913
+ const raw = String(args.task_ids ?? '').trim()
914
+ let ids = []
915
+ if (raw.startsWith('[')) {
916
+ try {
917
+ const parsed = JSON.parse(raw)
918
+ if (Array.isArray(parsed)) ids = parsed.map((item) => String(item).trim()).filter(Boolean)
919
+ } catch {
920
+ return 'task_ids must be a JSON array of strings, or a comma-separated list.'
921
+ }
922
+ } else if (raw !== '') {
923
+ ids = raw.split(',').map((item) => item.trim()).filter(Boolean)
924
+ }
925
+ if (ids.length === 0) return 'task_ids is required: pass the ids returned by lovart_generate.'
926
+ const waiting = String(args.wait ?? '').toLowerCase() === 'true'
927
+ const budgetSeconds = Math.min(Math.max(Number(args.timeout_seconds ?? 120) || 120, 5), 900)
928
+ const deadline = Date.now() + budgetSeconds * 1000
929
+ const settled = new Set(['completed', 'failed', 'error', 'cancelled', 'canceled'])
930
+ const rowsFrom = (payload) => {
931
+ const list = Array.isArray(payload)
932
+ ? payload
933
+ : Array.isArray(payload?.tasks)
934
+ ? payload.tasks
935
+ : Array.isArray(payload?.result?.tasks)
936
+ ? payload.result.tasks
937
+ : payload?.task_id !== undefined || payload?.taskId !== undefined
938
+ ? [payload]
939
+ : []
940
+ return list.map((item) => summarizeTask(item)).filter((item) => item !== null && item.taskId !== null)
941
+ }
942
+ let rows = []
943
+ for (;;) {
944
+ try {
945
+ rows = rowsFrom(await callTool(access, 'get_task_status', { task_ids: ids }, { timeoutMs: 30000 }))
946
+ } catch (error) {
947
+ return `Could not read tasks: ${error instanceof Error ? error.message : String(error)}`
948
+ }
949
+ if (!waiting) break
950
+ if (rows.length > 0 && rows.every((row) => row.status !== null && settled.has(String(row.status).toLowerCase()))) break
951
+ if (Date.now() >= deadline) break
952
+ await new Promise((resolve) => setTimeout(resolve, 3000))
953
+ }
954
+ try {
955
+ const ledger = loadLedger()
956
+ if (applyTaskStatus(ledger, rows)) saveLedger(ledger)
957
+ } catch { /* the ledger is a convenience, never a hard failure */ }
958
+ return JSON.stringify({
959
+ account: `lovart-${account.id}`,
960
+ waited: waiting,
961
+ tasks: rows,
962
+ artifacts: rows.flatMap((row) => row.artifacts ?? []).filter((item) => item.url),
963
+ }, null, 2)
964
+ },
965
+ })))
966
+
881
967
  disposers.push(ctx.tools.register(defineTool({
882
968
  name: 'lovart_export_credential',
883
969
  description: 'Export one account login as an encrypted bundle plus a separate one-time key file. Tokens are never printed: move both files to another DSH machine and run lovart_import_credential there. Only for your own machines — sharing an account login breaks Lovart terms and gives full control of that account.',
package/lib/panel.mjs CHANGED
@@ -131,11 +131,12 @@ export function registerPanel(ctx, { accounts, credentials, login, addAccount, r
131
131
  return { generatedAt: new Date(now).toISOString(), proxy: proxy || null, accounts: rows }
132
132
  }
133
133
 
134
- const handler = async (req, res) => {
134
+ const latestKey = Symbol.for('dsh.lovart.panel.latest')
135
+ const serve = async (req, res) => {
135
136
  try {
136
137
  if (!allowed(req)) return writeJson(res, 403, { error: 'forbidden' })
137
138
  const url = new URL(req.url ?? '/', 'http://dsh.internal')
138
- const route = url.pathname.slice(PANEL_API.length).replace(/^\/+/, '')
139
+ const route = url.pathname.slice(PANEL_API.length).replace(/^\/+/, '').replace(/\/+$/, '')
139
140
  if (route === 'status' && (req.method === 'GET' || req.method === 'HEAD')) {
140
141
  return writeJson(res, 200, await status())
141
142
  }
@@ -277,11 +278,21 @@ export function registerPanel(ctx, { accounts, credentials, login, addAccount, r
277
278
  return writeJson(res, 500, { error: String(error instanceof Error ? error.message : error).slice(0, 300) })
278
279
  }
279
280
  }
280
- return writeJson(res, 404, { error: 'not found' })
281
+ return writeJson(res, 404, { error: 'not found', route, version: 'panel' })
281
282
  } catch (error) {
282
283
  return writeJson(res, 500, { error: String(error instanceof Error ? error.message : error).slice(0, 300) })
283
284
  }
284
285
  }
285
286
 
287
+ // Several generations of this package can be alive at once: a webServer prefix
288
+ // route cannot be replaced, so the first registration keeps answering. Let every
289
+ // older handler forward to the newest one instead of serving stale routes.
290
+ const handler = async (req, res) => {
291
+ const latest = globalThis[latestKey]
292
+ if (latest !== undefined && latest !== handler) return latest(req, res)
293
+ return serve(req, res)
294
+ }
295
+ globalThis[latestKey] = handler
296
+
286
297
  return server.register({ kind: 'prefix', path: PANEL_API, handler })
287
298
  }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Pure builders for Lovart MCP payloads.
3
+ *
4
+ * The gateway's `generate_image` / `generate_video` tools only accept a few
5
+ * top-level fields; every model-specific field (resolution, size, quality, ...)
6
+ * belongs inside `params`. Media arguments must point at files Lovart hosts
7
+ * itself, so anything from elsewhere has to go through `upload_asset` first.
8
+ */
9
+
10
+ export const MODES = [
11
+ { id: 'text-to-image', kind: 'image', label: '文生图', needs: ['prompt'] },
12
+ { id: 'image-with-references', kind: 'image', label: '参考图生图(图生图)', needs: ['prompt', 'ref_images'] },
13
+ { id: 'text-to-video', kind: 'video', label: '文生视频', needs: ['prompt'] },
14
+ { id: 'first-frame-video', kind: 'video', label: '首帧生视频', needs: ['first_frame'] },
15
+ { id: 'first-last-frame-video', kind: 'video', label: '首尾帧生视频', needs: ['first_frame', 'last_frame'] },
16
+ { id: 'video-with-references', kind: 'video', label: '参考图/参考视频生视频', needs: ['ref_images'] },
17
+ ]
18
+
19
+ const MEDIA_FIELDS = ['ref_images', 'first_frame', 'last_frame', 'ref_video']
20
+
21
+ function asList(value) {
22
+ if (value === undefined || value === null) return []
23
+ if (Array.isArray(value)) return value.map((item) => String(item).trim()).filter(Boolean)
24
+ const text = String(value).trim()
25
+ if (text === '') return []
26
+ if (text.startsWith('[')) {
27
+ let parsed
28
+ try {
29
+ parsed = JSON.parse(text)
30
+ } catch {
31
+ throw new Error('media lists must be a URL, a comma-separated list, or a JSON array of URLs')
32
+ }
33
+ if (!Array.isArray(parsed)) throw new Error('media lists must be a JSON array of URLs')
34
+ return parsed.map((item) => String(item).trim()).filter(Boolean)
35
+ }
36
+ return text.split(',').map((item) => item.trim()).filter(Boolean)
37
+ }
38
+
39
+ function assertUrl(value, field) {
40
+ let url
41
+ try {
42
+ url = new URL(value)
43
+ } catch {
44
+ throw new Error(`${field} must be an HTTP(S) URL, got ${JSON.stringify(value)}`)
45
+ }
46
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
47
+ throw new Error(`${field} must be an HTTP(S) URL, got ${url.protocol}`)
48
+ }
49
+ return url
50
+ }
51
+
52
+ export function detectMode({ kind = 'image', refImages = [], firstFrame, lastFrame, refVideo } = {}) {
53
+ if (kind === 'video') {
54
+ if (firstFrame !== undefined && lastFrame !== undefined) return 'first-last-frame-video'
55
+ if (firstFrame !== undefined) return 'first-frame-video'
56
+ if (refVideo !== undefined) return 'video-with-references'
57
+ if (refImages.length > 0) return 'video-with-references'
58
+ return 'text-to-video'
59
+ }
60
+ return refImages.length > 0 ? 'image-with-references' : 'text-to-image'
61
+ }
62
+
63
+ export function buildGeneratePayload(input) {
64
+ const kind = input.kind === 'video' ? 'video' : 'image'
65
+ const prompt = typeof input.prompt === 'string' ? input.prompt : ''
66
+ if (prompt.trim() === '') throw new Error('prompt is required')
67
+ if (typeof input.model !== 'string' || input.model === '') throw new Error('model is required')
68
+ const refImages = asList(input.refImages)
69
+ const warnings = []
70
+ const media = { refImages }
71
+ for (const [field, key] of [['firstFrame', 'firstFrame'], ['lastFrame', 'lastFrame'], ['refVideo', 'refVideo']]) {
72
+ const value = input[field]
73
+ if (value !== undefined && value !== null && String(value).trim() !== '') media[key] = String(value).trim()
74
+ }
75
+ for (const list of [refImages, [media.firstFrame, media.lastFrame, media.refVideo].filter(Boolean)].flat()) assertUrl(list, 'media')
76
+ if (media.lastFrame !== undefined && media.firstFrame === undefined) {
77
+ warnings.push('last_frame without first_frame: only some models interpolate from the end frame alone.')
78
+ }
79
+ for (const url of refImages) {
80
+ if (!/(^|\.)lovart\.ai$/.test(new URL(url).hostname)) {
81
+ warnings.push(`${url} is not hosted by Lovart; upload it with lovart_tool(tool:"upload_asset") first, otherwise the gateway rejects the format.`)
82
+ }
83
+ }
84
+
85
+ const params = {}
86
+ if (typeof input.resolution === 'string' && input.resolution !== '') {
87
+ params.resolution = kind === 'video' ? input.resolution.toLowerCase() : input.resolution
88
+ }
89
+ if (kind === 'image' && typeof input.size === 'string' && input.size !== '') params.size = input.size
90
+ if (input.options !== undefined && input.options !== null) {
91
+ if (typeof input.options !== 'object' || Array.isArray(input.options)) throw new Error('options must be a JSON object')
92
+ Object.assign(params, input.options)
93
+ }
94
+
95
+ const payload = { prompt, model: input.model }
96
+ if (typeof input.aspectRatio === 'string' && input.aspectRatio !== '') payload.aspect_ratio = input.aspectRatio
97
+ if (typeof input.projectId === 'string' && input.projectId !== '') payload.project_id = input.projectId
98
+ if (kind === 'image') {
99
+ const count = Number(input.count ?? 1)
100
+ if (Number.isFinite(count) && count > 1) payload.n = Math.trunc(count)
101
+ if (refImages.length > 0) payload.ref_images = refImages
102
+ } else {
103
+ const duration = Number(input.duration)
104
+ if (Number.isFinite(duration) && duration > 0) payload.duration = Math.trunc(duration)
105
+ if (media.firstFrame !== undefined) payload.first_frame = media.firstFrame
106
+ if (media.lastFrame !== undefined) payload.last_frame = media.lastFrame
107
+ if (refImages.length > 0) payload.ref_images = refImages
108
+ if (media.refVideo !== undefined) payload.ref_video = media.refVideo
109
+ }
110
+ if (Object.keys(params).length > 0) payload.params = params
111
+
112
+ return {
113
+ payload,
114
+ mode: detectMode({ kind, refImages, firstFrame: media.firstFrame, lastFrame: media.lastFrame, refVideo: media.refVideo }),
115
+ warnings,
116
+ }
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lovart-mcp",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "main": "./lib/index.js",
6
6
  "exports": {