Skip to main content

Security middleware for Model Context Protocol (MCP) that detects and blocks malicious tool calls

Project description

Kavach - MCP Security Middleware

Security middleware for Model Context Protocol (MCP) that detects and blocks malicious tool calls using pattern-based rule scanning.

Built by Shivam Namdeo | PyPI Package | Use Cases

Quick Start

# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate

# Run the example
cd example
python3 app.py

Architecture

Core Components:

  • middleware.py - KavachMiddleware: Main entry point. Processes tool calls and returns allow/block decisions.
  • engine.py - DetectionEngine: Scans text against rules and collects violations.
  • rules.py - KAVACH_RULES: Rule definitions for detecting prompt injection, PII, API keys, etc.
  • types.py - Rule: Data class defining rule structure (id, name, severity, patterns).

How It Works

Sync: Content-based Blocking

from kavach import KavachMiddleware

middleware = KavachMiddleware()

# Process any tool call
result = middleware.process({
    "tool": "aws.s3",
    "access_key": "AKIAIOSFODNN7EXAMPLE"
})

# Returns: {"allowed": False, "violations": [...]}

Async: FastMCP Middleware Integration

from fastmcp import FastMCP
from kavach import KavachMiddleware

mcp = FastMCP("my-server")
mcp.add_middleware(
    KavachMiddleware(
        sensitive_tools=[
            "filesystem.delete",
            "aws.*",           # wildcard patterns
            "database.execute"
        ]
    )
)

Flow:

  1. Tool call intercepted by on_call_tool() middleware hook
  2. Tool name matched against sensitive_tools patterns
  3. If matched, DetectionEngine scans arguments against rules
  4. If violations found and strict mode enabled → raises SecurityException
  5. Otherwise → chain to next middleware

Rules

Detects:

Current Default Rule

  • Prompt Injection - "ignore previous instructions", "override instructions"
  • Secret Leakage - AWS keys (AKIA...), OpenAI keys (sk-...)
  • PII - 10/16 digit sequences

Add custom rules in rules.py:

Rule(
    id="custom-rule",
    name="Rule Name",
    severity="high",
    patterns=[re.compile(r"pattern")]
)

Usage

Option 1: Default Rules Only

middleware = KavachMiddleware()

Option 2: Extend Defaults with Custom Rules

from kavach.types import Rule
import re

custom_rules = [
    Rule(
        id="custom-ban",
        name="Custom Ban",
        severity="high",
        description="Ban specific phrases",
        patterns=[re.compile(r"dangerous\s+action", re.I)]
    )
]

middleware = KavachMiddleware(
    rules=custom_rules,
    extend_rules=True  # Merge with KAVACH_RULES (default)
)

Option 3: Replace Defaults with Custom Rules

middleware = KavachMiddleware(
    rules=custom_rules,
    extend_rules=False  # Use ONLY custom rules
)

Option 4: Control Tool Access

# Allow violations in non-sensitive tools
middleware = KavachMiddleware(strict=False)

# Protect specific tools
middleware = KavachMiddleware(
    sensitive_tools=["filesystem.delete", "aws.s3.delete_bucket"]
)

Project Structure

kavach-mcp-middleware/
├── kavach/
│   ├── __init__.py       # Package exports
│   ├── middleware.py     # Main middleware class
│   ├── engine.py         # Detection logic
│   ├── rules.py          # Security rules
│   └── types.py          # Data classes
└── example/
    └── app.py            # Example usage

API Reference

KavachMiddleware.__init__()

Parameter Type Default Description
rules List[Rule] KAVACH_RULES Custom detection rules
strict bool True Raise exception (True) or return blocked result (False)
sensitive_tools List[str] [] Tools to protect (exact match or wildcard patterns)
extend_rules bool True Merge custom rules with defaults (True) or replace (False)

Methods

  • process(tool_call: dict) - Sync content scanning. Returns {"allowed": bool, ...}
  • async on_call_tool(context, call_next) - FastMCP async middleware hook
  • register_tool(tool_name: str) - Add tool to sensitive_tools at runtime

Contributing

We'd love to get more features and improvements! Please feel free to:

  • Add new detection rules in kavach/rules.py
  • Improve the detection engine in kavach/engine.py
  • Submit bug fixes and enhancements via pull requests
  • Suggest new security patterns to detect

All contributions are welcome! 🚀

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kavach_mcp-0.1.8.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kavach_mcp-0.1.8-py3-none-any.whl (7.0 kB view details)

Uploaded Python 3

File details

Details for the file kavach_mcp-0.1.8.tar.gz.

File metadata

  • Download URL: kavach_mcp-0.1.8.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for kavach_mcp-0.1.8.tar.gz
Algorithm Hash digest
SHA256 47df7dbd95f03d5d08d6cb4010d0679d627d81acf70d277b126605d9191a57bb
MD5 10cea817c05087b0b5939cd906f066a8
BLAKE2b-256 b80e5a2146d1b0eeddbafec6bbf08b04e493c10ecc2af211b1ce3e274c7f4f8d

See more details on using hashes here.

File details

Details for the file kavach_mcp-0.1.8-py3-none-any.whl.

File metadata

  • Download URL: kavach_mcp-0.1.8-py3-none-any.whl
  • Upload date:
  • Size: 7.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for kavach_mcp-0.1.8-py3-none-any.whl
Algorithm Hash digest
SHA256 ae0f6be926d27ceac196831bb1c73d1116ec373196505ea985e0daa05a3ad54f
MD5 fafe00c11af1f51a715ea5b5f11164e0
BLAKE2b-256 262984526b638d685051dc8118e5757f4014033b1220609c0eb80d8762f6747e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page