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.--html-theme <auto|dark|light>: Sets the theme the HTML report opens with (defaultauto, which follows the viewer's system setting). Viewers can still switch themes from the report. Requires--html.--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 it, in both directions: a setting set tofalsepasses the matching--no-flag.
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-secrets,--no-danger,--no-quality,--no-clones: Disable a scan even when project configuration enables it (including throughfail_on_*gates or quality thresholds). Of a flag and its--no-form, the last one given wins. The VS Code extension passes these for settings explicitly set tofalse; unset settings leave the choice to the project configuration.--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.--force-exclude: Apply folder exclusions (exclude_foldersand the defaults) to files passed directly by path, as editors and pre-commit hooks pass them. Only folders below the project root (the folder of the configuration file in use) count, so a checkout under a folder such asbuild/still analyzes its own files. Without this flag, a file named on the command line is always analyzed.--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.--no-include-tests,--no-include-ipynb: Skip test files or notebooks even when project configuration includes them; the last of a flag and its--no-form wins.--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. Lines, and the byte offsets of suggested fixes, are then relative to the finding's cell (cell_number, counting markdown cells as nbformat does). Stable IDs of cell findings include the cell.--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. Refuses to generate a whitelist when the scan is incomplete.--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.
Overlapping input paths analyze each physical Python file once. A directory passed explicitly alongside its parent is still scanned even when the parent's exclude or ignore rules would skip it, matching explicitly passed files. Directory scans reject source symlinks that resolve outside the scanned directory and report the failure as an incomplete scan.
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.
Every analysis subcommand (raw, cc, hal, mi, stats, deslop, files, projects, deps) takes one or more paths, or --root <PATH> in place of them. With neither, the current directory is analyzed.
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 <RANK>: Set minimum complexity rank (A-F). Alias:--min.-x,--max-rank <RANK>: Set maximum complexity rank (A-F). Alias:--max.-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 <RANK>: Set minimum MI rank (A-C). Alias:--min.-x,--max-rank <RANK>: Set maximum MI rank (A-C). Alias:--max.--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 LLM-friction assessment and report the Slop Index (0–100). One run covers architecture, Git context, repository health, searchability, naming, TODOs, globals, exceptions, wildcard imports, side effects, singletons, anti-patterns, duplicates, unreferenced functions, and function metrics.
See DeSlop: LLM Friction Score for how the score is computed, the report format, every gate and config key, and CI examples.
--fail-on-any: Fail when any configured gate fails. The global form (cytoscnpy --fail-on-any deslop ...) is also supported.--ci: Apply the Slop Index ceiling (40 unless--max-scoreormax_slop_indexsets one).--max-score <N>: Maximum allowed Slop Index (0–100).--root <PATH>: Project root for analysis (use instead of positional paths).--json: Output one JSON report.--format <terminal|json|llm>: Select the text report, JSON report, or LLM remediation plan. An explicit--formattakes precedence over--json.--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 (default176000).
Tests and sample-code directories are skipped unless the global --include-tests flag is given before the subcommand.
Exit code 1 means a gate failed. scan_integrity (unreadable or unparsable files) and no_python_files always run; the Slop Index ceiling runs with --ci or --max-score; limits under [cytoscnpy.deslop] run with --fail-on-any.
cytoscnpy deslop .
cytoscnpy deslop . --json --fail-on-any
cytoscnpy deslop . --ci --max-score 50
cytoscnpy deslop . --format llm -o remediation.md
files¶
Show per-file metrics table.
-j,--json: Output only JSON.--exclude-folders <DIRS>: Exclude specific folders from analysis.
projects¶
List the projects under a folder: the folder itself plus each folder below it with its own .cytoscnpy.toml, or a pyproject.toml with a [tool.cytoscnpy] table. Configuration is read from a scan target's nearest ancestor, so in a monorepo each nested project's settings apply only when that project is scanned on its own; editors scan each listed project separately. Folders a scan skips (excluded, default-excluded such as .venv or node_modules, or gitignored) are not searched.
--json: Output{"projects": [...]}with absolute paths.
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.
lsp¶
Start a Language Server Protocol server over stdio for editors (Zed, Neovim, Helix and others).
When the editor opens a Python file and each time one is saved, the server analyzes the workspace folder holding it, the same way as cytoscnpy <folder> --json, and publishes the findings as diagnostics for every file in it. A file outside every workspace folder, or any file when the editor passes {"analysisMode": "file"} as initialization options, is analyzed on its own, as cytoscnpy <file> --json --force-exclude does. Code actions remove or rename unused code, add # noqa comments, and, as in VS Code, remove all unused code of one kind or all dead code in the file at once. Each project in a workspace folder (a directory with its own pyproject.toml or .cytoscnpy.toml) is analyzed with its own configuration, and files changed on disk are picked up when the editor supports file watching. Editors pass the VS Code extension's settings, without the cytoscnpy. prefix, as initialization options or the cytoscnpy workspace configuration section, for example {"enableSecretsScan": true, "maxComplexity": 12, "args": ["--include-tests"]}. The VS Code commands (cytoscnpy.analyzeCurrentFile, cytoscnpy.analyzeWorkspace, cytoscnpy.complexity, cytoscnpy.halstead, cytoscnpy.maintainability, cytoscnpy.rawMetrics) are LSP commands, also offered as source code actions; metric reports open in an editor tab when the editor supports window/showDocument. See Integrations.
Note: Like
mcp-server, thelspsubcommand is handled by thecytoscnpy-clibinary. The Python package'scytoscnpycommand prints an error instead.
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
# 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
]
# Per-file rule suppressions (glob -> rule IDs). Keep table headers like this
# one after all top-level keys: every key below a header belongs to that table.
# Glob behavior: "*" matches a single path segment, "**" matches recursively.
[cytoscnpy.per-file-ignores]
"tests/*" = ["CSP-D701"]
"**/__init__.py" = ["CSP-L001"]
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"
An invalid regex name or file glob, whether in the config or in a TOML file passed with --whitelist, stops the scan with an error that names the entry. Before this, such entries were dropped without a warning.
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 groups: ssrf, path_traversal, sql_injection, command_injection, and code_injection, each with return_value, guard, and side_effect lists. See Security for details.
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.