Skip to content
Open
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
143 changes: 143 additions & 0 deletions scripts/build_plugins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Generate or verify agent marketplace plugin skills from one source of truth (#224).

Reads built-in skills from `src/secfoo/skills/definitions/*.md` and renders platform
files cleanly without duplicating skill prompts across plugin directories.

Usage:
python scripts/build_plugins.py [--target all|claude|cursor] [--check] [--mcpb]
"""

from __future__ import annotations

import argparse
import io
import json
import sys
import zipfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))

from secfoo.__about__ import __version__
from secfoo.skills.loader import Skill, load_all_skills
from secfoo.skills.renderer import (
OUTPUT_CONTRACT,
SAFETY_PREAMBLE,
SKILL_OUTPUT_CONTRACTS,
)

CLAUDE_SKILLS_DIR = ROOT / "plugins" / "secfoo" / "skills"
CURSOR_SKILLS_DIR = ROOT / "plugins" / "cursor-secfoo" / "skills"
MCPB_MANIFEST_PATH = ROOT / "packaging" / "mcpb" / "manifest.json"
DEFAULT_MCPB_OUT = ROOT / "dist" / f"secfoo-{__version__}.mcpb"


def _builtin_skills() -> list[Skill]:
return sorted((s for s in load_all_skills().values() if s.is_builtin), key=lambda s: s.id)


def render_skill_file(skill: Skill, *, host_label: str) -> str:
"""Render one canonical `SKILL.md` for an external agent host from its definition."""
contract = SKILL_OUTPUT_CONTRACTS.get(skill.output_type) or OUTPUT_CONTRACT.format(skill_name=skill.name)
desc = " ".join(skill.description.splitlines()).strip()
rendered = (
"---\n"
f"name: {skill.id}\n"
f"description: {json.dumps(desc)}\n"
"---\n\n"
f"<!-- Generated by scripts/build_plugins.py from src/secfoo/skills/definitions/{skill.id}.md for {host_label}. -->\n\n"
f"{SAFETY_PREAMBLE}\n\n"
f"## Skill: {skill.name}\n"
f"{skill.body.strip()}\n\n"
"## Persistence\n"
f"Once you complete the analysis, submit the full Markdown report via the `secfoo` MCP tool "
f"`submit_report(skill=\"{skill.id}\", target=\"<project-root-or-url>\", report=...)` so findings "
"appear in `secfoo serve` (and sync to the portal automatically when an ingest key is configured).\n\n"
f"{contract.strip()}\n"
)
return rendered.replace("\r\n", "\n")


def expected_outputs(target: str) -> dict[Path, str]:
"""Return mapping of `{output_path: expected_content}` for existing/requested targets."""
outputs: dict[Path, str] = {}
skills = _builtin_skills()
if target in ("all", "claude") and (CLAUDE_SKILLS_DIR.parent.exists() or target == "claude"):
for skill in skills:
outputs[CLAUDE_SKILLS_DIR / skill.id / "SKILL.md"] = render_skill_file(skill, host_label="Claude Code")
if target in ("all", "cursor") and (CURSOR_SKILLS_DIR.parent.exists() or target == "cursor"):
for skill in skills:
outputs[CURSOR_SKILLS_DIR / skill.id / "SKILL.md"] = render_skill_file(skill, host_label="Cursor")
return outputs


def build_mcpb_archive(output_path: Path = DEFAULT_MCPB_OUT) -> Path:
"""Package `packaging/mcpb/` into a `.mcpb` ZIP archive for Claude Desktop."""
manifest_dir = MCPB_MANIFEST_PATH.parent
if not MCPB_MANIFEST_PATH.is_file():
raise FileNotFoundError(f"Missing MCPB manifest: {MCPB_MANIFEST_PATH}")
manifest_data = json.loads(MCPB_MANIFEST_PATH.read_text(encoding="utf-8"))
output_path.parent.mkdir(parents=True, exist_ok=True)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for file_path in sorted(manifest_dir.rglob("*")):
if file_path.is_file():
arcname = file_path.relative_to(manifest_dir).as_posix()
if arcname == "manifest.json":
continue
zf.writestr(arcname, file_path.read_bytes())
# Ensure manifest stays normalized and cleanly written once.
zf.writestr("manifest.json", json.dumps(manifest_data, indent=2) + "\n")
output_path.write_bytes(buf.getvalue())
return output_path


def _rel(path: Path) -> Path:
return path.relative_to(ROOT) if path.is_relative_to(ROOT) else path


def run(*, target: str = "all", check: bool = False, mcpb: bool = False, mcpb_out: Path | None = None) -> int:
outputs = expected_outputs(target)
if check:
drift: list[str] = []
for path, expected in outputs.items():
if not path.is_file():
drift.append(f"missing {_rel(path)}")
continue
actual = path.read_text(encoding="utf-8").replace("\r\n", "\n")
if actual != expected:
drift.append(f"stale {_rel(path)}")
if drift:
print("Plugin files out of date with src/secfoo/skills/definitions/:")
for item in drift:
print(f" - {item}")
return 1
print(f"Verified {len(outputs)} plugin skill file(s) match source definitions.")
return 0

for path, content in outputs.items():
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="\n") as handle:
handle.write(content)
print(f"Generated {len(outputs)} plugin skill file(s).")
if mcpb:
built = build_mcpb_archive(mcpb_out or DEFAULT_MCPB_OUT)
print(f"Built MCPB extension bundle: {_rel(built)}")
return 0


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Build or validate Secfoo editor plugin files.")
parser.add_argument("--target", choices=("all", "claude", "cursor"), default="all")
parser.add_argument("--check", action="store_true", help="Exit non-zero if generated files are out of date.")
parser.add_argument("--mcpb", action="store_true", help="Build Claude Desktop .mcpb bundle.")
parser.add_argument("--mcpb-out", type=Path, default=None, help="Optional output path for .mcpb archive.")
args = parser.parse_args(argv)
return run(target=args.target, check=args.check, mcpb=args.mcpb, mcpb_out=args.mcpb_out)


if __name__ == "__main__":
raise SystemExit(main())
40 changes: 40 additions & 0 deletions server.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "com.secfoo/secfoo",
"title": "Secfoo Security Review MCP Server",
"description": "AI-powered SAST, SCA reachability, secret scanning, threat modeling, and architecture review. Local by default; optional API key syncs to app.secfoo.com.",
"version": "0.3.2",
"repository": {
"url": "https://github.com/secfoo-com/secfoo",
"source": "github"
},
"packages": [
{
"registryType": "pypi",
"identifier": "secfoo",
"version": "0.3.2",
"runtimeHint": "uvx",
"transport": {
"type": "stdio"
},
"packageArguments": [
{
"type": "positional",
"value": "mcp"
},
{
"type": "positional",
"value": "serve"
}
],
"environmentVariables": [
{
"name": "SECFOO_CLOUD_API_KEY",
"description": "Optional Secfoo ingest key (sfc_ingest_...) to sync submitted runs to app.secfoo.com. Omit for local-only mode.",
"isRequired": false,
"isSecret": true
}
]
}
]
}
15 changes: 15 additions & 0 deletions src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3131,6 +3131,21 @@ def mcp_sync(
raise typer.Exit(code=1)


@mcp_app.command(name="serve")
def mcp_serve(
root: list[Path] | None = typer.Option(
None,
"--root",
"-r",
help="Workspace root directory allowed for local targets (defaults to host MCP roots or CWD).",
),
) -> None:
"""Run Secfoo's stdio MCP server for Claude Code, Claude Desktop, and Cursor."""
from secfoo.mcp_server import serve

serve(allowed_roots=root)


def main() -> None:
app()

Expand Down
Loading
Loading