Skip to content

analyze_code

Parse source code and extract its structure including functions, classes, methods, imports, and complexity metrics.

Quick Reference

analyze_code(
    file_path: str = None,       # Path to file
    code: str = None,            # Or provide code directly
    language: str = "auto"       # Language hint
) -> AnalysisResult

User Stories

Persona Story Tool Value
👤 Sarah (AI User) "I need structure (functions/classes) without full content" Fast analysis, minimal tokens
🔰 Alex (First-Timer) "I want to see the structure of a Python file without reading all the code" Easy first example
🔧 Chris (OSS Contributor) "Analyze AST parsing logic for new language support" Feature development

See all user stories

Parameters

Parameter Type Required Default Description
file_path string No* None Absolute path to the source file
code string No* None Source code as string
language string No "auto" Language: python, javascript, typescript, java, jsx, tsx

*One of file_path or code is required.

Response Schema

{
  "data": {
    "file_path": "string",
    "language": "string",
    "functions": [
      {
        "name": "string",
        "line_start": "integer",
        "line_end": "integer",
        "parameters": ["string"],
        "return_type": "string | null",
        "docstring": "string | null",
        "complexity": "integer",
        "is_async": "boolean"
      }
    ],
    "classes": [
      {
        "name": "string",
        "line_start": "integer",
        "line_end": "integer",
        "bases": ["string"],
        "docstring": "string | null",
        "methods": [
          {
            "name": "string",
            "line_start": "integer",
            "line_end": "integer",
            "parameters": ["string"],
            "is_static": "boolean",
            "is_classmethod": "boolean"
          }
        ]
      }
    ],
    "imports": [
      {
        "module": "string",
        "names": ["string"],
        "alias": "string | null",
        "line": "integer"
      }
    ],
    "global_variables": [
      {
        "name": "string",
        "line": "integer",
        "type_annotation": "string | null"
      }
    ],
    "complexity_summary": {
      "total_functions": "integer",
      "total_classes": "integer",
      "average_complexity": "float",
      "max_complexity": "integer",
      "high_complexity_functions": ["string"]
    }
  },
  "error": null,
  "tier_applied": "string",
  "duration_ms": "integer"
}

Examples

Analyze a Python File

Analyze the structure of src/utils/helpers.py
{
  "file_path": "/project/src/utils/helpers.py"
}
codescalpel analyze-code src/utils/helpers.py
{
  "data": {
    "file_path": "/project/src/utils/helpers.py",
    "language": "python",
    "functions": [
      {
        "name": "validate_email",
        "line_start": 10,
        "line_end": 25,
        "parameters": ["email: str"],
        "return_type": "bool",
        "docstring": "Validate email format using regex.",
        "complexity": 3,
        "is_async": false
      },
      {
        "name": "format_date",
        "line_start": 28,
        "line_end": 45,
        "parameters": ["dt: datetime", "fmt: str = '%Y-%m-%d'"],
        "return_type": "str",
        "docstring": "Format datetime to string.",
        "complexity": 2,
        "is_async": false
      }
    ],
    "classes": [],
    "imports": [
      {"module": "re", "names": [], "alias": null, "line": 1},
      {"module": "datetime", "names": ["datetime"], "alias": null, "line": 2}
    ],
    "complexity_summary": {
      "total_functions": 2,
      "total_classes": 0,
      "average_complexity": 2.5,
      "max_complexity": 3,
      "high_complexity_functions": []
    }
  },
  "tier_applied": "community",
  "duration_ms": 45
}

Analyze Inline Code

Analyze this Python code:

class DataProcessor:
    def __init__(self, config):
        self.config = config

    def process(self, data):
        return [self.transform(item) for item in data]

    def transform(self, item):
        return item.upper()
{
  "code": "class DataProcessor:\n    def __init__(self, config):\n        self.config = config\n    \n    def process(self, data):\n        return [self.transform(item) for item in data]\n    \n    def transform(self, item):\n        return item.upper()",
  "language": "python"
}
# Save code to temp file first
cat > temp.py << 'EOF'
class DataProcessor:
    def __init__(self, config):
        self.config = config

    def process(self, data):
        return [self.transform(item) for item in data]

    def transform(self, item):
        return item.upper()
EOF

codescalpel analyze-code temp.py
{
  "data": {
    "language": "python",
    "functions": [],
    "classes": [
      {
        "name": "DataProcessor",
        "line_start": 1,
        "line_end": 10,
        "bases": [],
        "docstring": null,
        "methods": [
          {
            "name": "__init__",
            "line_start": 2,
            "line_end": 3,
            "parameters": ["self", "config"],
            "is_static": false,
            "is_classmethod": false
          },
          {
            "name": "process",
            "line_start": 5,
            "line_end": 6,
            "parameters": ["self", "data"],
            "is_static": false,
            "is_classmethod": false
          },
          {
            "name": "transform",
            "line_start": 8,
            "line_end": 9,
            "parameters": ["self", "item"],
            "is_static": false,
            "is_classmethod": false
          }
        ]
      }
    ],
    "imports": []
  },
  "tier_applied": "community",
  "duration_ms": 23
}

Analyze TypeScript/React

Analyze the React component in components/UserCard.tsx
{
  "file_path": "/project/components/UserCard.tsx",
  "language": "tsx"
}
codescalpel analyze-code components/UserCard.tsx --language tsx
{
  "data": {
    "file_path": "/project/components/UserCard.tsx",
    "language": "tsx",
    "functions": [
      {
        "name": "UserCard",
        "line_start": 8,
        "line_end": 25,
        "parameters": ["props: UserCardProps"],
        "return_type": "JSX.Element",
        "is_async": false,
        "component_type": "functional",
        "is_server_component": false
      }
    ],
    "classes": [],
    "imports": [
      {"module": "react", "names": ["useState", "useEffect"], "line": 1},
      {"module": "./types", "names": ["UserCardProps"], "line": 2}
    ]
  },
  "tier_applied": "community",
  "duration_ms": 38
}

Tier Differences

This tool is available at all tiers. What differs are the limits and capabilities:

Feature Community Pro Enterprise
Availability ✅ Available ✅ Available ✅ Available
Basic analysis
Complexity metrics ✅ Advanced
Configured languages ✅ 13-language limits profile ✅ 13-language limits profile ✅ 13-language limits profile
Max file size 1MB 100MB 100MB
Dependency analysis Single file only ✅ Cross-file ✅ Cross-file
Tool findings Up to 50 static-tool findings Unlimited Unlimited
Timeout Tier-default timeout Tier-default timeout Tier-default timeout

Error Handling

File Not Found

{
  "data": null,
  "error": {
    "code": "FILE_NOT_FOUND",
    "message": "File not found: /project/missing.py",
    "suggestions": [
      "/project/src/missing.py",
      "/project/lib/missing.py"
    ]
  }
}

Parse Error

{
  "data": null,
  "error": {
    "code": "PARSE_ERROR",
    "message": "Syntax error at line 15: unexpected indent",
    "details": {
      "line": 15,
      "column": 4
    }
  }
}

Tier Limits

Analysis capabilities vary by tier:

Feature Community Pro Enterprise
Max file size 1 MB 10 MB 100 MB
Languages Python, JS, TS, Java Python, JS, TS, Java All
Complexity analysis Basic Detailed Comprehensive
Custom rules Not available Limited Unlimited
Token estimates

Community Tier

  • ✅ Parse Python, JavaScript, TypeScript, Java
  • ✅ Extract functions, classes, imports
  • ✅ Basic complexity scores
  • ⚠️ Max 1 MB file size

Pro Tier

  • ✅ All Community features
  • ✅ Up to 10 MB files
  • ✅ Code smell detection
  • ✅ Advanced metrics (maintainability index, cognitive complexity)

Enterprise Tier

  • ✅ All Pro features
  • ✅ Up to 100 MB files
  • ✅ Custom analysis rules
  • ✅ Compliance checking (MISRA, CERT)
  • ✅ Multi-language project analysis

See tier comparison

  1. Check complexity metrics - Identify functions needing refactoring
  2. Use before extraction - Understand structure before extracting