npm package: @modular-intelligence/threat-modeling
Description: MCP server for threat modeling (STRIDE, attack trees, risk scoring)
Latest version: 1.0.2

# Threat Modeling MCP Server

A comprehensive threat modeling service using STRIDE analysis, attack tree generation, and risk scoring frameworks. This MCP (Model Context Protocol) server enables Claude to perform systematic threat analysis on system architectures, validate data flow diagrams for security issues, and prioritize security risks based on likelihood and impact.

## Overview

This server provides intelligent threat modeling and security analysis capabilities through a unified interface:

- **STRIDE Analysis** - Identify threats across all six STRIDE categories (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege) tailored to specific component types and data sensitivity levels
- **Attack Tree Generation** - Create hierarchical attack trees showing potential attack paths and techniques grouped by threat category with risk ratings
- **DFD Validation** - Validate data flow diagrams for common security issues including unencrypted trust boundary crossings, missing authentication controls, and sensitive data handling violations
- **Risk Scoring** - Calculate risk scores using a likelihood x impact matrix with adjustments for existing security controls
- **Threat Library Search** - Query a comprehensive threat library containing 12 threat types with 24 mitigation strategies

Perfect for security architects, threat modelers, penetration testers, and development teams planning secure system designs.

## Tools

| Tool | Description |
|------|-------------|
| `stride_analyze` | Perform STRIDE threat analysis on system components |
| `attack_tree_generate` | Generate attack trees for given attacker goals |
| `dfd_validate` | Validate data flow diagrams for security issues |
| `risk_score` | Calculate risk scores using likelihood x impact matrix |
| `threat_library_search` | Search threat library by keyword or category |

### STRIDE Analyze

Perform STRIDE threat analysis on a system component. The tool identifies applicable threats across all STRIDE categories based on component type and data sensitivity, returning categorized threats with likelihood, impact, examples, and recommended mitigations.

**Input Parameters:**
```typescript
{
  component_name: string        // Name or description of the component
  component_type: string        // web_app | api | database | network | mobile_app | iot_device | cloud_service | microservice
  data_sensitivity?: string     // public | internal | confidential | restricted (default: internal)
}
```

**Example Request:**
```json
{
  "component_name": "User Authentication API",
  "component_type": "api",
  "data_sensitivity": "confidential"
}
```

**Example Output:**
```json
{
  "component": {
    "name": "User Authentication API",
    "type": "api",
    "data_sensitivity": "confidential"
  },
  "analysis": [
    {
      "category": "Spoofing",
      "threats": [
        {
          "id": "T001",
          "name": "Authentication Bypass",
          "description": "Attacker bypasses authentication mechanisms to gain unauthorized access.",
          "likelihood": "HIGH",
          "impact": "HIGH",
          "examples": ["Default credentials", "Session hijacking", "Token theft", "Credential stuffing"],
          "mitigations": [
            {
              "id": "M001",
              "name": "Multi-Factor Authentication",
              "description": "Implement MFA for all user accounts, especially privileged accounts.",
              "category": "authentication",
              "effort": "MEDIUM"
            },
            {
              "id": "M002",
              "name": "Strong Password Policy",
              "description": "Enforce minimum length, complexity requirements, and password rotation.",
              "category": "authentication",
              "effort": "LOW"
            }
          ]
        },
        {
          "id": "T012",
          "name": "Phishing",
          "description": "Attacker deceives users into revealing credentials or sensitive information.",
          "likelihood": "HIGH",
          "impact": "HIGH",
          "examples": ["Spear phishing", "Clone phishing", "Vishing", "Smishing"],
          "mitigations": [
            {
              "id": "M023",
              "name": "Security Awareness Training",
              "description": "Regular phishing simulation and security awareness training for all staff.",
              "category": "training",
              "effort": "MEDIUM"
            }
          ]
        }
      ]
    },
    {
      "category": "Tampering",
      "threats": [
        {
          "id": "T003",
          "name": "Data Manipulation",
          "description": "Attacker modifies data in transit or at rest without authorization.",
          "likelihood": "MEDIUM",
          "impact": "HIGH",
          "examples": ["Man-in-the-middle", "SQL injection", "Parameter tampering"],
          "mitigations": [
            {
              "id": "M006",
              "name": "Encryption in Transit",
              "description": "Use TLS/SSL for all data in transit. Enforce minimum TLS 1.2.",
              "category": "encryption",
              "effort": "LOW"
            }
          ]
        }
      ]
    },
    {
      "category": "Information Disclosure",
      "threats": [
        {
          "id": "T006",
          "name": "Data Leakage",
          "description": "Sensitive information is exposed to unauthorized parties.",
          "likelihood": "HIGH",
          "impact": "HIGH",
          "examples": ["Error messages with stack traces", "Directory listing", "Unencrypted data transmission", "Verbose API responses"],
          "mitigations": [
            {
              "id": "M012",
              "name": "Data Classification",
              "description": "Classify data by sensitivity and apply appropriate protection controls.",
              "category": "data_protection",
              "effort": "MEDIUM"
            }
          ]
        }
      ]
    }
  ],
  "summary": {
    "total_threats": 8,
    "high_impact": 5,
    "high_likelihood": 4
  }
}
```

### Attack Tree Generate

Generate an attack tree for a given attacker goal. Creates a hierarchical tree structure showing attack paths grouped by STRIDE categories, with specific techniques and their associated likelihood and impact ratings.

**Input Parameters:**
```typescript
{
  goal: string            // Attacker's objective
  component_type: string  // web_app | api | database | network | mobile_app | iot_device | cloud_service | microservice
  depth?: number          // Tree depth 1-4 (default: 3)
}
```

**Example Request:**
```json
{
  "goal": "Steal user credentials from database",
  "component_type": "database",
  "depth": 3
}
```

**Example Output:**
```json
{
  "goal": "Steal user credentials from database",
  "component_type": "database",
  "depth": 3,
  "tree": {
    "root": "Steal user credentials from database",
    "children": [
      {
        "method": "Tampering",
        "category": "Tampering",
        "description": "Attack methods in the Tampering category",
        "children": [
          {
            "technique": "Data Manipulation",
            "threat_id": "T003",
            "description": "Attacker modifies data in transit or at rest without authorization.",
            "likelihood": "MEDIUM",
            "impact": "HIGH",
            "examples": ["Man-in-the-middle", "SQL injection", "Parameter tampering"]
          },
          {
            "technique": "Log Tampering",
            "threat_id": "T004",
            "description": "Attacker modifies or deletes audit logs to cover tracks.",
            "likelihood": "MEDIUM",
            "impact": "HIGH",
            "examples": ["Log deletion", "Log modification", "Timestamp manipulation"]
          }
        ]
      },
      {
        "method": "Elevation of Privilege",
        "category": "Elevation of Privilege",
        "description": "Attack methods in the Elevation of Privilege category",
        "children": [
          {
            "technique": "Privilege Escalation",
            "threat_id": "T010",
            "description": "Attacker gains higher privileges than authorized.",
            "likelihood": "MEDIUM",
            "impact": "CRITICAL",
            "examples": ["Kernel exploit", "SUID abuse", "Misconfigured permissions", "IDOR"]
          },
          {
            "technique": "Injection Attack",
            "threat_id": "T011",
            "description": "Attacker injects malicious code or commands into the application.",
            "likelihood": "HIGH",
            "impact": "CRITICAL",
            "examples": ["SQL injection", "Command injection", "XSS", "LDAP injection", "Template injection"]
          }
        ]
      }
    ]
  },
  "metadata": {
    "total_attack_paths": 5,
    "highest_risk_paths": [
      {
        "category": "Elevation of Privilege",
        "technique": "Injection Attack",
        "threat_id": "T011"
      },
      {
        "category": "Denial of Service",
        "technique": "Resource Exhaustion",
        "threat_id": "T008"
      }
    ]
  }
}
```

### DFD Validate

Validate data flow diagram for security issues. Checks for unencrypted flows crossing trust boundaries, missing authentication controls, components without defined trust levels, and sensitive data transmitted over unencrypted protocols.

**Input Parameters:**
```typescript
{
  components: Array<{
    name: string                              // Component name
    type: string                              // Component type description
    trust_level?: "public" | "dmz" | "internal" | "trusted" | "privileged"  // Optional trust level
  }>
  data_flows: Array<{
    from: string                              // Source component name
    to: string                                // Destination component name
    data_type: string                         // Type of data being transmitted
    protocol?: string                         // Protocol used (HTTP, HTTPS, TLS, etc.)
  }>
  trust_boundaries: Array<{
    name: string                              // Boundary name
    components: string[]                      // Component names within boundary
  }>
}
```

**Example Request:**
```json
{
  "components": [
    {
      "name": "Web Browser",
      "type": "client",
      "trust_level": "public"
    },
    {
      "name": "Web Server",
      "type": "server",
      "trust_level": "dmz"
    },
    {
      "name": "Database Server",
      "type": "database",
      "trust_level": "internal"
    }
  ],
  "data_flows": [
    {
      "from": "Web Browser",
      "to": "Web Server",
      "data_type": "credentials",
      "protocol": "HTTPS"
    },
    {
      "from": "Web Server",
      "to": "Database Server",
      "data_type": "user_credentials",
      "protocol": "TCP"
    }
  ],
  "trust_boundaries": [
    {
      "name": "Internet",
      "components": ["Web Browser"]
    },
    {
      "name": "DMZ",
      "components": ["Web Server"]
    },
    {
      "name": "Internal Network",
      "components": ["Database Server"]
    }
  ]
}
```

**Example Output:**
```json
{
  "valid": false,
  "findings": [
    {
      "severity": "CRITICAL",
      "message": "Sensitive data (user_credentials) transmitted over unencrypted protocol (TCP): Web Server -> Database Server",
      "affected_flow": "Web Server -> Database Server",
      "recommendation": "Use encrypted protocols (HTTPS, SFTP, TLS) for all sensitive data transmission"
    },
    {
      "severity": "HIGH",
      "message": "Data flow from public zone to internal zone requires authentication: Web Browser -> Web Server",
      "affected_flow": "Web Browser -> Web Server",
      "recommendation": "Implement strong authentication (MFA recommended) for flows from public to internal/trusted zones"
    }
  ],
  "summary": {
    "total_findings": 2,
    "critical": 1,
    "high": 1,
    "medium": 0,
    "low": 0
  }
}
```

### Risk Score

Calculate risk score using likelihood x impact matrix with control adjustments. Computes raw risk score, applies reduction based on existing controls, and provides risk level classification with prioritized recommendations.

**Input Parameters:**
```typescript
{
  threat_name: string           // Name of the threat
  likelihood: string            // LOW | MEDIUM | HIGH
  impact: string                // LOW | MEDIUM | HIGH | CRITICAL
  existing_controls?: string[]  // List of existing security controls
}
```

**Example Request:**
```json
{
  "threat_name": "SQL Injection Attack on User Database",
  "likelihood": "HIGH",
  "impact": "CRITICAL",
  "existing_controls": [
    "Parameterized queries implemented",
    "Web application firewall",
    "Input validation on API"
  ]
}
```

**Example Output:**
```json
{
  "threat": "SQL Injection Attack on User Database",
  "assessment": {
    "likelihood": "HIGH",
    "likelihood_value": 3,
    "impact": "CRITICAL",
    "impact_value": 4
  },
  "risk_score": {
    "raw_score": 12,
    "adjusted_score": 10.5,
    "risk_level": "CRITICAL"
  },
  "controls": {
    "count": 3,
    "controls_applied": [
      "Parameterized queries implemented",
      "Web application firewall",
      "Input validation on API"
    ],
    "reduction_factor": 1.5
  },
  "recommendations": [
    "Immediate action required - prioritize mitigation",
    "Consider implementing multiple layers of defense (defense-in-depth)",
    "High likelihood detected - focus on preventive controls and monitoring",
    "High impact detected - implement detective and corrective controls",
    "Develop incident response plan for this threat"
  ],
  "risk_matrix": {
    "description": "HIGH likelihood x CRITICAL impact = CRITICAL risk",
    "priority": 1
  }
}
```

### Threat Library Search

Search threat library by category or keyword. Searches across threat names, descriptions, examples, and IDs. Returns matching threats sorted by risk score with full mitigation details.

**Input Parameters:**
```typescript
{
  query: string              // Search keyword
  category?: string          // Optional STRIDE category filter (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege)
}
```

**Example Request:**
```json
{
  "query": "injection",
  "category": "Elevation of Privilege"
}
```

**Example Output:**
```json
{
  "query": "injection",
  "category": "Elevation of Privilege",
  "results": [
    {
      "id": "T011",
      "category": "Elevation of Privilege",
      "name": "Injection Attack",
      "description": "Attacker injects malicious code or commands into the application.",
      "likelihood": "HIGH",
      "impact": "CRITICAL",
      "examples": ["SQL injection", "Command injection", "XSS", "LDAP injection", "Template injection"],
      "mitigations": [
        {
          "id": "M008",
          "name": "Input Validation",
          "description": "Validate and sanitize all user inputs. Use allowlists over blocklists.",
          "category": "application",
          "effort": "MEDIUM"
        },
        {
          "id": "M021",
          "name": "Parameterized Queries",
          "description": "Use parameterized queries or prepared statements for all database operations.",
          "category": "application",
          "effort": "LOW"
        },
        {
          "id": "M022",
          "name": "Output Encoding",
          "description": "Encode all output to prevent XSS and injection attacks.",
          "category": "application",
          "effort": "LOW"
        }
      ]
    }
  ],
  "summary": {
    "total_results": 1,
    "by_category": [
      {
        "category": "Elevation of Privilege",
        "count": 1
      }
    ],
    "high_risk_count": 1
  }
}
```

## Configuration

This server does not require any environment variables. All threat and mitigation data is bundled within the server package.

## Installation

### Prerequisites

- Bun runtime (version 1.x or later)
- Node.js 18+ (alternative runtime)

### Steps

1. Clone or download this repository:
```bash
git clone <repo-url>
cd threat-modeling
```

2. Install dependencies:
```bash
bun install
```

3. Build the project:
```bash
bun run build
```

4. Run the server:
```bash
bun run start
```

The server will start listening on stdio transport.

## Usage

### Running the Server

Start the server with Bun:

```bash
bun run src/index.ts
```

The server implements the Model Context Protocol (MCP) and communicates via stdio transport. It can be integrated with Claude or other MCP clients.

### Claude Desktop Configuration

Add the server to your Claude Desktop configuration at `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "threat-modeling": {
      "command": "bun",
      "args": [
        "run",
        "/path/to/threat-modeling/src/index.ts"
      ]
    }
  }
}
```

### Claude Code MCP Settings

Configure the server in Claude Code's MCP settings (typically in `.mcp.json` or via settings UI):

```json
{
  "servers": {
    "threat-modeling": {
      "transport": "stdio",
      "command": "bun",
      "args": ["run", "/path/to/threat-modeling/src/index.ts"]
    }
  }
}
```

### Example Usage in Claude

Once configured, you can use the tools directly in conversations with Claude:

**Request:**
"Perform a STRIDE analysis on our REST API that handles user authentication"

**Claude will call:**
```json
{
  "tool": "stride_analyze",
  "input": {
    "component_name": "REST API - User Authentication",
    "component_type": "api",
    "data_sensitivity": "confidential"
  }
}
```

**Request:**
"Generate an attack tree for the goal of stealing customer data from our database"

**Claude will call:**
```json
{
  "tool": "attack_tree_generate",
  "input": {
    "goal": "Steal customer data from database",
    "component_type": "database",
    "depth": 3
  }
}
```

**Request:**
"Validate this data flow diagram: Browser -> Web Server (HTTPS) -> Database (unencrypted), with trust boundaries for public internet, DMZ, and internal network"

**Claude will call:**
```json
{
  "tool": "dfd_validate",
  "input": {
    "components": [
      {"name": "Browser", "type": "client", "trust_level": "public"},
      {"name": "Web Server", "type": "server", "trust_level": "dmz"},
      {"name": "Database", "type": "database", "trust_level": "internal"}
    ],
    "data_flows": [
      {"from": "Browser", "to": "Web Server", "data_type": "user_data", "protocol": "HTTPS"},
      {"from": "Web Server", "to": "Database", "data_type": "credentials", "protocol": "TCP"}
    ],
    "trust_boundaries": [
      {"name": "Internet", "components": ["Browser"]},
      {"name": "DMZ", "components": ["Web Server"]},
      {"name": "Internal", "components": ["Database"]}
    ]
  }
}
```

**Request:**
"Calculate the risk score for authentication bypass with high likelihood and critical impact, assuming we have multi-factor authentication implemented"

**Claude will call:**
```json
{
  "tool": "risk_score",
  "input": {
    "threat_name": "Authentication Bypass",
    "likelihood": "HIGH",
    "impact": "CRITICAL",
    "existing_controls": ["Multi-Factor Authentication", "Session timeout enforcement", "Intrusion detection"]
  }
}
```

**Request:**
"Search the threat library for denial of service threats"

**Claude will call:**
```json
{
  "tool": "threat_library_search",
  "input": {
    "query": "resource exhaustion",
    "category": "Denial of Service"
  }
}
```

## Security

This server is designed for security analysis and modeling purposes. The following security considerations apply:

### Threat Library Data

The threat library contains threat intelligence for defensive security analysis. This information is used to:
- Identify potential vulnerabilities in system designs
- Prioritize security control implementation
- Support threat modeling and risk assessment activities

### Input Validation

**Component Names and Types**
- Component names limited to 200 characters
- Component types restricted to predefined categories (web_app, api, database, network, mobile_app, iot_device, cloud_service, microservice)

**Attack Goals and Queries**
- Maximum query length: 500 characters
- Searches operate on threat library data only
- No external network lookups or API calls

**DFD Components**
- Component names validated for format and length
- Trust levels restricted to valid zones (public, dmz, internal, trusted, privileged)
- Data types validated as strings
- All components referenced in data flows must be defined

**Risk Assessment Parameters**
- Threat names limited to 500 characters
- Likelihood and impact restricted to predefined enumerated values
- Controls list accepts arbitrary security control descriptions

### What This Server Does Not Do

This server does not:
- Perform active security scanning or penetration testing
- Access external systems or networks
- Require API keys or credentials
- Make network requests outside the server process
- Store threat assessment results or configuration data

### Recommended Usage

Use this server for:
- Design-time threat modeling and analysis
- Security architecture reviews
- Risk assessment and prioritization
- Educational purposes and security awareness
- Documentation of security considerations

## License

ISC License - see LICENSE file for details