summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md12
-rw-r--r--config.example.toml4
-rw-r--r--doc/Design.md6
-rw-r--r--doc/Specifications.md8
-rw-r--r--doc/config.md59
-rw-r--r--doc/mcp.md4
-rw-r--r--src/mcp_sd15/config.py27
-rw-r--r--src/mcp_sd15/schema.py34
-rw-r--r--src/mcp_sd15/tools/generate_guided_image.py2
-rw-r--r--src/mcp_sd15/tools/generate_image.py2
-rw-r--r--src/mcp_sd15/tools/inpaint_image.py2
-rw-r--r--tests/conftest.py2
-rw-r--r--tests/test_config.py74
-rw-r--r--tests/test_schema.py62
14 files changed, 286 insertions, 12 deletions
diff --git a/README.md b/README.md
index 46c3b0c..aafc072 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,18 @@ port = 8000
この場合、MCPクライアントは`http://127.0.0.1:8000/mcp`へ接続します。
+全ツールで共通するbase promptを`[prompt]`で指定できます。プロンプトファイルは
+`<root>/prompts/`に配置し、TOMLにはファイル名だけを記述します。
+
+```toml
+[prompt]
+positive_file = "positive.txt"
+negative_file = "negative.txt"
+```
+
+起動時にファイルを読み込み、LLMからのプロンプトと結合してpipelineへ渡します。
+positiveは`base, user`の順でカンマ区切り、negativeは`base\nuser`の順で改行区切りです。
+
モデルは `<root>/checkpoints`、`vae`、`lora`、`controlnet` からだけ読み込みます。
VAE componentは生成に常に必要です。`model.vae`を省略した場合はcheckpoint内蔵VAEを使い、
指定した場合だけ外部VAEへ置き換えます。設定されたLoRAは起動時にすべてロードされ、3つの
diff --git a/config.example.toml b/config.example.toml
index ed8988a..aa8766b 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -35,3 +35,7 @@ directory = "./outputs"
# transport = "streamable-http" の場合は host と port も指定する
# host = "127.0.0.1"
# port = 8000
+
+# [prompt]
+# positive_file = "positive.txt"
+# negative_file = "negative.txt"
diff --git a/doc/Design.md b/doc/Design.md
index ede063c..a603406 100644
--- a/doc/Design.md
+++ b/doc/Design.md
@@ -146,6 +146,11 @@ class GenerationConfig:
cfg_scale: float
scheduler: str
default_size: str
+
+@dataclass(frozen=True)
+class PromptConfig:
+ positive: str = ""
+ negative: str = ""
```
Pydanticは必須とせず、`tomllib + dataclass + 明示的validation`を基本とする。
@@ -160,6 +165,7 @@ Pydanticは必須とせず、`tomllib + dataclass + 明示的validation`を基æœ
| VAE | `<root>/vae/<file>` |
| LoRA | `<root>/lora/<file>` |
| ControlNet | `<root>/controlnet/<file>` |
+| prompt | `<root>/prompts/<file>` |
設計上、MCP入力から任意モデルパスを指定することは禁止する。
diff --git a/doc/Specifications.md b/doc/Specifications.md
index db59c28..cc178bb 100644
--- a/doc/Specifications.md
+++ b/doc/Specifications.md
@@ -133,6 +133,7 @@ LLM側には生成意図に必要な最小限の入力のみを公開し、モãƒ
| LoRA | 0個以上 |
| LoRA weight | LoRAごとに指定 |
| ControlNet | Depth / Openpose / Inpaintを個別設定 |
+| Base prompt | positive / negative 各0または1ファイル |
| モデルルート | TOMLで1つのルートディレクトリを指定 |
### 6.3 推奨ディレクトリ
@@ -142,7 +143,8 @@ models/
├─ checkpoints/
├─ vae/
├─ lora/
-└─ controlnet/
+├─ controlnet/
+└─ prompts/
```
設定値には原則としてファイル名を記述し、内部で用途別ディレクトリへ解決する。
@@ -188,6 +190,10 @@ model = "control_v11p_sd15_inpaint.safetensors"
[output]
directory = "./outputs"
+
+[prompt]
+positive_file = "positive.txt"
+negative_file = "negative.txt"
```
### 7.1 Scheduler
diff --git a/doc/config.md b/doc/config.md
index 48142dc..9fcdd55 100644
--- a/doc/config.md
+++ b/doc/config.md
@@ -25,10 +25,13 @@ uv run mcp-sd15 --config C:\path\to\config.toml
│ └─ <model.vae>
├─ lora/
│ └─ <model.lora.file>
-└─ controlnet/
- ├─ <controlnet.depth.model>
- ├─ <controlnet.openpose.model>
- └─ <controlnet.inpaint.model>
+├─ controlnet/
+│ ├─ <controlnet.depth.model>
+│ ├─ <controlnet.openpose.model>
+│ └─ <controlnet.inpaint.model>
+└─ prompts/
+ ├─ <prompt.positive_file>
+ └─ <prompt.negative_file>
```
各モデル項目にはパスではなくファイル名だけを記述する。絶対パス、ディレクトリ名を含む
@@ -59,6 +62,8 @@ uv run mcp-sd15 --config C:\path\to\config.toml
| `server.transport` | string enum | No | `stdio` |
| `server.host` | string | No | `127.0.0.1` |
| `server.port` | integer | No | `8000` |
+| `prompt.positive_file` | string | No | なし |
+| `prompt.negative_file` | string | No | なし |
## 4. `[model]`
@@ -295,10 +300,46 @@ port = 8000
- 既定値は`8000`
- `transport`が`stdio`のときは使用されない
+## 10. `[prompt]`
+
+全ツールで共通するbase promptを指定する。プロンプトファイルは`<root>/prompts/`に
+配置し、TOMLにはファイル名だけを記述する。table自体を省略した場合はbase promptなし
+(後方互換)となる。
+
+```toml
+[prompt]
+positive_file = "positive.txt"
+negative_file = "negative.txt"
+```
+
+起動時にファイルを読み込み、LLMからのプロンプトと結合してpipelineへ渡す。
+
+### 結合規則
+
+| 項目 | 結合方式 |
+|---|---|
+| positive | `base_positive, user_positive` の順でカンマ区切り |
+| negative | `base_negative\nuser_negative` の順で改行区切り |
+
+baseが空の場合はuserプロンプトのみになる。userの`positive_prompt`が空の場合は
+従来通りエラーになる。
+
+### `positive_file`
+
+- `<root>/prompts/<positive_file>`として解決
+- ファイル名のみ指定可能。パスは拒否される
+- 省略時はbase positiveなし
+
+### `negative_file`
+
+- `<root>/prompts/<negative_file>`として解決
+- ファイル名のみ指定可能。パスは拒否される
+- 省略時はbase negativeなし
+
相対`directory`はconfigファイルのディレクトリを基準に解決する。保存が有効な場合、
ディレクトリは最初の保存時に作成され、ファイル名はランダムUUIDの`<uuid>.png`となる。
-## 9. 最小設定例
+## 11. 最小設定例
Text-to-Imageだけを使用する最小構成は次のとおり。
@@ -311,7 +352,7 @@ checkpoint = "model.safetensors"
この場合、VAEとLoRAは使用せず、全ControlNetとローカル保存は無効になる。生成設定には
既定値が使用される。
-## 10. 全設定例
+## 12. 全設定例
```toml
[model]
@@ -349,9 +390,13 @@ model = "control_v11p_sd15_inpaint.safetensors"
[output]
enabled = false
directory = "./outputs"
+
+[prompt]
+positive_file = "positive.txt"
+negative_file = "negative.txt"
```
-## 11. 起動時validation
+## 13. 起動時validation
次のいずれかに該当するとMCPサーバは起動しない。
diff --git a/doc/mcp.md b/doc/mcp.md
index 32c644d..9edb3ca 100644
--- a/doc/mcp.md
+++ b/doc/mcp.md
@@ -24,6 +24,10 @@ Stable Diffusion 1.xによる画像生成を行う次の3ツールを公開すã‚
| `negative_prompt` | 任意の文字列。省略または`null`の場合は空文字列 |
| 最大長 | それぞれ10,000文字 |
+`[prompt]`設定でbase promptを指定している場合、LLMからのプロンプトと結合してから
+pipelineへ渡す。positiveは`base, user`の順でカンマ区切り、negativeは`base\nuser`の順で
+改行区切りとなる。base promptはMCPツール入力には公開しない。
+
### 2.2 Image size
`size`には次の列挙値だけを指定できる。省略または`null`の場合は
diff --git a/src/mcp_sd15/config.py b/src/mcp_sd15/config.py
index df2da34..e41bdfd 100644
--- a/src/mcp_sd15/config.py
+++ b/src/mcp_sd15/config.py
@@ -80,12 +80,19 @@ class ServerConfig:
@dataclass(frozen=True)
+class PromptConfig:
+ positive: str = ""
+ negative: str = ""
+
+
+@dataclass(frozen=True)
class AppConfig:
model: ModelConfig
generation: GenerationConfig
controlnet: ControlNetConfig
output: OutputConfig
server: ServerConfig = ServerConfig()
+ prompt: PromptConfig = PromptConfig()
def controlnet_path(self, mode: str) -> Path:
item = self.controlnet.for_mode(mode)
@@ -121,6 +128,13 @@ def _filename(value: str | None, label: str) -> str | None:
return value
+def _read_prompt(path: Path) -> str:
+ try:
+ return path.read_text(encoding="utf-8").strip()
+ except OSError as exc:
+ raise ConfigError(f"cannot read prompt file {path}: {exc}") from exc
+
+
def _bool(table: dict[str, Any], key: str, default: bool) -> bool:
value = table.get(key, default)
if not isinstance(value, bool):
@@ -230,12 +244,25 @@ def load_config(path: str | Path, *, validate_paths: bool = True) -> AppConfig:
):
raise ConfigError("server.port must be an integer between 1 and 65535")
+ prompt_raw = _table(raw, "prompt")
+ positive_file = _filename(_string(prompt_raw, "positive_file"), "prompt.positive_file")
+ negative_file = _filename(_string(prompt_raw, "negative_file"), "prompt.negative_file")
+ prompt_positive = ""
+ prompt_negative = ""
+ if positive_file:
+ positive_path = root / "prompts" / positive_file
+ prompt_positive = _read_prompt(positive_path)
+ if negative_file:
+ negative_path = root / "prompts" / negative_file
+ prompt_negative = _read_prompt(negative_path)
+
config = AppConfig(
model=ModelConfig(root, checkpoint, vae, tuple(loras)),
generation=GenerationConfig(steps_value, cfg_scale, scheduler, default_size),
controlnet=controlnet,
output=OutputConfig(output_dir.resolve(), _bool(output_raw, "enabled", False)),
server=ServerConfig(transport, host, port_value),
+ prompt=PromptConfig(prompt_positive, prompt_negative),
)
if validate_paths:
validate_model_paths(config)
diff --git a/src/mcp_sd15/schema.py b/src/mcp_sd15/schema.py
index e22450d..184cc8d 100644
--- a/src/mcp_sd15/schema.py
+++ b/src/mcp_sd15/schema.py
@@ -49,6 +49,14 @@ def _size(value: str | ImageSize | None, default: str) -> ImageSize:
raise InvalidRequestError(f"unsupported size: {value}") from exc
+def _combine(base: str, user: str, *, separator: str) -> str:
+ if not base:
+ return user
+ if not user:
+ return base
+ return f"{base}{separator}{user}"
+
+
@dataclass(frozen=True)
class TextToImageRequest:
positive_prompt: str
@@ -63,10 +71,14 @@ class TextToImageRequest:
size: str | ImageSize | None = None,
*,
default_size: str = ImageSize.SQUARE_512,
+ base_positive: str = "",
+ base_negative: str = "",
) -> TextToImageRequest:
+ user_positive = _prompt(positive_prompt, "positive_prompt", required=True)
+ user_negative = _prompt(negative_prompt, "negative_prompt", required=False)
return cls(
- _prompt(positive_prompt, "positive_prompt", required=True),
- _prompt(negative_prompt, "negative_prompt", required=False),
+ _combine(base_positive, user_positive, separator=", "),
+ _combine(base_negative, user_negative, separator="\n"),
_size(size, default_size),
)
@@ -89,9 +101,16 @@ class GuidedImageRequest:
size: str | ImageSize | None = None,
*,
default_size: str = ImageSize.SQUARE_512,
+ base_positive: str = "",
+ base_negative: str = "",
) -> GuidedImageRequest:
base = TextToImageRequest.create(
- positive_prompt, negative_prompt, size, default_size=default_size
+ positive_prompt,
+ negative_prompt,
+ size,
+ default_size=default_size,
+ base_positive=base_positive,
+ base_negative=base_negative,
)
try:
mode = ControlMode(control_mode)
@@ -120,9 +139,16 @@ class InpaintImageRequest:
size: str | ImageSize | None = None,
*,
default_size: str = ImageSize.SQUARE_512,
+ base_positive: str = "",
+ base_negative: str = "",
) -> InpaintImageRequest:
base = TextToImageRequest.create(
- positive_prompt, negative_prompt, size, default_size=default_size
+ positive_prompt,
+ negative_prompt,
+ size,
+ default_size=default_size,
+ base_positive=base_positive,
+ base_negative=base_negative,
)
for label, value in (("input_image", input_image), ("mask_image", mask_image)):
if not isinstance(value, str) or not value.strip():
diff --git a/src/mcp_sd15/tools/generate_guided_image.py b/src/mcp_sd15/tools/generate_guided_image.py
index c69286c..fec4229 100644
--- a/src/mcp_sd15/tools/generate_guided_image.py
+++ b/src/mcp_sd15/tools/generate_guided_image.py
@@ -19,5 +19,7 @@ async def generate_guided_image(
negative_prompt,
size,
default_size=service.config.generation.default_size,
+ base_positive=service.config.prompt.positive,
+ base_negative=service.config.prompt.negative,
)
return await service.generate_guided_image(request)
diff --git a/src/mcp_sd15/tools/generate_image.py b/src/mcp_sd15/tools/generate_image.py
index bae30c8..c1ddad9 100644
--- a/src/mcp_sd15/tools/generate_image.py
+++ b/src/mcp_sd15/tools/generate_image.py
@@ -15,5 +15,7 @@ async def generate_image(
negative_prompt,
size,
default_size=service.config.generation.default_size,
+ base_positive=service.config.prompt.positive,
+ base_negative=service.config.prompt.negative,
)
return await service.generate_image(request)
diff --git a/src/mcp_sd15/tools/inpaint_image.py b/src/mcp_sd15/tools/inpaint_image.py
index be1dbda..e1232ce 100644
--- a/src/mcp_sd15/tools/inpaint_image.py
+++ b/src/mcp_sd15/tools/inpaint_image.py
@@ -19,5 +19,7 @@ async def inpaint_image(
negative_prompt,
size,
default_size=service.config.generation.default_size,
+ base_positive=service.config.prompt.positive,
+ base_negative=service.config.prompt.negative,
)
return await service.inpaint_image(request)
diff --git a/tests/conftest.py b/tests/conftest.py
index 862b4f5..e4a7c4b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -14,6 +14,7 @@ from mcp_sd15.config import (
GenerationConfig,
ModelConfig,
OutputConfig,
+ PromptConfig,
ServerConfig,
)
@@ -30,6 +31,7 @@ def app_config(tmp_path: Path) -> AppConfig:
),
output=OutputConfig(tmp_path / "outputs", False),
server=ServerConfig(),
+ prompt=PromptConfig(),
)
diff --git a/tests/test_config.py b/tests/test_config.py
index 9a6bf89..b0dfac0 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -195,3 +195,77 @@ def test_rejects_empty_host(tmp_path: Path) -> None:
)
with pytest.raises(ConfigError, match="host"):
load_config(path, validate_paths=False)
+
+
+def test_prompt_defaults_to_empty_when_omitted(tmp_path: Path) -> None:
+ path = tmp_path / "config.toml"
+ path.write_text(
+ f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n',
+ encoding="utf-8",
+ )
+ config = load_config(path, validate_paths=False)
+ assert config.prompt.positive == ""
+ assert config.prompt.negative == ""
+
+
+def test_prompt_reads_files_from_root_prompts(tmp_path: Path) -> None:
+ root = tmp_path / "models"
+ (root / "checkpoints").mkdir(parents=True)
+ (root / "checkpoints" / "base.safetensors").touch()
+ (root / "prompts").mkdir()
+ (root / "prompts" / "positive.txt").write_text("masterpiece, best quality", encoding="utf-8")
+ (root / "prompts" / "negative.txt").write_text("low quality, blurry", encoding="utf-8")
+ path = tmp_path / "config.toml"
+ path.write_text(
+ f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
+ '[prompt]\npositive_file = "positive.txt"\nnegative_file = "negative.txt"\n',
+ encoding="utf-8",
+ )
+ config = load_config(path)
+ assert config.prompt.positive == "masterpiece, best quality"
+ assert config.prompt.negative == "low quality, blurry"
+
+
+def test_prompt_rejects_path_traversal(tmp_path: Path) -> None:
+ root = tmp_path / "models"
+ (root / "checkpoints").mkdir(parents=True)
+ (root / "checkpoints" / "base.safetensors").touch()
+ path = tmp_path / "config.toml"
+ path.write_text(
+ f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
+ '[prompt]\npositive_file = "../escape.txt"\n',
+ encoding="utf-8",
+ )
+ with pytest.raises(ConfigError, match="file name"):
+ load_config(path, validate_paths=False)
+
+
+def test_prompt_rejects_missing_file(tmp_path: Path) -> None:
+ root = tmp_path / "models"
+ (root / "checkpoints").mkdir(parents=True)
+ (root / "checkpoints" / "base.safetensors").touch()
+ path = tmp_path / "config.toml"
+ path.write_text(
+ f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
+ '[prompt]\npositive_file = "absent.txt"\n',
+ encoding="utf-8",
+ )
+ with pytest.raises(ConfigError, match="prompt file"):
+ load_config(path, validate_paths=False)
+
+
+def test_prompt_accepts_only_positive(tmp_path: Path) -> None:
+ root = tmp_path / "models"
+ (root / "checkpoints").mkdir(parents=True)
+ (root / "checkpoints" / "base.safetensors").touch()
+ (root / "prompts").mkdir()
+ (root / "prompts" / "positive.txt").write_text("masterpiece", encoding="utf-8")
+ path = tmp_path / "config.toml"
+ path.write_text(
+ f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
+ '[prompt]\npositive_file = "positive.txt"\n',
+ encoding="utf-8",
+ )
+ config = load_config(path)
+ assert config.prompt.positive == "masterpiece"
+ assert config.prompt.negative == ""
diff --git a/tests/test_schema.py b/tests/test_schema.py
index 15a5f9b..51ec4a2 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -41,3 +41,65 @@ def test_inpaint_requires_both_images() -> None:
def test_arbitrary_dimensions_are_not_accepted() -> None:
with pytest.raises(InvalidRequestError, match="size"):
TextToImageRequest.create("cat", size="640x480")
+
+
+def test_base_prompts_are_combined_with_user_prompts() -> None:
+ request = TextToImageRequest.create(
+ "a cat",
+ "blurry",
+ base_positive="masterpiece, best quality",
+ base_negative="low quality, watermark",
+ )
+ assert request.positive_prompt == "masterpiece, best quality, a cat"
+ assert request.negative_prompt == "low quality, watermark\nblurry"
+
+
+def test_base_positive_only_does_not_add_trailing_separator() -> None:
+ request = TextToImageRequest.create(
+ "a cat",
+ base_positive="masterpiece",
+ )
+ assert request.positive_prompt == "masterpiece, a cat"
+ assert request.negative_prompt == ""
+
+
+def test_base_negative_only_does_not_add_leading_separator() -> None:
+ request = TextToImageRequest.create(
+ "a cat",
+ "blurry",
+ base_negative="low quality",
+ )
+ assert request.positive_prompt == "a cat"
+ assert request.negative_prompt == "low quality\nblurry"
+
+
+def test_empty_base_prompts_preserve_user_prompts() -> None:
+ request = TextToImageRequest.create("a cat", "blurry")
+ assert request.positive_prompt == "a cat"
+ assert request.negative_prompt == "blurry"
+
+
+def test_guided_request_combines_base_prompts() -> None:
+ request = GuidedImageRequest.create(
+ "a dancer",
+ "openpose",
+ "abc",
+ "deformed",
+ base_positive="masterpiece",
+ base_negative="low quality",
+ )
+ assert request.positive_prompt == "masterpiece, a dancer"
+ assert request.negative_prompt == "low quality\ndeformed"
+
+
+def test_inpaint_request_combines_base_prompts() -> None:
+ request = InpaintImageRequest.create(
+ "a vase",
+ "abc",
+ "def",
+ "artifacts",
+ base_positive="masterpiece",
+ base_negative="low quality",
+ )
+ assert request.positive_prompt == "masterpiece, a vase"
+ assert request.negative_prompt == "low quality\nartifacts"