Skip to main content

Kavach Shield

Security middleware and detection engine for FastMCP servers.

Install

pip install kavach-shield

For local development:

pip install -e .

kavach-shield depends on fastmcp, kavach-logger, and kavach-mcp-events.

Built-In Rules

KAVACH_RULES includes regex rules for:

  • Prompt injection.
  • Data exfiltration.
  • PII-like numbers.
  • Secret/API key leakage.
  • Dangerous eval/exec/subprocess patterns.
  • SQL injection patterns.

Each rule is a Rule(id, name, severity, description, patterns) dataclass.

Detection Engine

from kavach_shield import DetectionEngine, KAVACH_RULES

engine = DetectionEngine(KAVACH_RULES)
violations = engine.scan("ignore all previous instructions")

for violation in violations:
    print(violation["rule"], violation["severity"])

scan(text) returns dictionaries with rule, name, and severity.

FastMCP Middleware

from fastmcp import FastMCP
from kavach_shield import KavachMiddleware

mcp = FastMCP("Shielded Server")

shield = KavachMiddleware(
    strict=True,
    sensitive_tools=["execute_*", "db_*", "delete_*"],
)

mcp.add_middleware(shield)

Middleware behavior:

  • Emits pre_tool_call before every tool call.
  • Scans inbound arguments only for tools matching sensitive_tools.
  • Scans outbound responses for all tools.
  • Emits security_check when rules match.
  • Emits tool_error when a wrapped tool raises.
  • Emits post_tool_call after successful execution.
  • Masks sensitive strings in string responses and FastMCP text content.

In strict=True, violations raise SecurityException. In strict=False, violations are logged and emitted without blocking.

Custom Rules

import re
from kavach_shield import KavachMiddleware, Rule

custom_rules = [
    Rule(
        id="command-injection",
        name="Command Injection",
        severity="high",
        description="Shell command separators and risky binaries",
        patterns=[
            re.compile(r"(;|&&|\|\||`|\$\()", re.I),
            re.compile(r"\b(rm|curl|wget|bash|sh)\b", re.I),
        ],
    )
]

shield = KavachMiddleware(
    rules=custom_rules,
    extend_rules=True,  # default: append custom rules to KAVACH_RULES
    strict=True,
)

Set extend_rules=False to use only the rules you pass.

Sensitive Tools

Sensitive tools support shell-style wildcards via fnmatch:

shield = KavachMiddleware(sensitive_tools=["db_*", "file_write", "execute_*"])
shield.register_tool("admin_delete_user")

Events

from kavach_events import MCP_HOOKS, event_manager

@event_manager.subscribe([MCP_HOOKS.SECURITY_CHECK], tools=["*"])
async def log_security(payload):
    print(payload["tool_name"], payload.get("violations", []))

Event payloads include tool_name, arguments, context, is_sensitive, and event-specific fields such as violations, stage, response, or error.

Static Processing

For non-MCP payloads:

from kavach_shield import KavachMiddleware

shield = KavachMiddleware(strict=True)
result = shield.process({"tool": "db_query", "query": "select 1"})

Returns {"allowed": True, "data": ...} or raises SecurityException in strict mode.

Metadata

Release files for kavach-shield 0.0.3

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

Source distribution (sdist)

Source distribution for kavach-shield 0.0.3
File Size Uploaded Provenance
kavach_shield-0.0.3.tar.gz 6.4 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for kavach-shield 0.0.3
File Interpreter ABI Platform
kavach_shield-0.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 13.7 kB

Release files / kavach_shield-0.0.3.tar.gz

Download URL kavach_shield-0.0.3.tar.gz
Size 6.4 kB
Tags Source
SHA-256 checksum
How to use checksums
d221cf11d620c7fe5256b60f991ba9d33eccee5e6f3075f95ef4a75e072a125c
BLAKE2b-256 checksum
How to use checksums
2be61825c8c2ab8d37429f5ca7f803d04f02c617b6a1365b6ac28e0a13c5c6d7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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 Jun 13, 2026.

Transparency log

Release files / kavach_shield-0.0.3-py3-none-any.whl

Download URL kavach_shield-0.0.3-py3-none-any.whl
Size 7.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
76e81f3ee17ce2388656c2640411537ed96bb8ceb7c3201a6970d8039de7ee0e
BLAKE2b-256 checksum
How to use checksums
697352a6b7b31535c4446aec60f69705fa61057c11a356d938ea406b222ebdd6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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 Jun 13, 2026.

Transparency log

Security for kavach-shield 0.0.3

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.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kavach_shield-0.0.3.tar.gz

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 Jun 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.3 This release

2 release files Full provenance

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