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.3",
"repository": {
"url": "https://github.com/secfoo-com/secfoo",
"source": "github"
},
"packages": [
{
"registryType": "pypi",
"identifier": "secfoo",
"version": "0.3.3",
"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
78 changes: 73 additions & 5 deletions src/secfoo/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

import json
import os
import re
import sys
import urllib.error
Expand Down Expand Up @@ -79,27 +80,94 @@ def _toml_escape(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"')


def _env_credentials() -> tuple[str | None, str]:
key = (os.environ.get("SECFOO_CLOUD_API_KEY") or "").strip() or None
portal = (os.environ.get("SECFOO_CLOUD_PORTAL_URL") or "").strip() or DEFAULT_PORTAL_URL
return key, portal


def load_cloud_config(path: Path | None = None) -> CloudConfig | None:
"""Returns None if no cloud config exists yet (cloud sync is entirely
optional/additive) -- callers treat that as "not logged in", not an
error.

When `path` is omitted, `SECFOO_CLOUD_API_KEY` (plus optional
`SECFOO_CLOUD_PORTAL_URL`) takes precedence over `~/.secfoo/cloud.toml`
so CLI runs, `runner.py`, and `secfoo mcp serve` share one config source.
"""
path = path or CLOUD_CONFIG_PATH
if not path.exists():
if path is None:
env_key, env_portal = _env_credentials()
if env_key is not None:
return CloudConfig(
api_key=_require_ingest_key(env_key),
portal_url=_portal_origin(env_portal),
)
target = path or CLOUD_CONFIG_PATH
if not target.exists():
return None
try:
data = tomllib.loads(path.read_text(encoding="utf-8"))
data = tomllib.loads(target.read_text(encoding="utf-8"))
except tomllib.TOMLDecodeError as exc:
raise CloudError(f"{path}: invalid TOML: {exc}") from exc
raise CloudError(f"{target}: invalid TOML: {exc}") from exc
api_key = data.get("api_key")
if not api_key:
raise CloudError(f"{path}: missing api_key")
raise CloudError(f"{target}: missing api_key")
return CloudConfig(
api_key=_require_ingest_key(api_key),
portal_url=_portal_origin(data.get("portal_url") or DEFAULT_PORTAL_URL),
)


def resolve_cloud_status(path: Path | None = None) -> tuple[CloudConfig | None, dict[str, object]]:
"""Inspect env / `cloud.toml` without raising or exposing raw credentials.

Returns `(ingest_config_or_none, status_dict)` where `uploads_enabled` is
True strictly for valid `sfc_ingest_*` keys.
"""
raw_key, raw_url = _env_credentials()
if raw_key is None:
target = path or CLOUD_CONFIG_PATH
if target.exists():
try:
data = tomllib.loads(target.read_text(encoding="utf-8"))
except (OSError, tomllib.TOMLDecodeError):
data = {}
raw_key = str(data.get("api_key") or "").strip() or None
raw_url = str(data.get("portal_url") or "").strip() or DEFAULT_PORTAL_URL
if not raw_key:
return None, {
"mode": "local",
"uploads_enabled": False,
"key_kind": "none",
"portal_url": None,
}
try:
portal_url = _portal_origin(raw_url)
except CloudError:
portal_url = DEFAULT_PORTAL_URL
kind = key_kind(raw_key)
if kind == "ingest":
return CloudConfig(api_key=raw_key, portal_url=portal_url), {
"mode": "connected",
"uploads_enabled": True,
"key_kind": "ingest",
"portal_url": portal_url,
}
if kind == "view":
return None, {
"mode": "local",
"uploads_enabled": False,
"key_kind": "view",
"portal_url": portal_url,
}
return None, {
"mode": "local",
"uploads_enabled": False,
"key_kind": "invalid",
"portal_url": None,
}


def save_cloud_config(config: CloudConfig, path: Path | None = None) -> None:
path = path or CLOUD_CONFIG_PATH
path.parent.mkdir(parents=True, exist_ok=True)
Expand Down
Loading
Loading