Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions docs/en/tools-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,8 +337,8 @@ List project assets or upload local images and videos to the active project.
| :--- | :--- | :--- | :--- |
| `action` | `string` | No | `list` (default) or `upload`. |
| `files` | `string[]` | For `upload` | Local image or video paths on the server. |
| `query` | `string` | No | Case-insensitive substring matching asset ID, name, or prompt. |
| `kind` | `string` | No | Filter by `"image"`, `"video"`, `"audio"`, `"scene"`, `"character"`, or `"all"` (default). |
| `query` | `string` | No | Case-insensitive substring matching asset ID, media ID, name, or prompt. |
| `kind` | `string` | No | Filter by `"image"`, `"video"`, `"audio"` (including saved custom voices), `"scene"`, `"character"`, or `"all"` (default). |
| `collection` | `string` | No | Filter by collection ID, name substring, `"all"`, `"none"`, or `"uncollected"`. |
| `limit` | `integer` | No | Maximum items to return (`>= 1`). |
| `resolve_urls` | `boolean` | No | Get missing media URLs. For image or audio requests, the tool resolves assets with an unknown media type before it applies the result limit. Default is `true`. The lookup has a 10-second limit. |
Expand Down Expand Up @@ -387,11 +387,12 @@ The tool checks the result of each write in a new read of the same project. The

### `flow_download`

Download a matching project media asset (image, video, audio, or character look) to `<home>/downloads` and index it in `flow-mcp.db`. Waits up to `45` seconds (`pending: true` on timeout) and returns `{"file", "resource_uri", "record"}`. If the client supports MCP `2025-06-18` or newer, it also returns a `resource_link`.
Download a matching project media asset (image, video, custom voice, character look or assigned voice, scene, or scene clip) to `<home>/downloads` and index it in `flow-mcp.db`. By default, video downloads keep the primary rendition of the asset. Set `quality` to `"360p"`, `"720p"`, `"1080p"`, `"4k"`, or `"best"` to select a verified video variant. Use `<sceneId>` to download a scene (directly for untrimmed single-clip scenes, or through the scene export service of Flow on verified front-end builds; unverified builds return `unsupported_front_end`). Use `<sceneId>:<wfId>` to download one clip workflow from a scene. Waits up to `45` seconds (`pending: true` on timeout) and returns `{"file", "resource_uri", "record"}`. If the client supports MCP `2025-06-18` or newer, it also returns a `resource_link`.

| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `match` | `string` | Yes | Exact asset ID, exact name, or case-insensitive substring matching a project asset. |
| `match` | `string` | Yes | Exact asset ID, `<sceneId>:<wfId>` scene clip ID, media or variant ID, exact name, or case-insensitive substring matching a project asset. |
| `quality` | `string` | No | Video quality selector: `"original"` (default), `"360p"`, `"720p"`, `"1080p"`, `"4k"`, or `"best"`. |

### `flow_downloads`

Expand Down
9 changes: 5 additions & 4 deletions docs/ja/tools-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,8 +337,8 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、
| :--- | :--- | :--- | :--- |
| `action` | `string` | いいえ | `list`(既定)または `upload`。 |
| `files` | `string[]` | `upload` の場合に必須 | サーバー上のローカル画像または動画のパス。 |
| `query` | `string` | いいえ | アセット ID、名前、またはプロンプトに一致する大文字小文字を区別しない部分文字列。 |
| `kind` | `string` | いいえ | `"image"`、`"video"`、`"audio"`、`"scene"`、`"character"`、または `"all"`(既定)で絞り込みます。 |
| `query` | `string` | いいえ | アセット ID、メディア ID、名前、またはプロンプトに一致する大文字小文字を区別しない部分文字列。 |
| `kind` | `string` | いいえ | `"image"`、`"video"`、`"audio"`(保存済みカスタムボイスを含む)、`"scene"`、`"character"`、または `"all"`(既定)で絞り込みます。 |
| `collection` | `string` | いいえ | コレクション ID、名前部分文字列、`"all"`、`"none"`、または `"uncollected"` で絞り込みます。 |
| `limit` | `integer` | いいえ | 返す最大項目数(`>= 1`)。 |
| `resolve_urls` | `boolean` | いいえ | 不足しているメディア URL を取得します。画像または音声で絞り込む場合は、種類が不明なアセットを確認してから件数を制限します。既定値は `true` で、待機時間は最大 10 秒です。 |
Expand Down Expand Up @@ -387,11 +387,12 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、

### `flow_download`

一致するプロジェクトのメディアアセット(画像、動画、音声、またはキャラクター外見)を `<home>/downloads` へダウンロードし、`flow-mcp.db` に登録します。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。
一致するプロジェクトのメディアアセット(画像、動画、カスタムボイス、キャラクター外見または設定済みボイス、シーン、またはシーンクリップ)を `<home>/downloads` へダウンロードし、`flow-mcp.db` に登録します。動画ダウンロードは既定でアセット本来のプライマリ版を保持し、`quality` に `"360p"`、`"720p"`、`"1080p"`、`"4k"`、または `"best"` を指定すると検証済みの動画解像度派生版を選択できます。`<sceneId>` でシーン全体をダウンロードし(未トリミングの単一クリップシーンは直接ダウンロードし、複数クリップまたはトリミング済みシーンは検証済みフロントエンドビルド上で Flow のシーン書き出しサービスを経由して書き出し、未検証ビルドでは `unsupported_front_end` を返します)、`<sceneId>:<wfId>` でシーン内の単一クリップワークフローをダウンロードします。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。

| パラメータ | 型 | 必須 | 説明 |
| :--- | :--- | :--- | :--- |
| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセット ID、完全一致名、または大文字小文字を区別しない部分文字列。 |
| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセット ID、`<sceneId>:<wfId>` シーンクリップ ID、メディアまたは派生 ID、完全一致名、または大文字小文字を区別しない部分文字列。 |
| `quality` | `string` | いいえ | 動画品質の選択:`"original"`(既定)、`"360p"`、`"720p"`、`"1080p"`、`"4k"`、または `"best"`。 |

### `flow_downloads`

Expand Down
9 changes: 5 additions & 4 deletions docs/zh-CN/tools-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,8 +337,8 @@ flow-mcp [OPTIONS] <COMMAND>
| :--- | :--- | :--- | :--- |
| `action` | `string` | 否 | `list`(默认)或 `upload`。 |
| `files` | `string[]` | `upload` 时必填 | 服务端所在机器的本地图片或视频路径。 |
| `query` | `string` | 否 | 匹配资产 ID、名称或提示词的忽略大小写子串。 |
| `kind` | `string` | 否 | 按 `"image"`、`"video"`、`"audio"`、`"scene"`、`"character"` 或 `"all"`(默认)筛选。 |
| `query` | `string` | 否 | 匹配资产 ID、媒体 ID、名称或提示词的忽略大小写子串。 |
| `kind` | `string` | 否 | 按 `"image"`、`"video"`、`"audio"`(含已保存的自定义音色)、`"scene"`、`"character"` 或 `"all"`(默认)筛选。 |
| `collection` | `string` | 否 | 按集合 ID、名称子串、`"all"`、`"none"` 或 `"uncollected"` 筛选。 |
| `limit` | `integer` | 否 | 返回的最大条目数(`>= 1`)。 |
| `resolve_urls` | `boolean` | 否 | 补齐缺失的媒体 URL。筛选图片或音频时,先查明媒体类型未知的资源,再应用条数限制。默认 `true`,最多等待 10 秒。 |
Expand Down Expand Up @@ -387,11 +387,12 @@ flow-mcp [OPTIONS] <COMMAND>

### `flow_download`

将匹配的项目媒体资产(图像、视频、音频或角色外观)下载至 `<home>/downloads` 并索引到 `flow-mcp.db`。最多等待 `45` 秒(超时返回 `pending: true`),并返回 `{"file", "resource_uri", "record"}`。如果客户端支持 MCP `2025-06-18` 或更高版本,还会返回 `resource_link`。
将匹配的项目媒体资产(图像、视频、自定义音色、角色外观或绑定音色、场景或场景片段)下载至 `<home>/downloads` 并索引到 `flow-mcp.db`。视频下载默认保留资产本身的主版本;可将 `quality` 设为 `"360p"`、`"720p"`、`"1080p"`、`"4k"` 或 `"best"` 以选择已验证的视频清晰度变体。传入 `<sceneId>` 下载整个场景(未裁剪的单片段场景直接下载,多片段或已裁剪场景在已验证的前端构建上通过 Flow 场景导出服务导出,未验证构建返回 `unsupported_front_end`);传入 `<sceneId>:<wfId>` 下载场景内的单个片段工作流。最多等待 `45` 秒(超时返回 `pending: true`),并返回 `{"file", "resource_uri", "record"}`。如果客户端支持 MCP `2025-06-18` 或更高版本,还会返回 `resource_link`。

| 参数 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| `match` | `string` | 是 | 匹配项目资产的精确资产 ID、精确名称或忽略大小写子串。 |
| `match` | `string` | 是 | 匹配项目资产的精确资产 ID、`<sceneId>:<wfId>` 场景片段 ID、媒体或变体 ID、精确名称或忽略大小写子串。 |
| `quality` | `string` | 否 | 视频清晰度选择:`"original"`(默认)、`"360p"`、`"720p"`、`"1080p"`、`"4k"` 或 `"best"`。 |

### `flow_downloads`

Expand Down
268 changes: 268 additions & 0 deletions src/asset_matching.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,268 @@
// Copyright 2026 ByteLand Technology Limited
// SPDX-License-Identifier: MIT

//! Asset ID, variant media ID, and `<sceneId>:<wfId>` scene clip matching helpers.

use anyhow::{Context, Result};

use crate::assets::FlowAsset;

/// Strips a leading `media/` or `workflows/` prefix from a resource identifier.
pub(crate) fn strip_resource_prefix(raw: &str) -> &str {
let trimmed = raw.trim();
if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") {
&trimmed[6..]
} else if trimmed.len() > 10 && trimmed[..10].eq_ignore_ascii_case("workflows/") {
&trimmed[10..]
} else {
trimmed
}
}

/// Strips a leading `media/` prefix from a media resource identifier.
pub(crate) fn strip_media_prefix(raw: &str) -> &str {
let trimmed = raw.trim();
if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") {
&trimmed[6..]
} else {
trimmed
}
}

/// Finds the first asset matching `pred`, preferring `video`, `image`, and `audio` tiles over referencing `character` and `scene` tiles.
fn find_preferring_direct_media<F>(assets: &[FlowAsset], mut pred: F) -> Option<&FlowAsset>
where
F: FnMut(&FlowAsset) -> bool,
{
let mut fallback: Option<&FlowAsset> = None;
for asset in assets {
if pred(asset) {
if !matches!(asset.kind.as_str(), "character" | "scene") {
return Some(asset);
}
if fallback.is_none() {
fallback = Some(asset);
}
}
}
fallback
}

/// Selects the best-matching asset by exact ID, media ID, exact name, name substring,
/// ID or media ID substring, or optional prompt substring.
pub(crate) fn match_asset<'a>(
assets: &'a [FlowAsset],
match_str: &str,
include_prompt: bool,
) -> Option<&'a FlowAsset> {
let raw = match_str.trim();
if raw.is_empty() {
return None;
}
let clean_raw = strip_media_prefix(raw);
let clean_res = strip_resource_prefix(raw);
let lower = raw.to_lowercase();
let clean_lower = clean_raw.to_lowercase();
let clean_res_lower = clean_res.to_lowercase();

assets
.iter()
.find(|a| a.id == raw)
.or_else(|| {
find_preferring_direct_media(assets, |a| {
a.workflow_id
.as_deref()
.is_some_and(|wf| wf == raw || strip_resource_prefix(wf) == clean_res)
})
})
.or_else(|| {
find_preferring_direct_media(assets, |a| {
a.primary_media_id
.as_deref()
.is_some_and(|id| id == raw || strip_media_prefix(id) == clean_raw)
})
})
.or_else(|| {
find_preferring_direct_media(assets, |a| {
a.media_ids
.iter()
.any(|id| id == raw || strip_media_prefix(id) == clean_raw)
})
})
.or_else(|| assets.iter().find(|a| a.name.eq_ignore_ascii_case(raw)))
.or_else(|| {
assets
.iter()
.find(|a| a.name.to_lowercase().contains(&lower))
})
.or_else(|| {
assets
.iter()
.find(|a| !a.id.contains(':') && a.id.to_lowercase().contains(&lower))
})
.or_else(|| assets.iter().find(|a| a.id.to_lowercase().contains(&lower)))
.or_else(|| {
find_preferring_direct_media(assets, |a| {
a.workflow_id
.as_deref()
.is_some_and(|wf| wf.to_lowercase().contains(&clean_res_lower))
|| a.primary_media_id
.as_deref()
.is_some_and(|id| id.to_lowercase().contains(&clean_lower))
|| a.media_ids
.iter()
.any(|id| id.to_lowercase().contains(&clean_lower))
})
})
.or_else(|| {
if include_prompt {
assets.iter().find(|a| {
a.prompt
.as_deref()
.unwrap_or("")
.to_lowercase()
.contains(&lower)
})
} else {
None
}
})
}

/// Pins `target.primary_media_id` when `match_str` selects a specific variant in `target.media_ids`.
pub(crate) fn pin_matched_variant_id(target: &mut FlowAsset, match_str: &str) {
let raw = match_str.trim();
if raw.is_empty() || target.id == raw || target.name.eq_ignore_ascii_case(raw) {
return;
}
let clean_raw = strip_media_prefix(raw);
let exact = target
.media_ids
.iter()
.find(|id| id.as_str() == raw || strip_media_prefix(id) == clean_raw)
.cloned();
let lower = raw.to_lowercase();
let clean_lower = clean_raw.to_lowercase();
let matched = exact.or_else(|| {
if target.name.to_lowercase().contains(&lower) || target.id.to_lowercase().contains(&lower)
{
return None;
}
target
.media_ids
.iter()
.find(|id| id.to_lowercase().contains(&clean_lower))
.cloned()
});
if let Some(variant_id) = matched {
let normalized = strip_media_prefix(&variant_id).to_string();
let changed =
target.primary_media_id.as_deref().map(strip_media_prefix) != Some(normalized.as_str());
target.primary_media_id = Some(normalized);
if changed {
target.url = None;
}
}
}

/// Resolves an explicit `<sceneId>:<wfId>` clip selector against a scene tile in `assets`.
pub(crate) fn resolve_scene_clip_selector(
assets: &[FlowAsset],
match_str: &str,
context_label: &str,
) -> Result<Option<FlowAsset>> {
let raw = match_str.trim();
if assets.iter().any(|a| a.id == raw) {
return Ok(None);
}
let Some((raw_scene, raw_wf)) = raw.split_once(':') else {
return Ok(None);
};
let scene_key = strip_resource_prefix(raw_scene);
let Some(scene) = assets
.iter()
.find(|a| a.kind == "scene" && (a.id == raw_scene.trim() || a.id == scene_key))
else {
return Ok(None);
};
let wf_id = strip_resource_prefix(raw_wf);
if wf_id.is_empty() || wf_id.contains(':') {
anyhow::bail!(
"Invalid scene clip selector '{}' for {}: expected '<scene_id>:<workflow_id>'",
raw,
context_label
);
}
let clip = scene
.scene_clips
.iter()
.find(|c| c.workflow_id == wf_id || strip_resource_prefix(&c.workflow_id) == wf_id)
.with_context(|| {
format!(
"Scene '{}' has no clip workflow '{}' for {}",
scene.id, wf_id, context_label
)
})?;
let standalone = assets.iter().find(|a| {
a.kind == "video"
&& (a.id == clip.workflow_id
|| a.id == wf_id
|| a.workflow_id
.as_deref()
.is_some_and(|wf| wf == wf_id || strip_resource_prefix(wf) == wf_id))
});
let primary_media_id = clip
.primary_media_id
.clone()
.or_else(|| standalone.and_then(|v| v.primary_media_id.clone()));
let url = clip
.url
.clone()
.or_else(|| standalone.and_then(|v| v.url.clone()));
let mut media_ids = standalone.map(|v| v.media_ids.clone()).unwrap_or_default();
if let Some(ref mid) = primary_media_id
&& !media_ids.iter().any(|existing| existing == mid)
{
media_ids.insert(0, mid.clone());
}
let resolved_id = if context_label == "flow_download" || standalone.is_none() {
format!("{}:{}", scene.id, clip.workflow_id)
} else if let Some(v) = standalone {
v.id.clone()
} else {
format!("{}:{}", scene.id, clip.workflow_id)
};
let name = standalone
.map(|v| v.name.clone())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| format!("{} ({})", scene.name, clip.workflow_id));
Ok(Some(FlowAsset {
id: resolved_id,
name,
kind: "video".to_string(),
prompt: standalone.and_then(|v| v.prompt.clone()),
url,
collection_id: scene.collection_id.clone(),
collection_name: scene.collection_name.clone(),
width: standalone.and_then(|v| v.width),
height: standalone.and_then(|v| v.height),
duration: standalone.and_then(|v| v.duration),
primary_media_id,
personality_notes: None,
voice: None,
trim_start_seconds: standalone.and_then(|v| v.trim_start_seconds),
trim_end_seconds: standalone.and_then(|v| v.trim_end_seconds),
media_status: standalone.and_then(|v| v.media_status.clone()),
media_error: standalone.and_then(|v| v.media_error.clone()),
media_ids,
workflow_id: Some(clip.workflow_id.clone()),
requires_scene_export: false,
pcm_audio: false,
media_kind: Some("video".to_string()),
variants: standalone.map(|v| v.variants.clone()).unwrap_or_default(),
scene_clips: Vec::new(),
created_at: standalone
.and_then(|v| v.created_at.clone())
.or_else(|| scene.created_at.clone()),
}))
}
Loading
Loading