Skip to main content

MCP Security Framework

PyPI version Python 3.8+ License: MIT Code style: black Imports: isort

Universal security framework for microservices with SSL/TLS, authentication, authorization, and rate limiting.

Features

  • 🔐 Multi-method Authentication: API keys, JWT tokens, X.509 certificates
  • 🛡️ SSL/TLS Management: Server and client certificate handling
  • 🔑 Role-based Authorization: Flexible permission system with role hierarchy
  • ⚡ Rate Limiting: Configurable request rate limiting
  • 🚀 Framework Agnostic: Works with FastAPI, Flask, and standalone
  • 🛠️ CLI Tools: Certificate management and security testing
  • 📊 Comprehensive Logging: Security event logging and monitoring

Quick Start

Installation

# Basic installation
pip install mcp-security-framework

# With framework support
pip install mcp-security-framework[fastapi]
pip install mcp-security-framework[flask]

# Development installation
pip install mcp-security-framework[dev]

Basic Usage

from mcp_security_framework import SecurityManager, SecurityConfig
from mcp_security_framework.schemas.config import AuthConfig, PermissionConfig

# Create configuration
config = SecurityConfig(
    auth=AuthConfig(
        enabled=True,
        methods=["api_key"],
        api_keys={"admin": "admin_key_123"}
    ),
    permissions=PermissionConfig(
        roles={"admin": ["read", "write"]}
    )
)

# Create security manager
security_manager = SecurityManager(config)

# Validate request
result = security_manager.validate_request({
    "api_key": "admin_key_123",
    "required_permissions": ["read", "write"]
})

if result.is_valid:
    print("Access granted!")
else:
    print(f"Access denied: {result.error_message}")

FastAPI Integration

from mcp_security_framework import SecurityManager, SecurityConfig
from mcp_security_framework.schemas.config import AuthConfig, PermissionConfig

# Configuration
config = SecurityConfig(
    auth=AuthConfig(
        enabled=True,
        methods=["api_key", "jwt"],
        api_keys={"user": "user_key_456"},
        jwt_secret="your_jwt_secret_key"
    ),
    permissions=PermissionConfig()
)

# Create security manager
security_manager = SecurityManager(config)

# Create FastAPI middleware
security_middleware = security_manager.create_fastapi_middleware()

# The middleware is now ready to be integrated with your FastAPI application
# via the standard FastAPI middleware integration pattern

Flask Integration

from mcp_security_framework import SecurityManager, SecurityConfig
from mcp_security_framework.schemas.config import AuthConfig, PermissionConfig

# Configuration
config = SecurityConfig(
    auth=AuthConfig(
        enabled=True,
        methods=["api_key"]
    ),
    permissions=PermissionConfig()
)

# Create security manager
security_manager = SecurityManager(config)

# Create Flask middleware
security_middleware = security_manager.create_flask_middleware()

# The middleware can be integrated with your Flask application
# via: app.wsgi_app = security_middleware(app.wsgi_app)

CLI Tools

Certificate Management

# Create root CA
mcp-cert create-ca --ca-name "My Root CA" --output-dir ./certs

# Create client certificate
mcp-cert create-client-cert --name "client1" --roles "user,admin" --permissions "read,write"

# Create server certificate
mcp-cert create-server-cert --name "api-server" --domains "api.example.com"

Security Testing

# Validate configuration
mcp-security validate-config --config-file security_config.json

# Test authentication
mcp-security test-auth --config-file security_config.json --api-key "test_key"

Configuration

Basic Configuration File

{
  "ssl": {
    "enabled": true,
    "cert_file": "server.crt",
    "key_file": "server.key",
    "ca_cert_file": "ca.crt",
    "verify_mode": "CERT_REQUIRED",
    "min_version": "TLSv1.2"
  },
  "auth": {
    "enabled": true,
    "methods": ["api_key", "jwt", "certificate"],
    "api_keys": {
      "admin": "admin_key_123",
      "user": "user_key_456"
    },
    "jwt_secret": "your_jwt_secret_key",
    "jwt_expiry_hours": 24,
    "public_paths": ["/docs", "/health"]
  },
  "certificates": {
    "ca_dir": "./certs",
    "roles_oid": "1.3.6.1.4.1.99999.1.1",
    "permissions_oid": "1.3.6.1.4.1.99999.1.2",
    "verify_certificates": true,
    "check_revocation": true
  },
  "permissions": {
    "roles_file": "roles.json",
    "deny_by_default": true,
    "case_sensitive": false,
    "allow_wildcard": true
  },
  "rate_limit": {
    "enabled": true,
    "rate_limit": 100,
    "time_window": 60,
    "by_ip": true,
    "by_user": true
  }
}

Roles and Permissions

{
  "roles": {
    "admin": {
      "name": "admin",
      "description": "Administrator role",
      "permissions": ["read", "write", "delete", "admin"],
      "priority": 100
    },
    "user": {
      "name": "user",
      "description": "Regular user role",
      "permissions": ["read", "write"],
      "priority": 50
    },
    "guest": {
      "name": "guest",
      "description": "Guest role",
      "permissions": ["read"],
      "priority": 10
    }
  },
  "role_hierarchy": {
    "roles": {
      "admin": ["user"],
      "user": ["guest"]
    }
  },
  "default_policy": {
    "deny_by_default": true,
    "require_role_match": true,
    "case_sensitive": false,
    "allow_wildcard": true
  }
}

Wildcard Roles

Some deployments need to assign every available role to a token or certificate. The framework now supports the wildcard role marker * (aliases: all, any) in every configuration point that accepts role lists (API tokens, user role mappings, certificate roles, and validator inputs). When present, the wildcard:

  • Grants access to every role defined in the Permission Manager
  • Satisfies any allow_roles constraint in certificate validation
  • Automatically inherits all permissions associated with every configured role

Security note: wildcard roles implicitly include denied roles. If you add a wildcard token or certificate, ensure that deny_roles lists or permission policies explicitly guard sensitive actions. To block wildcard usage entirely, add "*" to the relevant deny list.

Documentation

Development

Setup Development Environment

# Clone repository
git clone https://github.com/mcp-security/mcp-security-framework.git
cd mcp-security-framework

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install development dependencies
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=mcp_security_framework --cov-report=html

# Run specific test categories
pytest -m unit
pytest -m integration
pytest -m "not slow"

Code Quality

# Run all tests and quality checks
python -m pipeline

# List all available checks
python -m pipeline --list

# Format code
black mcp_security_framework tests
isort mcp_security_framework tests

# Lint code
flake8 mcp_security_framework tests
mypy mcp_security_framework

Building Documentation

# Install documentation dependencies
pip install -e ".[docs]"

# Build documentation
sphinx-build -b html docs docs/_build/html

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass (pytest)
  6. Format and lint your code (black, isort, flake8, mypy)
  7. Commit your changes (git commit -m 'Add amazing feature')
  8. Push to the branch (git push origin feature/amazing-feature)
  9. Open a Pull Request

Security

If you discover a security vulnerability, please report it to us at security@mcp.example.com.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

See CHANGELOG.md for a list of changes and version history.

Metadata

Release files for mcp-security-framework 2.3.2

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

Source distribution (sdist)

Source distribution for mcp-security-framework 2.3.2
File Size Uploaded Provenance
mcp_security_framework-2.3.2.tar.gz 215.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for mcp-security-framework 2.3.2
File Interpreter ABI Platform
mcp_security_framework-2.3.2-py3-none-any.whl Python 3 none any Details

Total release size: 471.7 kB

Release files / mcp_security_framework-2.3.2.tar.gz

Download URL mcp_security_framework-2.3.2.tar.gz
Size 215.5 kB
Tags Source
SHA-256 checksum
How to use checksums
80813297c92327c824cbd98bb8667c753c1ce0d262e41edee5371595a5c0ba02
BLAKE2b-256 checksum
How to use checksums
e6874e030ebc51b882a3983d4fde2e8d84fd8eadb15bc5e9a3afbeae5489a36a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Release files / mcp_security_framework-2.3.2-py3-none-any.whl

Download URL mcp_security_framework-2.3.2-py3-none-any.whl
Size 256.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
12307497bc5c672c9c5f9b85328922265b552a21e47f50884ad2688d5d904ef9
BLAKE2b-256 checksum
How to use checksums
bf4ef22b8125dd6d649b72d47f75010909ffb62643f00c9a5961dfd4f455f129
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Security for mcp-security-framework 2.3.2

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

Release history Release notifications | RSS feed

This release

2.3.2 This release

2 release files No 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