Skip to main content

Security middleware for Model Context Protocol (MCP) - detection engine and rules

Project description

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.

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_shield-0.0.3.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

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

kavach_shield-0.0.3-py3-none-any.whl (7.4 kB view details)

Uploaded Python 3

File details

Details for the file kavach_shield-0.0.3.tar.gz.

File metadata

  • Download URL: kavach_shield-0.0.3.tar.gz
  • Upload date:
  • Size: 6.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for kavach_shield-0.0.3.tar.gz
Algorithm Hash digest
SHA256 d221cf11d620c7fe5256b60f991ba9d33eccee5e6f3075f95ef4a75e072a125c
MD5 04a4b3e52b17e7c23a5cea42a72a9a2f
BLAKE2b-256 2be61825c8c2ab8d37429f5ca7f803d04f02c617b6a1365b6ac28e0a13c5c6d7

See more details on using hashes here.

Provenance

The following attestation bundles were made for kavach_shield-0.0.3.tar.gz:

Publisher: upload_python_package.yml on shivamnamdeo0101/kavach-agent-ecosystem

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file kavach_shield-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: kavach_shield-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 7.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for kavach_shield-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 76e81f3ee17ce2388656c2640411537ed96bb8ceb7c3201a6970d8039de7ee0e
MD5 dd156323424847e040a88de5f4955016
BLAKE2b-256 697352a6b7b31535c4446aec60f69705fa61057c11a356d938ea406b222ebdd6

See more details on using hashes here.

Provenance

The following attestation bundles were made for kavach_shield-0.0.3-py3-none-any.whl:

Publisher: upload_python_package.yml on shivamnamdeo0101/kavach-agent-ecosystem

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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