Skip to main content

Code Firewall MCP

A structural similarity-based code security filter for MCP (Model Context Protocol). Blocks dangerous code patterns before they reach execution tools by comparing code structure against a blacklist of known-bad patterns.

How It Works

┌──────────┐    ┌─────────────┐    ┌───────────────────┐    ┌─────────────────────┐
│ Code     │───▶│ CST → Embed │───▶│ Similarity Check  │───▶│ Execution Tools     │
│ (file)   │    │ (tree-sitter│    │ vs blacklist      │    │ (rlm_exec, etc.)    │
└──────────┘    │  + Ollama)  │    │ (ChromaDB)        │    └─────────────────────┘
                └─────────────┘    └─────────┬─────────┘
                                             │
                                    ┌────────┴────────┐
                                    ▼                 ▼
                               [BLOCKED]         [ALLOWED]
  1. Parse code to Concrete Syntax Tree (CST) using tree-sitter
  2. Normalize by stripping identifiers and literals → structural skeleton
  3. Embed the normalized structure via Ollama
  4. Compare against blacklisted patterns in ChromaDB
  5. Block if similarity exceeds threshold, otherwise allow

Key Insight

Code patterns like os.system("rm -rf /") and os.system("ls") have identical structure. By normalizing away the specific commands/identifiers, we can detect dangerous patterns regardless of the specific arguments used.

Installation

# Via uvx (recommended)
uvx code-firewall-mcp

# Or install from source
pip install -e .

Requirements

  • Python 3.10+
  • Ollama (for embeddings)
  • ChromaDB (for vector storage)
  • tree-sitter (optional, for better parsing)

Pull an embedding model:

ollama pull nomic-embed-text

Tools

firewall_check

Check if a code file is safe to pass to execution tools.

result = await firewall_check(file_path="/path/to/script.py")
# Returns: {allowed: bool, blocked: bool, similarity: float, ...}

firewall_check_code

Check code string directly (no file required).

result = await firewall_check_code(
    code="import os; os.system('rm -rf /')",
    language="python"
)

firewall_blacklist

Add a dangerous pattern to the blacklist.

result = await firewall_blacklist(
    code="os.system(arbitrary_command)",
    reason="Arbitrary command execution",
    severity="critical"
)

firewall_record_delta

Record near-miss variants to sharpen the classifier.

result = await firewall_record_delta(
    code="subprocess.run(['ls', '-la'])",
    similar_to="abc123",
    notes="Legitimate use case for file listing"
)

firewall_list_patterns

List patterns in the blacklist or delta collection.

firewall_remove_pattern

Remove a pattern from blacklist or deltas.

firewall_status

Get firewall status and statistics.

Configuration

Environment variables:

Variable Default Description
FIREWALL_DATA_DIR /tmp/code-firewall Data storage directory
OLLAMA_URL http://localhost:11434 Ollama server URL
EMBEDDING_MODEL nomic-embed-text Ollama embedding model
SIMILARITY_THRESHOLD 0.85 Block threshold (0-1)
NEAR_MISS_THRESHOLD 0.70 Near-miss recording threshold

Usage Pattern

Pre-filter for massive-context-mcp

Use code-firewall-mcp as a gatekeeper before passing code to rlm_exec:

# 1. Check code safety
check = await firewall_check_code(user_code)

if check["blocked"]:
    print(f"BLOCKED: {check['reason']}")
    return

# 2. If allowed, proceed with execution
result = await rlm_exec(code=user_code, context_name="my-context")

Building the Blacklist

The blacklist grows through use:

  1. Initial seeding: Add known dangerous patterns
  2. Audit feedback: When rlm_auto_analyze finds security issues, add patterns
  3. Delta sharpening: Record near-misses to improve classification boundaries
# After security audit finds issues
await firewall_blacklist(
    code=dangerous_code,
    reason="Command injection via subprocess",
    severity="critical"
)

Structural Normalization

The normalizer strips:

  • Identifiers: my_var → _
  • String literals: "hello" → "S"
  • Numbers: 42 → N
  • Comments: Removed entirely

Example:

# Original
subprocess.run(["curl", url, "-o", output_file])

# Normalized
_._(["S", _, "S", _])

Both subprocess.run(["curl", ...]) and subprocess.run(["wget", ...]) normalize to the same structure, so blacklisting one catches both.

License

MIT

Metadata

Release files for code-firewall-mcp 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for code-firewall-mcp 0.7.0
File Size Uploaded
code_firewall_mcp-0.7.0.tar.gz 176.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for code-firewall-mcp 0.7.0
File Interpreter ABI Platform
code_firewall_mcp-0.7.0-py3-none-any.whl Python 3 none any Details

Total release size: 191.7 kB

Release files / code_firewall_mcp-0.7.0.tar.gz

Download URL code_firewall_mcp-0.7.0.tar.gz
Size 176.0 kB
Tags Source
SHA-256 checksum
How to use checksums
3b3b972c279107167a964ca0490eac2c0c74ff567a36078ea76038c2ab98dde1
BLAKE2b-256 checksum
How to use checksums
33d81b50ab7716e1bc3d6d4d13b7509fe71cf7507a15f32fba74b4df6239d4e3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 19, 2026.

Transparency log

Release files / code_firewall_mcp-0.7.0-py3-none-any.whl

Download URL code_firewall_mcp-0.7.0-py3-none-any.whl
Size 15.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
02ed9893e3dea511af430505b3638b9d957ff092f224ba07b0db0c15135fd016
BLAKE2b-256 checksum
How to use checksums
d2d44a080000668276559bb14bd12e61585878ce62df3fd9e846d9c6015c6f0f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 19, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.7.0 This release

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page