CLI Reference¶
This document provides a comprehensive reference for the cytoscnpy command-line interface.
Command Syntax¶
Main Options¶
Input & Output¶
[paths]: One or more paths to analyze (files or directories). If omitted, CytoScnPy defaults to the current working directory.--root <PATH>: Explicitly sets the project root. This is highly recommended for CI/CD environments to ensure that path-based security containment is correctly applied and that relative imports are resolved consistently. When--rootis used, positional[paths]are not allowed. It also ensures that reports (SARIF, GitLab, etc.) use paths relative to this root.--format <FORMAT>: Specifies the output format. Supported values:text(default),json,junit,github,gitlab,markdown,sarif,grouped(deprecated).--json: Format the result as a raw JSON object. Shorthand for--format json. This is ideal for piping into tools likejqor for consumption by CI/CD scripts.--verbose,-v: Prints detailed logs during the analysis process, including which files are being scanned and any non-fatal issues encountered.--quiet: Minimalist output. Only the final summary table (or JSON) is displayed, suppressing the per-file findings table.-
--fail-on-any: Enables all supported failure gates and exits with code1if any actionable finding is detected. For unused code, it uses zero tolerance unless--fail-threshold, config, orCYTOSCNPY_FAIL_THRESHOLDsupplies a threshold. Configured--max-lines,--max-args, and--max-nestinglimits (or their configuration equivalents) enable quality analysis and fail the scan when their corresponding rules report a violation. -
--fail-on-quality: Causes the process to exit with code1if any code quality issues (like high complexity or deep nesting) are detected. --fail-on-secrets: Enables secret scanning if needed and exits with code1if any secret findings are detected.--fail-on-danger: Enables dangerous-code/taint scanning if needed and exits with code1if any danger or taint findings are detected.--fail-on-missing-deps: Enables dependency analysis if needed and exits with code1if any missing dependency findings are detected.--fail-on-unused-deps: Enables dependency analysis if needed and exits with code1if any unused dependency findings are detected.--html: Generates a self-contained, interactive HTML report. Each source receives a distinct file-view filename, shared by metrics, issue, and clone links. Note that this feature may require additional dependencies and automatically enables quality scanning.--client <CLIENT>: Identify the calling editor/client. Currently onlyvscodeis supported. Whenvscodeis set, project config from.cytoscnpy.tomlorpyproject.tomlis still honored, and explicit VS Code settings are passed as CLI flags that override matching thresholds.
Scan Types¶
--secrets,-s: Actively scans for high-entropy strings, API keys, and hardcoded credentials. It checks variables, strings, and even comments (depending on configuration).--danger,-d: Enables security scanning for dangerous patterns likeeval(),exec(), and insecure temporary file creation. It also activates taint analysis to track user-controlled data flowing into dangerous sinks (e.g., SQL injection or command injection points). See Dangerous Code for a full rule list.--quality,-q: Runs code quality checks including Cyclomatic Complexity, Maintainability Index, block nesting depth, and function length/argument counts.--no-dead,-n: Skips the default dead code detection. Use this if you only care about security vulnerabilities or quality metrics and want to speed up the analysis.--deps: Analyze unused and missing dependencies by cross-referencingpyproject.toml/requirements.txtagainst imports found in the code. Opt-in — not run by default.
Analysis Configuration¶
--confidence <N>,-c: Sets a minimum confidence threshold (0-100). CytoScnPy uses a scoring system for dead code; setting this to80, for example, will suppress "noisy" findings where the tool isn't certain the code is unused.--exclude-folders <DIRS>: Exclude specific folders from analysis. Can be used multiple times.--include-folders <DIRS>: Force-include specific folders in analysis. Can be used multiple times.--include-tests: By default, CytoScnPy excludestests/,test/,test_*.py,*_test.py,conftest.py, andnoxfile.pyfrom main analysis,deslop, metrics, file statistics, and clone detection. Use this flag to include them. Dependency analysis still scans test/dev files intentionally so it can distinguish development-only imports from production imports.--include-ipynb: Enables scanning of Jupyter Notebook files. CytoScnPy extracts the Python code from cells and analyzes it as a virtual module.--ipynb-cells: When combined with--include-ipynb, this reports findings with cell numbers instead of just line numbers, making it easier to locate issues in the Notebook UI.--clones: Activates duplicate code detection. It uses AST-based hashing to find code blocks that are identical or nearly identical across your codebase.--clone-similarity <N>: Sets the similarity threshold for clone detection (0.0 to 1.0). A value of1.0finds only exact duplicates; a lower value like0.8(default) finds similar logic that might be refactored.--fix: Enables "Dead Code Auto-Fix" mode. By default, this is a dry-run—it will show you exactly what code would be removed without touching your files.--apply,-a: Executes the changes suggested by--fix. Warning: This modifies your source code. It is highly recommended to run with--fixfirst to review changes, and to have a clean Git state before applying.--fixtargets: functions, methods, classes, imports, and unused variables.--fixalways enforces a minimum confidence floor of 80% for safety, even if--confidenceis set lower.- In dry-run mode with
--json, CytoScnPy emits a deterministic JSON fix plan (kind: "dead_code_fix_plan") suitable for editor/CI consumption. - Nested definitions are located by their exact source position.
- Removing every statement from a required block inserts
pass; semicolon-separated statements remain valid. - Unused variables receive an available discard name (
_,_unused, or a numbered variant) without overwriting existing bindings or references. - Both previews and applied edits are validated as Python. Unreadable sources, missing definitions, conflicting edits, and invalid generated code fail with the file path and error context.
--make-whitelist: Generates a Python whitelist from currently detected unused symbols.--whitelist <PATH>: Loads one or more whitelist files to suppress matching dead-code findings.
CI/CD Failure Gates¶
The main analysis exits with code 1 when parsing or reading errors leave a scan incomplete, including when no failure flags are supplied. JSON reports retain the parse_errors list and any findings from files that were scanned. Directory traversal errors are included in that list, so unreadable subdirectories also fail the scan. Dead-code fixing (preview or apply) is refused when any parsing/read error makes the scan incomplete.
These flags allow you to set strict gates for CI/CD. If any enabled gate fails, CytoScnPy exits with code 1. Failure gates that depend on optional scans enable those scans automatically.
--fail-on-any: Convenience gate for CI. Implies quality, secrets, danger/taint, missing dependency, and unused dependency failure gates. For unused code, it defaults to--fail-threshold 0.0unless an explicit threshold is supplied.--fail-threshold <N>: Exit with 1 if the total percentage of unused code exceedsN. CLI, config, andCYTOSCNPY_FAIL_THRESHOLDvalues must be finite numbers from0through100(in that precedence order).--max-complexity <N>: Sets the maximum allowed Cyclomatic Complexity (standard is often10).--min-mi <N>: Sets the minimum allowed Maintainability Index for each file (usually40-65); a high project average cannot hide a failing file. A measured score of zero fails any positive threshold; an empty file inventory has no measured score.--max-nesting <N>: Sets the maximum allowed indentation/nesting level (e.g.,3or4).--max-args <N>: Sets the maximum number of arguments a function can have.-
--max-lines <N>: Sets the maximum number of lines a function can have. Configured--max-lines,--max-args, and--max-nestinglimits (or their configuration equivalents) enable quality analysis and fail the scan when their corresponding rules report a violation. -
--fail-on-quality: Exit with 1 if any quality issue is found. --fail-on-secrets: Exit with 1 if any secret finding is found; implies--secrets.--fail-on-danger: Exit with 1 if any danger or taint finding is found; implies--danger.--fail-on-missing-deps: Exit with 1 if missing dependencies are found; implies--deps.--fail-on-unused-deps: Exit with 1 if unused dependencies are found; implies--deps.
Subcommands¶
deslop shares a source and AST snapshot across its Python analyses. Health checks resolve package directories and files to the nearest project root so root-level manifests and tooling remain visible. Its JSON scoring.passed_gate and gates.passed fields both describe the final exit decision.
Metric commands report file discovery and source read failures rather than returning empty or perfect metrics. cc, mi, and hal also fail on invalid Python syntax. raw counts source text and accepts syntactically invalid Python.
raw¶
Calculate raw metrics (LOC, LLOC, SLOC, Comments, Multi, Blank).
-j,--json: Output JSON.-s,--summary: Show summary metrics.-O,--output-file <FILE>: Save output to file.-e,--exclude <DIR>: Folders to exclude.-i,--ignore <PATTERN>: Glob patterns to ignore.
cc¶
Calculate Cyclomatic Complexity.
-a,--average: Show average complexity.--total-average: Show total average complexity.-s,--show-complexity: Show complexity score with rank.-n,--min <RANK>: Set minimum complexity rank (A-F).-x,--max <RANK>: Set maximum complexity rank (A-F).-o,--order <ORDER>: Ordering function (score, lines, alpha).--no-assert: Do not count assert statements.--xml: Output XML.--fail-threshold <N>: Exit 1 if any block has complexity > N.-j,--json: Output JSON.-e,--exclude <DIR>: Folders to exclude.-i,--ignore <PATTERN>: Glob patterns to ignore.-O,--output-file <FILE>: Save output to file.
hal¶
Calculate Halstead Metrics.
-f,--functions: Compute metrics on function level.-j,--json: Output JSON.-e,--exclude <DIR>: Folders to exclude.-i,--ignore <PATTERN>: Glob patterns to ignore.-O,--output-file <FILE>: Save output to file.
mi¶
Calculate Maintainability Index.
-s,--show: Show actual MI value.-a,--average: Show average MI.-n,--min <RANK>: Set minimum MI rank (A-C).-x,--max <RANK>: Set maximum MI rank (A-C).--multi: Count multiline strings as comments (default: true).--fail-threshold <N>: Exit 1 if any file has MI < N.-j,--json: Output JSON.-e,--exclude <DIR>: Folders to exclude.-i,--ignore <PATTERN>: Glob patterns to ignore.-O,--output-file <FILE>: Save output to file.
stats¶
Generate comprehensive project statistics report. Discovery, read, and syntax errors fail the command instead of producing empty statistics. The files command also reports discovery and read errors; its line counts do not require valid Python syntax.
-a,--all: Enable all analysis: secrets, danger, quality, files.--root <PATH>: Project root for analysis (use instead of positional path).-s,--secrets: Scan for secrets.-d,--danger: Scan for dangerous code.-q,--quality: Scan for quality issues.-j,--json: Output JSON.-o,--output <FILE>: Output file path.--exclude-folders <DIRS>: Exclude specific folders from analysis.
deslop¶
Run the unified repository assessment. It includes architecture, Git context, health, searchability, naming, TODOs, globals, exceptions, wildcard imports, side effects, singletons, anti-patterns, duplicates, unreferenced functions, function metrics, and the Slop Index. Dead code, dependency, secret, danger, and general quality scans remain on their existing commands. The default text report shows the Slop Index, its dimension breakdown, up to 15 prioritized fixes, and gate status. It ends at the gate status on passing runs. Use --verbose for all analysis sections and file locations; --json always includes the complete structured results. The short tooling line lists up to six detected configurations and shows how many more are available in the full report. The report also includes scan_integrity with discovered and checked file counts and any unreadable or invalid Python files. An incomplete scan exits with code 1 even without --fail-on-any, so CI cannot treat partial results as a pass.
--fail-on-any: Exit with code1when any configured architecture, hotspot, context-budget, health, or analysis gate fails. The global form (cytoscnpy --fail-on-any deslop ...) is also supported.--ci: Apply the Slop Index ceiling (40 unless--max-scoreor config sets one).--max-score <N>: Maximum allowed Slop Index (0–100).--root <PATH>: Project root for analysis (use instead of positional path).--json: Output one JSON report.--format <terminal|json|llm>: Select the text report, JSON report, or LLM remediation plan.--verbose,-v: Show every analysis section and complete scoring diagnostics.-o,--output <FILE>: Output report file.--exclude <DIR>: Exclude a folder or path pattern from analysis.--ignore <PATTERN>,-i: Repeatable path or directory ignore pattern.--no-git: Disable Git history analysis.--git-months <N>: Set the maximum Git lookback.--context-budget <TOKENS>: Set usable LLM context capacity.
The JSON result includes the analyses listed above, scan_integrity, gates, and schema_version. Use --fail-on-any with limits in the configuration file to enforce CI gates.
Gate limits can be set under [cytoscnpy.deslop] (or [tool.cytoscnpy.deslop]):
max_cycles = 0
max_god_modules = 0
max_hotspots = 0
min_health_score = 70
# max_navigation_pct = 75.0
# max_duplicate_filenames = 0
# max_function_collisions = 0
# min_naming_consistency = 0.85
# max_todos = 0
The individual analysis results are included in deslop; they do not require separate commands. Use the JSON fields or configure [cytoscnpy.deslop] gates for targeted automation.
Verdict Bands¶
| Band | Slop Index Range | Description |
|---|---|---|
| Clean | 0 – 20 | Excellent health, negligible LLM friction |
| Acceptable | 21 – 40 | Normal codebase with minor slop within reasonable boundaries |
| Messy | 41 – 60 | Moderate structural friction, refactoring recommended |
| Sloppy | 61 – 80 | High friction, difficult navigation and maintenance |
| Disaster | 81 – 100 | Severe debt, high risk of LLM hallucinations and errors |
10-Dimension Scoring Model (Weights sum to 100)¶
- Setup reliability (weight 10): Build scripts, lockfile freshness, Docker, and environment configuration.
- Architecture clarity (weight 15): Directory depth, file sizes, god modules, and naming searchability.
- Coupling / blast radius (weight 15): Fan-in/out, circular import cycles, and cross-package dependencies.
- Style consistency (weight 10): Naming convention compliance percentage, linter, formatter, and type checker adoption.
- Test safety net (weight 15): Test-to-source file and line ratios, framework configuration.
- Runtime predictability (weight 10): Mutable globals, import side effects, singletons, bare excepts, anti-patterns.
- Feedback loop speed (weight 5): Test runner, linter configuration, and CI workflow responsiveness.
- Documentation (weight 10): README quality, setup instructions, architecture docs, and contributing guides.
- Dependency boundaries (weight 5): Lockfiles,
.gitignorehygiene, and vendor/generated code separation. - Context pressure (weight 5): Token consumption relative to context budget, active surface, and dead code.
files¶
Show per-file metrics table.
-j,--json: Output only JSON.--exclude-folders <DIRS>: Exclude specific folders from analysis.
deps¶
Analyze dependency hygiene with CytoScnPy rule categories:
CSP-R001: imported package is missing from direct dependency declarations.CSP-R002: declared production dependency is unused.CSP-R003: imported package is present only as a transitive lockfile dependency.CSP-R004: production code imports a development dependency.CSP-R005: declared dependency belongs to the Python standard library.
--json: Output JSON.--requirements <FILE>: Path to a specific requirements file (default: auto-discoverrequirements.txt/requirements-dev.txt).--ignore-unused <PKGS>: Comma-separated package names to suppress from the unused report.--ignore-missing <PKGS>: Comma-separated import names to suppress from the missing report.--exclude <DIRS>: Folders to exclude from import scanning.--extra-installed: Also report packages installed in the venv but not declared.--orphans: Report orphan packages — installed, undeclared, not imported, and not required by any other installed package.--include-dev-unused: Include development dependencies inCSP-R002findings. By default, dev dependencies from dependency groups, optional dependency groups, or dev/test requirements exports are not reported as unused.--fail-on-any: Exit with code1if any dependency finding is found; also enables the extra-installed and orphan reports.--fail-on-unused: Exit with code1if unused dependencies are found.--fail-on-missing: Exit with code1if missing dependencies are found.--fail-on-extra-installed: Exit with code1if extra installed packages are found; also enables the extra-installed report.--fail-on-orphans: Exit with code1if orphan packages are found; also enables the orphan report.--impact <PKG>: Show which transitive packages would be removable if<PKG>were dropped (requires a lockfile).--venv <PATH>: Override the venv path (default: auto-detect.venv).--lockfile <PATH>: Override the lockfile path (default: auto-detectuv.lock/poetry.lock).-O,--output-file <FILE>: Save output to file.
Note: Use the
depssubcommand when you want dependency analysis in isolation or need the extra flags (--extra-installed,--orphans,--impact). To include dependency findings alongside the main scan, pass--depsto the default analysis command.
Dependency scans report scan_complete and path-specific scan_errors in JSON. Discovery, source read/parse errors, missing explicit requirements files, and unreadable or missing -r includes make the command exit with code 1, even without a failure flag. Findings from successfully scanned files are retained. Incomplete scans suppress unused/orphan/removal recommendations; incomplete requirements declarations also suppress findings that depend on proving a package is undeclared. Test and production paths are classified relative to the project root, including when analyzing a source subdirectory or file.
mcp-server¶
Start MCP server for LLM integration.
--root <PATH>: Confine MCP path-based tools to this project directory. If omitted, the server uses its launch working directory.
Note: The
mcp-serversubcommand is handled by thecytoscnpy-clibinary. If you installed the Python package,cytoscnpy mcp-serverwill print an error. Use the standalone CLI build for MCP.
init¶
Initialize CytoScnPy configuration in the current directory.
This creates .cytoscnpy.toml (or appends [tool.cytoscnpy] to pyproject.toml) and adds .cytoscnpy to .gitignore when possible.
Configuration File¶
Create .cytoscnpy.toml in your project root to set defaults.
[cytoscnpy]
# Core settings
confidence = 60
secrets = true
danger = true
quality = true
include_tests = false
include_ipynb = false
project_type = "library" # "library" (default) or "application"
# Note: ipynb_cells is currently a CLI-only option
# Quality thresholds
max_complexity = 10 # Max cyclomatic complexity
max_nesting = 3 # Max nesting depth
max_args = 5 # Max function arguments
max_lines = 50 # Max function lines
min_mi = 40.0 # Min Maintainability Index
# Path filters
exclude_folders = ["build", "dist", ".venv"]
include_folders = ["src"]
# Rule suppression
ignore = ["CSP-P003"] # Globally ignore specific rule IDs
# Clone detection
clones = false # Enable duplicate code detection
clone_similarity = 0.8 # Similarity threshold (0.0-1.0)
# CI/CD
fail_threshold = 5.0
fail_on_secrets = true
fail_on_danger = true
# Per-file rule suppressions (glob -> rule IDs).
# Use a real table (not an inline `{ ... }`) so entries can span multiple
# lines without tripping TOML/editor syntax errors.
# Glob behavior: "*" matches a single path segment, "**" matches recursively.
[cytoscnpy.per-file-ignores]
"tests/*" = ["CSP-D701"]
"**/__init__.py" = ["CSP-L001"]
# Inline whitelist (suppress specific dead-code symbols).
# One array, one entry per line — no repeated headers needed.
whitelist = [
{ name = "my_handler" }, # "exact" match (default)
{ name = "another_symbol", pattern = "wildcard" }, # "exact", "wildcard", or "regex"
{ name = "legacy_fn", file = "src/api/*.py" }, # optional: restrict to a file glob
]
Prefer [[cytoscnpy.whitelist]] blocks instead if you want to attach a comment above each entry:
[[cytoscnpy.whitelist]]
name = "my_handler"
pattern = "exact"
[[cytoscnpy.whitelist]]
name = "another_symbol"
pattern = "wildcard"
Advanced Configuration¶
Secret Scanning¶
[cytoscnpy.secrets_config]
entropy_threshold = 4.5
min_length = 16
entropy_enabled = true
scan_comments = true
skip_docstrings = false
min_score = 50
suspicious_names = ["db_password", "oauth_token"]
[[cytoscnpy.secrets_config.patterns]]
name = "Slack Token"
regex = "xox[baprs]-([0-9a-zA-Z]{10,48})"
severity = "HIGH"
rule_id = "CSP-SCUSTOM-001" # Optional
Dependency Analysis¶
[cytoscnpy.deps]
enabled = true # Run dep analysis by default (same as --deps)
ignore_unused = ["celery", "redis"] # Suppress specific unused-dep findings
ignore_missing = ["numpy"] # Suppress specific missing-dep findings
fail_on_unused = true # Fail if unused dependencies are reported
fail_on_missing = true # Fail if missing dependencies are reported
fail_on_extra_installed = false # Fail on undeclared installed packages
fail_on_orphans = false # Fail on installed orphan packages
# Custom package → import name mappings (for packages where the import name
# differs from the package name and is not in the built-in mapping)
[cytoscnpy.deps.package_mapping]
"my-internal-lib" = ["mylib", "mylib_ext"]
Dangerous Code + Taint Analysis¶
[cytoscnpy.danger_config]
enable_taint = true
severity_threshold = "LOW" # LOW, MEDIUM, HIGH, CRITICAL
excluded_rules = ["CSP-D101"]
custom_sources = ["mylib.get_input"]
custom_sinks = ["mylib.exec"]
# Sanitizers are scoped by vulnerability type and behavior.
[cytoscnpy.danger_config.sanitizers.ssrf]
return_value = ["validate_allowed_url"]
guard = ["is_allowed_url"]
side_effect = ["validate_url_or_raise"]
[cytoscnpy.danger_config.sanitizers.path_traversal]
return_value = ["safe_join"]
[cytoscnpy.danger_config.sanitizers.sql_injection]
return_value = ["build_parameterized_query"]
[cytoscnpy.danger_config.sanitizers.command_injection]
return_value = ["quote_shell_argument"]
Sanitizer names are matched explicitly. Security-sounding variable names do not suppress findings, and each configured sanitizer affects only its vulnerability type.
Exit Codes¶
0: Success, no issues found (or issues below threshold).1: Issues found exceeding configured gates (quality, security, dependency, or fail_threshold).2: Runtime error or invalid arguments.