-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
1521 lines (1346 loc) · 46.8 KB
/
Copy pathmcp_server.py
File metadata and controls
1521 lines (1346 loc) · 46.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Rafiki MCP Server — exposes the local Rafiki toolbox as MCP tools.
Tools:
rafiki_status Show local setup, env, and client config snippets
rafiki_generate Generate a single image
rafiki_batch Process an image-prompts.md file
rafiki_list_styles List available style presets
rafiki_usage Show local generation usage
rafiki_registry_search Search the asset registry
rafiki_registry_export Export the asset registry
rafiki_media_index Index configured multimedia roots
rafiki_media_search Search indexed multimedia assets
rafiki_subjects List indexed subject profiles
rafiki_jobs List local long-running job records
rafiki_job_status Return hardened status fields for a single job
rafiki_media_warnings Return warnings from the last media registry index run
rafiki_archive_health Report archive health
rafiki_viewer_rebuild Rebuild a project viewer
rafiki_library_rebuild Rebuild the master library viewer
rafiki_render Render HTML to PNG through the Node CLI
rafiki_canva_export Export a Canva upload bundle
rafiki_notion_export Dry-run or export approved images to Notion
rafiki_run Run any supported Rafiki CLI workflow
Install locally:
codex mcp add rafiki -- /path/to/rafiki/.venv/bin/python /path/to/rafiki/mcp_server.py
claude mcp add --scope user rafiki -- /path/to/rafiki/.venv/bin/python /path/to/rafiki/mcp_server.py
Or add to a generic MCP config:
"mcpServers": {
"rafiki": {
"command": "/path/to/rafiki/.venv/bin/python",
"args": ["/path/to/rafiki/mcp_server.py"]
}
}
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any
_ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(_ROOT))
def _load_dotenv(path) -> None:
if not path.exists():
return
import os
for line in path.read_text().splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, _, v = line.partition("=")
os.environ.setdefault(k.strip(), v.strip())
_load_dotenv(_ROOT / ".env")
from mcp.server.fastmcp import FastMCP
from lib.core import generate_image
from lib.batch import run_batch
from lib.prompts import ASPECT_RATIOS, parse_image_prompts_md
from lib.styles import load_styles
from lib.models import DEFAULT_IMAGE_MODEL, resolve_model
from lib.usage import load_usage_log
_CLI_SUBCOMMANDS = {
"archive-health",
"view",
"library",
"link-projects",
"import",
"approve",
"billing",
"canva-export",
"clean",
"deploy",
"media",
"notion-export",
"regen",
"registry",
"social-expand",
"style",
"subjects",
"train",
"video",
"floyo",
"keyframes",
}
_CLI_TOP_LEVEL_FLAGS = {
"--prompt",
"-p",
"--prompt-file",
"-f",
"--list-styles",
"--usage",
"--doctor",
"--render",
"--render-dir",
}
_CLI_BLOCKED_SUBCOMMANDS = {"serve"}
_CLI_MUTATING_SUBCOMMANDS = {
"approve",
"billing",
"canva-export",
"clean",
"deploy",
"notion-export",
"regen",
"social-expand",
"import",
"media",
"subjects",
"train",
"video",
"floyo",
"keyframes",
}
mcp = FastMCP(
"rafiki",
instructions=(
"AI image generation via Gemini and OpenAI. "
"Supports single images, batch prompt files (.md), style presets, "
"style composition (kk+bcai), model aliases (flash, gpt, pro), "
"parallel batch generation with run isolation, and a constrained "
"bridge to Rafiki's CLI workflows."
),
)
def _capture(fn, *args, **kwargs):
"""Run fn with stdout redirected to stderr (keeps MCP stdio clean)."""
old = sys.stdout
sys.stdout = sys.stderr
try:
return fn(*args, **kwargs)
finally:
sys.stdout = old
def _json(data: dict | list) -> str:
return json.dumps(data, indent=2, ensure_ascii=False)
def _normalise_aspect_ratio(value: str) -> str:
return ASPECT_RATIOS.get(value, value)
def _style_arg(value: str) -> str | None:
if not value:
return None
if value == "none":
return "none"
return value
def _ref_list(
*,
prompt_count: int,
reference_image: str = "",
reference_images: list[str] | None = None,
) -> list[str | None]:
refs = [p for p in (reference_images or []) if p]
if refs:
if len(refs) == 1:
return refs * prompt_count
if len(refs) != prompt_count:
raise ValueError(
f"reference_images has {len(refs)} path(s) but {prompt_count} prompt(s)"
)
return refs
if reference_image:
return [reference_image] * prompt_count
return [None] * prompt_count
def _trim(text: str, limit: int = 20000) -> str:
if len(text) <= limit:
return text
return text[:limit] + f"\n...[trimmed {len(text) - limit} chars]"
def _file_url(path: Path) -> str:
return path.resolve(strict=False).as_uri()
def _path_info(path: Path) -> dict[str, str]:
resolved = path.resolve(strict=False)
return {"path": str(resolved), "url": resolved.as_uri()}
def _error_payload(tool: str, error: str, **extra: Any) -> str:
return _json({
"success": False,
"ok": False,
"tool": tool,
"error": error,
**extra,
})
def _run_command(
command: list[str],
timeout_seconds: int,
*,
mutating: bool,
external: bool = False,
) -> dict:
timeout = max(1, min(int(timeout_seconds), 3600))
try:
proc = subprocess.run(
command,
cwd=str(_ROOT),
env=os.environ.copy(),
text=True,
capture_output=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as e:
return {
"success": False,
"ok": False,
"timeout": True,
"timeout_seconds": timeout,
"command": command,
"cwd": str(_ROOT),
"mutating": mutating,
"external": external,
"stdout": _trim(e.stdout or ""),
"stderr": _trim(e.stderr or ""),
}
stdout = proc.stdout or ""
parsed_stdout = None
try:
parsed_stdout = json.loads(stdout)
except json.JSONDecodeError:
pass
return {
"success": proc.returncode == 0,
"ok": proc.returncode == 0,
"exit_code": proc.returncode,
"command": command,
"cwd": str(_ROOT),
"mutating": mutating,
"external": external,
"stdout": _trim(stdout),
"stderr": _trim(proc.stderr or ""),
"json": parsed_stdout,
}
def _validate_cli_args(args: list[str]) -> tuple[bool, str]:
if not args:
return False, "args is required"
for arg in args:
if not isinstance(arg, str):
return False, "all args must be strings"
if "\x00" in arg:
return False, "args may not contain NUL bytes"
first = args[0]
if first in _CLI_BLOCKED_SUBCOMMANDS:
return False, "`serve` is long-running; start the portal outside MCP"
if first in _CLI_SUBCOMMANDS:
return True, ""
if first.startswith("-") and first in _CLI_TOP_LEVEL_FLAGS:
return True, ""
if any(flag in args for flag in _CLI_TOP_LEVEL_FLAGS):
return True, ""
if first.endswith((".md", ".markdown")):
return True, ""
return False, (
"unsupported Rafiki CLI invocation; pass generate.py arguments only, "
"such as ['--usage'], ['view', 'project'], or ['--render', 'card.html']"
)
def _run_generate_py(args: list[str], timeout_seconds: int) -> dict:
ok, error = _validate_cli_args(args)
if not ok:
return {"success": False, "ok": False, "error": error, "args": args}
if args[0] in {"--render", "--render-dir"}:
return _run_node_rafiki(args, timeout_seconds, mutating=True)
command = [sys.executable, str(_ROOT / "generate.py"), *args]
action = args[0]
mutating = action in _CLI_MUTATING_SUBCOMMANDS
if action == "billing" and len(args) > 1 and args[1] == "summary":
mutating = False
return _run_command(
command,
timeout_seconds,
mutating=mutating,
)
def _run_node_rafiki(
args: list[str],
timeout_seconds: int,
*,
mutating: bool,
) -> dict:
return _run_command(
["node", str(_ROOT / "index.js"), *args],
timeout_seconds,
mutating=mutating,
)
def _resolve_project_dir(project: str, output_root: str = "") -> Path:
project_path = Path(project)
if project_path.is_absolute() or project_path.exists():
return project_path.resolve(strict=False)
root = Path(output_root) if output_root else _ROOT / "output"
return (root / project).resolve(strict=False)
def _default_output_root(output_root: str = "") -> Path:
return Path(output_root).resolve(strict=False) if output_root else (_ROOT / "output").resolve(strict=False)
def _library_preview(output_root: str = "") -> dict:
root = _default_output_root(output_root)
if not root.is_dir():
return {
"success": False,
"ok": False,
"error": f"Output root not found: {root}",
"output_root": str(root),
"library_path": str(root / "library.html"),
"library_url": _file_url(root / "library.html"),
}
from lib.renderers.library import _records_from_registry
records = _records_from_registry(root)
projects = {record.get("project", "") for record in records if record.get("project")}
present = sum(1 for record in records if record.get("ok"))
library_path = root / "library.html"
return {
"success": True,
"ok": True,
"output_root": str(root),
"library_path": str(library_path),
"library_url": _file_url(library_path),
"project_count": len(projects),
"image_count": len(records),
"present_image_count": present,
"missing_image_count": len(records) - present,
}
def _viewer_preview(
project: str,
*,
all_runs: bool,
approved: bool,
output_root: str = "",
) -> dict:
project_dir = _resolve_project_dir(project, output_root)
if not project_dir.is_dir():
return {
"success": False,
"error": f"Project not found: {project_dir}",
"project": project,
"project_dir": str(project_dir),
}
if approved:
viewer_path = project_dir / "approved" / "viewer.html"
approved_dir = project_dir / "approved"
image_count = len(list(approved_dir.glob("*.png"))) if approved_dir.exists() else 0
return {
"success": approved_dir.is_dir(),
"error": "" if approved_dir.is_dir() else f"Approved set not found: {approved_dir}",
"project": project,
"project_dir": str(project_dir),
"viewer_path": str(viewer_path),
"viewer_url": _file_url(viewer_path),
"run_count": 0,
"image_count": image_count,
"run_viewer_paths": [],
"run_viewer_urls": [],
}
run_dirs = sorted(p for p in project_dir.glob("run-*") if p.is_dir())
image_count = 0
for run_dir in run_dirs:
try:
data = json.loads((run_dir / "run.json").read_text(encoding="utf-8"))
except Exception:
continue
image_count += len(data.get("images", []))
viewer_path = project_dir / "viewer.html"
run_viewer_paths = [str(run_dir / "viewer.html") for run_dir in run_dirs] if all_runs else []
run_viewer_urls = [_file_url(run_dir / "viewer.html") for run_dir in run_dirs] if all_runs else []
return {
"success": True,
"project": project,
"project_dir": str(project_dir),
"viewer_path": str(viewer_path),
"viewer_url": _file_url(viewer_path),
"run_count": len(run_dirs),
"image_count": image_count,
"run_viewer_paths": run_viewer_paths,
"run_viewer_urls": run_viewer_urls,
}
def _render_targets(html_path: str = "", html_dir: str = "") -> tuple[list[Path], str]:
if bool(html_path) == bool(html_dir):
return [], "Pass exactly one of html_path or html_dir"
if html_path:
path = Path(html_path)
if not path.exists():
return [], f"HTML file not found: {path}"
return [path.resolve()], ""
directory = Path(html_dir)
if not directory.is_dir():
return [], f"HTML directory not found: {directory}"
files = sorted(path.resolve() for path in directory.iterdir() if path.suffix == ".html")
if not files:
return [], f"No HTML files found in {directory}"
return files, ""
def _canva_preview(
project: str,
*,
output_dir: str = "",
no_zip: bool = False,
output_root: str = "",
) -> dict:
from lib.exporters import canva
root = Path(output_root) if output_root else canva.DEFAULT_OUTPUT_ROOT
project_dir = root / project
if not project_dir.is_dir():
return {"success": False, "error": f"Project not found: {project_dir}"}
try:
source = canva._resolve_source(project_dir)
except FileNotFoundError as e:
return {"success": False, "error": str(e)}
images = sorted(source.glob("*.png"))
export_dir = Path(output_dir) if output_dir else project_dir / "canva-export"
result_path = export_dir if no_zip else export_dir.with_suffix(".zip")
return {
"success": True,
"project": project,
"project_dir": str(project_dir.resolve(strict=False)),
"source_dir": str(source.resolve(strict=False)),
"output_dir": str(export_dir.resolve(strict=False)),
"result_path": str(result_path.resolve(strict=False)),
"result_url": _file_url(result_path),
"count": len(images),
"image_count": len(images),
"zip": not no_zip,
}
@mcp.tool()
def rafiki_status() -> str:
"""Report the local Rafiki MCP setup without exposing secret values."""
python_bin = sys.executable
server_path = str(_ROOT / "mcp_server.py")
result = {
"success": True,
"ok": True,
"tool": "rafiki_status",
"repo_root": str(_ROOT),
"python": python_bin,
"mcp_server": server_path,
"env": {
"GOOGLE_API_KEY": bool(os.environ.get("GOOGLE_API_KEY")),
"OPENAI_API_KEY": bool(os.environ.get("OPENAI_API_KEY")),
"REPLICATE_API_TOKEN": bool(os.environ.get("REPLICATE_API_TOKEN")),
"NOTION_API_KEY": bool(os.environ.get("NOTION_API_KEY")),
"NOTION_DATABASE_ID": bool(os.environ.get("NOTION_DATABASE_ID")),
},
"common_tools": [
"rafiki_generate",
"rafiki_batch",
"rafiki_list_styles",
"rafiki_usage",
"rafiki_registry_search",
"rafiki_registry_export",
"rafiki_media_index",
"rafiki_media_search",
"rafiki_subjects",
"rafiki_jobs",
"rafiki_job_status",
"rafiki_media_warnings",
"rafiki_train_lora",
"rafiki_video_generate",
"rafiki_floyo_generate",
"rafiki_keyframes_generate",
"rafiki_style_anchors",
"rafiki_archive_health",
"rafiki_viewer_rebuild",
"rafiki_library_rebuild",
"rafiki_render",
"rafiki_canva_export",
"rafiki_notion_export",
"rafiki_run",
],
"cli_bridge_subcommands": sorted(_CLI_SUBCOMMANDS),
"blocked_cli_subcommands": sorted(_CLI_BLOCKED_SUBCOMMANDS),
"codex_add_command": (
f"codex mcp add rafiki -- {python_bin} {server_path}"
),
"claude_add_command": (
f"claude mcp add --scope user rafiki -- {python_bin} {server_path}"
),
}
return _json(result)
@mcp.tool()
def rafiki_generate(
prompt: str,
output_path: str = "output.png",
model: str = DEFAULT_IMAGE_MODEL,
aspect_ratio: str = "16:9",
resolution: str = "1K",
quality: str = "high",
style: str = "kk",
reference_image: str = "",
global_reference_images: list[str] | None = None,
reference_role: str = "style",
composition_references: list[str] | None = None,
dry_run: bool = False,
) -> str:
"""Generate a single image using Rafiki.
Args:
prompt: Text description of the desired image.
output_path: Where to save the PNG (absolute or relative to cwd).
model: Model ID or alias. Aliases: flash/nano/pro (Gemini), gpt/gpt1/dalle3 (OpenAI).
aspect_ratio: 16:9 | 1:1 | 9:16 | linkedin | instagram | story | square.
resolution: 1K | 2K | 4K — Gemini Pro only.
quality: low | medium | high — OpenAI only.
style: kk | hopecode | bcai | upgrade | none | composed (e.g. kk+bcai).
reference_image: Optional path to a reference image.
global_reference_images: Additional reference image paths reused for this generation.
reference_role: style | brand | mockup.
composition_references: Extra reference paths for mockup composition.
dry_run: Preview without calling any API.
Returns:
JSON string with success, output_path, model, and message.
"""
resolved_model = resolve_model(model)
resolved_style = _style_arg(style)
resolved_aspect_ratio = _normalise_aspect_ratio(aspect_ratio)
success = _capture(
generate_image,
prompt=prompt,
output_path=output_path,
model=resolved_model,
aspect_ratio=resolved_aspect_ratio,
resolution=resolution,
quality=quality,
style=resolved_style,
reference_image=reference_image or None,
reference_images=global_reference_images,
reference_role=reference_role,
composition_references=composition_references,
dry_run=dry_run,
)
result: dict = {
"success": success,
"ok": success,
"tool": "rafiki_generate",
"output_path": output_path,
"output_url": _file_url(Path(output_path)),
"model": resolved_model,
"aspect_ratio": resolved_aspect_ratio,
"resolution": resolution,
"style": style,
"reference_image": reference_image,
"global_reference_images": global_reference_images or [],
"reference_role": reference_role,
"dry_run": dry_run,
"prompt_preview": prompt[:120],
}
if success and not dry_run:
result["message"] = f"Image saved to {output_path}"
elif dry_run:
result["message"] = "Dry run — no API call made"
else:
result["message"] = "Generation failed — check stderr for details"
return json.dumps(result, indent=2)
@mcp.tool()
def rafiki_batch(
prompt_file: str,
output_dir: str = "",
model: str = DEFAULT_IMAGE_MODEL,
aspect_ratio: str = "16:9",
resolution: str = "1K",
quality: str = "high",
style: str = "kk",
reference_image: str = "",
reference_images: list[str] | None = None,
global_reference_images: list[str] | None = None,
reference_role: str = "style",
composition_references: list[str] | None = None,
workers: int = 1,
dry_run: bool = False,
no_viewer: bool = False,
) -> str:
"""Process an image-prompts.md file and generate all images in the batch.
Creates a timestamped run-*/ subdirectory so previous runs are never
overwritten. Generates both a per-run viewer and a project comparison viewer.
Args:
prompt_file: Path to the image-prompts.md file.
output_dir: Directory for output images (default: <prompt_file_dir>/images/).
model: Model ID or alias for all images.
aspect_ratio: Default aspect ratio (per-prompt overrides are respected).
resolution: Default resolution (Gemini Pro only).
quality: Quality level (OpenAI only).
style: Style preset or composed spec (e.g. kk+bcai). 'none' = no style.
reference_image: Optional reference image reused for every prompt.
reference_images: Optional per-prompt reference image paths.
global_reference_images: Additional reference image paths reused for every prompt.
reference_role: style | brand | mockup.
composition_references: Extra reference paths for mockup composition.
workers: Parallel generation workers (1 = sequential, 4 = fast).
dry_run: Preview without generating any images.
no_viewer: Skip generating viewer.html gallery.
Returns:
JSON string with success, counts, run_dir, viewer_path, and per-image results.
"""
prompt_path = Path(prompt_file)
if not prompt_path.exists() and not dry_run:
return _error_payload(
"rafiki_batch",
f"Prompt file not found: {prompt_file}",
mutating=False,
external=False,
dry_run=dry_run,
)
prompts = _capture(parse_image_prompts_md, str(prompt_path)) if prompt_path.exists() else []
out_dir = Path(output_dir) if output_dir else prompt_path.parent / "images"
resolved_model = resolve_model(model)
resolved_style = _style_arg(style)
resolved_aspect_ratio = _normalise_aspect_ratio(aspect_ratio)
try:
ref_paths = _ref_list(
prompt_count=len(prompts),
reference_image=reference_image,
reference_images=reference_images,
)
except ValueError as e:
return _error_payload(
"rafiki_batch",
str(e),
mutating=False,
external=False,
dry_run=dry_run,
)
result = _capture(
run_batch,
prompts=prompts,
project_dir=out_dir,
model=resolved_model,
aspect_ratio=resolved_aspect_ratio,
resolution=resolution,
quality=quality,
style=resolved_style,
ref_paths=ref_paths,
global_reference_images=global_reference_images,
reference_role=reference_role,
composition_references=composition_references,
workers=workers,
dry_run=dry_run,
generate_viewer_html=not no_viewer,
prompt_file=str(prompt_path),
invocation_source="mcp",
)
return json.dumps({
"success": result.success,
"ok": result.success,
"tool": "rafiki_batch",
"mode": "batch",
"dry_run": dry_run,
"generated": result.success_count,
"total": result.total,
"project_dir": str(result.project_dir),
"run_dir": str(result.run_dir),
"run_id": result.run_id,
"viewer_path": result.viewer_path,
"viewer_url": _file_url(Path(result.viewer_path)) if result.viewer_path else "",
"model": resolved_model,
"aspect_ratio": resolved_aspect_ratio,
"resolution": resolution,
"style": style,
"global_reference_images": global_reference_images or [],
"images": result.images,
})
@mcp.tool()
def rafiki_list_styles() -> str:
"""List all available Rafiki style presets with descriptions.
Returns:
JSON mapping style names to {description, default}.
Tip: compose styles with '+', e.g. kk+bcai.
"""
styles = load_styles()
result = {
"success": True,
"ok": True,
"tool": "rafiki_list_styles",
"count": len(styles),
"styles": {
name: {
"description": cfg.get("description", ""),
"default": cfg.get("default", False),
}
for name, cfg in styles.items()
},
"_tip": "Compose styles with '+', e.g. style='kk+bcai'",
}
return _json(result)
@mcp.tool()
def rafiki_usage() -> str:
"""Return local Rafiki usage history and recent generations."""
return _json({
"success": True,
"ok": True,
"tool": "rafiki_usage",
**load_usage_log(),
})
@mcp.tool()
def rafiki_registry_search(query: str, limit: int = 20) -> str:
"""Search the persisted Rafiki asset registry.
Args:
query: Case-insensitive substring matched against title, caption, and tags.
limit: Maximum number of results to return, capped at 100.
"""
from lib import registry
safe_limit = max(1, min(int(limit), 100))
results = [entry.to_dict() for entry in registry.search(query)[:safe_limit]]
return _json({
"success": True,
"ok": True,
"tool": "rafiki_registry_search",
"query": query,
"limit": safe_limit,
"count": len(results),
"mutating": False,
"external": False,
"results": results,
})
@mcp.tool()
def rafiki_registry_export(format: str = "csv", dry_run: bool = False) -> str:
"""Export the persisted asset registry to CSV or JSON.
Args:
format: csv | json.
dry_run: Preview the export path and count without writing files.
"""
from lib import registry
fmt = format.lower()
if fmt not in {"csv", "json"}:
return _error_payload(
"rafiki_registry_export",
"format must be 'csv' or 'json'",
format=format,
dry_run=dry_run,
mutating=False,
external=False,
)
entries = registry._load_registry()
path = registry.REGISTRY_CSV if fmt == "csv" else registry.REGISTRY_JSON
if dry_run:
return _json({
"success": True,
"ok": True,
"tool": "rafiki_registry_export",
"format": fmt,
"dry_run": True,
"mutating": False,
"external": False,
"count": len(entries),
**_path_info(path),
})
try:
exported = registry.export(format=fmt)
except ValueError as e:
return _error_payload(
"rafiki_registry_export",
str(e),
format=format,
dry_run=dry_run,
mutating=False,
external=False,
)
return _json({
"success": True,
"ok": True,
"tool": "rafiki_registry_export",
"format": fmt,
"dry_run": False,
"mutating": True,
"external": False,
"count": len(entries),
**_path_info(exported),
})
@mcp.tool()
def rafiki_media_index(
root: str = "",
key: str = "alex-samuel",
importer: str = "alex-samuel",
dry_run: bool = True,
) -> str:
"""Index configured multimedia roots or one explicit local root."""
from lib import media_registry
from lib.media_roots import MediaRoot
if importer not in {"alex-samuel", "generic"}:
return _error_payload("rafiki_media_index", "importer must be alex-samuel or generic")
roots = None
if root:
roots = {key: MediaRoot(key=key, path=Path(root).expanduser(), importer=importer)}
payload = media_registry.index(roots=roots, write=not dry_run)
return _json({
"success": True,
"ok": True,
"tool": "rafiki_media_index",
"dry_run": dry_run,
"mutating": not dry_run,
"external": False,
"registry_path": str(media_registry.MEDIA_REGISTRY_JSON),
"registry_url": _file_url(media_registry.MEDIA_REGISTRY_JSON),
**payload,
})
@mcp.tool()
def rafiki_media_search(query: str = "", kind: str = "", collection: str = "", limit: int = 50) -> str:
"""Search the multimedia registry for images, videos, audio, styles, and manifests."""
from lib import media_registry
safe_limit = max(1, min(int(limit), 200))
results = [entry.to_dict() for entry in media_registry.search(query, kind=kind, collection=collection)[:safe_limit]]
return _json({
"success": True,
"ok": True,
"tool": "rafiki_media_search",
"query": query,
"kind": kind,
"collection": collection,
"limit": safe_limit,
"count": len(results),
"mutating": False,
"external": False,
"results": results,
})
@mcp.tool()
def rafiki_subjects(subject: str = "") -> str:
"""List indexed subject profiles, or return one subject when subject is passed."""
from lib import media_registry
profiles = [profile.to_dict() for profile in media_registry.subjects()]
if subject:
profiles = [profile for profile in profiles if profile.get("key") == subject]
return _json({
"success": bool(profiles) or not subject,
"ok": bool(profiles) or not subject,
"tool": "rafiki_subjects",
"subject": subject,
"count": len(profiles),
"mutating": False,
"external": False,
"subjects": profiles,
})
@mcp.tool()
def rafiki_jobs() -> str:
"""List local dry-run/executed job records stored under data/jobs."""
from lib.jobs import list_jobs
jobs = list_jobs()
return _json({
"success": True,
"ok": True,
"tool": "rafiki_jobs",
"count": len(jobs),
"mutating": False,
"external": False,
"jobs": jobs,
})
@mcp.tool()
def rafiki_train_lora(
subject: str,
input_images_url: str = "",
execute: bool = False,
output_root: str = "",
) -> str:
"""Plan or launch a Replicate FLUX LoRA training job. Defaults to dry-run."""
from lib.training import plan_lora_training
result = plan_lora_training(
subject=subject,
input_images_url=input_images_url,
execute=execute,
output_root=Path(output_root) if output_root else None,
)
return _json({
"success": True,
"ok": True,
"tool": "rafiki_train_lora",
"mutating": True,
"external": execute,
**result,
})
@mcp.tool()
def rafiki_video_generate(
storyboard: str,
model: str = "wan-video/wan2.1-with-lora",
execute: bool = False,
output_root: str = "",
) -> str:
"""Plan or launch a storyboard video generation job. Defaults to dry-run."""
from lib.video_jobs import plan_video_generation
result = plan_video_generation(
storyboard_path=Path(storyboard),
model=model,
execute=execute,
output_root=Path(output_root) if output_root else None,
)
return _json({
"success": True,
"ok": True,
"tool": "rafiki_video_generate",
"mutating": True,
"external": execute,
**result,
})
@mcp.tool()
def rafiki_floyo_generate(
workflow: str = "wan22_endframe",
start_image: str = "",
end_image: str = "",
prompt: str = "",
project: str = "floyo",
execute: bool = False,
output_root: str = "",