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:
- Tool call intercepted by
on_call_tool()middleware hook - Tool name matched against
sensitive_toolspatterns - If matched,
DetectionEnginescans arguments against rules - If violations found and strict mode enabled → raises
SecurityException - Otherwise → chain to next middleware
Rules
Detects:
- 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 hookregister_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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kavach_mcp-0.1.7.tar.gz.
File metadata
- Download URL: kavach_mcp-0.1.7.tar.gz
- Upload date:
- Size: 5.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7a40edcd22a028e5581e4310f0a32d239c8516927f89fcc4f0f3a02ff95e7351
|
|
| MD5 |
c0affb5f6aa3c772a84ea496cf22ebec
|
|
| BLAKE2b-256 |
dd9288fe45334006a4b0585e10ccdf72adfd41c139d501311fdb761e027ee410
|
Provenance
The following attestation bundles were made for kavach_mcp-0.1.7.tar.gz:
Publisher:
python-publish.yml on shivamnamdeo0101/kavach-mcp-middleware
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
kavach_mcp-0.1.7.tar.gz -
Subject digest:
7a40edcd22a028e5581e4310f0a32d239c8516927f89fcc4f0f3a02ff95e7351 - Sigstore transparency entry: 1732534275
- Sigstore integration time:
-
Permalink:
shivamnamdeo0101/kavach-mcp-middleware@e3b522e525a9ba0c5925beaf8f4a11d3892e2519 -
Branch / Tag:
refs/tags/v0.1.7 - Owner: https://github.com/shivamnamdeo0101
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@e3b522e525a9ba0c5925beaf8f4a11d3892e2519 -
Trigger Event:
release
-
Statement type:
File details
Details for the file kavach_mcp-0.1.7-py3-none-any.whl.
File metadata
- Download URL: kavach_mcp-0.1.7-py3-none-any.whl
- Upload date:
- Size: 6.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
28def43192393217d70a9e519a89be32e34ae9ec91ef656d136d1ca68825b92f
|
|
| MD5 |
e496a0982961ec75841e1e7d55fd1cdc
|
|
| BLAKE2b-256 |
c665ba6f733a76b9692866e8a4c3e02ee6f5bb42e77ae97435e324af5e91f6ed
|
Provenance
The following attestation bundles were made for kavach_mcp-0.1.7-py3-none-any.whl:
Publisher:
python-publish.yml on shivamnamdeo0101/kavach-mcp-middleware
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
kavach_mcp-0.1.7-py3-none-any.whl -
Subject digest:
28def43192393217d70a9e519a89be32e34ae9ec91ef656d136d1ca68825b92f - Sigstore transparency entry: 1732534319
- Sigstore integration time:
-
Permalink:
shivamnamdeo0101/kavach-mcp-middleware@e3b522e525a9ba0c5925beaf8f4a11d3892e2519 -
Branch / Tag:
refs/tags/v0.1.7 - Owner: https://github.com/shivamnamdeo0101
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@e3b522e525a9ba0c5925beaf8f4a11d3892e2519 -
Trigger Event:
release
-
Statement type: