Metadata-Version: 2.4
Name: mcpknight
Version: 0.1.0
Summary: Active Runtime Security Firewall & Interceptor Gateway for Agent Tools & MCP Servers
License: Apache-2.0
Keywords: mcp,security,firewall,llm,ai,claude,cursor,zero-trust,prompt-injection
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: typer>=0.12.0
Requires-Dist: rich>=13.0.0
Requires-Dist: pydantic>=2.0
Requires-Dist: loguru>=0.7.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"

# MCPSentinel

**Active Zero-Trust Runtime Security Firewall & Interceptor Gateway for AI Agent Tools & MCP Servers.**

MCPSentinel provides real-time security gating for Agentic tools and MCP servers across 4 critical lifecycle phases:
1. **Pre-Registration Intent & Threat Inspection**: Static and semantic analysis detecting covert exfiltration, indirect prompt injection, privilege escalation, and schema manipulation.
2. **Pre-Execution Argument Gating**: Sandboxing and runtime inspection blocking unauthorized path traversal, command injection, and sensitive parameter overrides.
3. **Execution & Latency Profiling**: Tamper-proof telemetry profiling execution latency and outputs.
4. **Post-Execution Behavioral Drift Verification**: Intercepts outputs and quarantines tools exhibiting sudden behavioral shifts, capability creep, or mimicry attacks.

---

## ⚡ 1-Click Auto-Protect for Claude Desktop, Cursor & Codex

Instead of manually editing JSON configs, MCPSentinel can **automatically detect, backup, and wrap** all configured MCP servers with one command:

```bash
# Automatically scan & protect Claude Desktop, Cursor, and Codex / Claude Code configs
mcpsentinel protect

# Or target a specific application / config file
mcpsentinel protect --claude
mcpsentinel protect --cursor
mcpsentinel protect --codex
mcpsentinel protect --config /path/to/custom_mcp_config.json

# Restore / unwrap servers at any time
mcpsentinel unwrap
```

---

## 🔒 Transparent MCP Proxy (`mcpsentinel wrap`)

MCPSentinel can transparently wrap any standard MCP server over stdio without any code modifications.

### MCP Client Configuration (`claude_desktop_config.json`, Cursor, etc.)

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "mcpsentinel",
      "args": ["wrap", "npx", "@modelcontextprotocol/server-filesystem", "/workspace"]
    },
    "custom_server": {
      "command": "mcpsentinel",
      "args": ["wrap", "python3", "my_mcp_server.py"]
    }
  }
}
```

When wrapped, MCPSentinel automatically:
- Intercepts `tools/list` with zero startup handshake latency by caching tool definitions without eager evaluation.
- Intercepts `tools/call` requests with JIT Intent & Security Analysis upon first call, blocking malicious schemas, sensitive parameter overrides (e.g. `/etc/shadow`), and quarantined tools fail-fast before execution.
- Intercepts `tools/call` responses, detecting prompt injections and behavioral drift to suppress malicious payloads before they reach the LLM.

---

## 📊 Structured Logging & Telemetry (Loguru & Loki)

MCPSentinel provides dual real-time and persistent telemetry:

- **Stdio Safe**: Real-time console logs are streamed exclusively to `sys.stderr`, ensuring MCP JSON-RPC protocol messages over `stdout` are never corrupted.
- **Persistent Local Logs**:
  - Formatted text log: `~/.mcpsentinel/logs/mcpsentinel.log` (automatic 10MB rotation, 14-day retention).
  - Structured JSONL log: `~/.mcpsentinel/logs/mcpsentinel.jsonl` (machine-readable SIEM format).
- **Grafana Loki Streaming**: Set `MCPSENTINEL_LOKI_URL="http://localhost:3100"` to stream telemetry asynchronously in background daemon threads.

```bash
# Stream live logs with the built-in CLI monitor
mcpsentinel logs

# Follow only ERROR / WARNING logs
mcpsentinel logs --level ERROR

# View last 50 lines without following
mcpsentinel logs --no-follow -n 50

# Stream raw structured JSONL SIEM events
mcpsentinel logs --json

# Clear stored logs
mcpsentinel logs --clear
```

---

## 🛠️ Python SDK Usage

You can also protect native Python tools and functions directly using the `@firewall.protect` decorator:

```python
from mcpsentinel import RuntimeFirewall

firewall = RuntimeFirewall()

@firewall.protect()
def query_database(query: str) -> dict:
    """Executes a database query."""
    return {"status": "success", "rows": []}

# Calls are gated through pre-call checks and post-call drift verification
result = query_database(query="SELECT * FROM users")
```

---

## 💻 CLI Usage

MCPSentinel includes a full CLI powered by **Typer** and **Rich**.

### Installation

```bash
# Global installation via pipx / pip
pip install mcpsentinel
# or
pipx install mcpsentinel

# Or for local development:
pip install -e .
```

---

### Commands Overview

#### 1. Transparent MCP Server Wrap (`mcpsentinel wrap`)
```bash
mcpsentinel wrap npx @modelcontextprotocol/server-filesystem /tmp
```

#### 2. Auto-Protect MCP Client Configurations (`mcpsentinel protect`)
```bash
mcpsentinel protect --claude
mcpsentinel protect --cursor
mcpsentinel protect --codex
```

#### 3. Inspect / Analyze Tool Security (`mcpsentinel inspect`)
```bash
# Inspect via JSON string
mcpsentinel inspect --tool-json '{"name": "search_docs", "description": "Search public docs", "parameters": {"query": "string"}}'

# Inspect via JSON file
mcpsentinel inspect --file tool_definition.json
```

#### 4. Execute / Call Tools Through Firewall (`mcpsentinel call`)
```bash
# Call a safe tool
mcpsentinel call search_docs --tool-json '{"name": "search_docs"}' --arguments '{"query": "firewall"}'

# Malicious arguments will be blocked fail-fast
mcpsentinel call read_file --tool-json '{"name": "read_file"}' --arguments '{"path": "/etc/shadow"}'
```

#### 5. Manually Approve Blocked Tools (`mcpsentinel approve`)
```bash
mcpsentinel approve fetch_notes --operator alice --reviewer-note "Approved for restricted debug environment"
```

#### 6. Quarantine Management (`mcpsentinel quarantine`)
```bash
# List all quarantined tools
mcpsentinel quarantine list

# Check status of a specific tool
mcpsentinel quarantine status fetch_notes

# Release a tool from quarantine
mcpsentinel quarantine release fetch_notes --operator admin --reviewer-note "Audit resolved"
```

#### 7. Audit Trail (`mcpsentinel audit`)
```bash
mcpsentinel audit logs --limit 20
```

#### 8. Live Log Monitoring (`mcpsentinel logs` / `mcpsentinel monitor`)
```bash
# Follow formatted live logs
mcpsentinel logs

# Filter by log level
mcpsentinel logs --level WARNING

# Output in JSON format
mcpsentinel logs --json
```

---

## 📁 Project Structure

```text
mcpsentinel/
├── cli.py                         # Unified CLI entrypoint (Typer & Rich)
├── config_patcher.py              # Automatic client config scanner & patcher
├── firewall_cli.py                # Standalone firewall CLI interface
├── main.py                        # Top-level executable entry
├── mcp_firewall_client.py         # MCP Firewall client wrapper
├── mcp_proxy.py                   # Transparent stdio MCP JSON-RPC proxy gateway
├── runtime_firewall.py            # Core 4-phase runtime security firewall engine
├── sentinel_logger.py             # Dual console/file & Grafana Loki logger
├── pyproject.toml                 # Package metadata & build configuration
├── README.md                      # Project documentation
│
├── intent_analyser/               # Phase 1: Static & LLM semantic intent analysis
│   ├── static_analyser.py         # AST & regex threat pattern matching
│   ├── semantic_analyser.py       # Zero-dependency LLM caller (Ollama/OpenAI/Claude/Gemini/Groq)
│   └── schemas.py                 # Security intent schemas & data models
│
├── quarantine_engine/             # Quarantine persistence & manual review workflow
│   ├── quarantine_engine/
│   │   ├── core.py                # Quarantine manager core logic
│   │   ├── models.py              # Quarantine & audit state models
│   │   ├── audit_log.py           # Immutable audit logging engine
│   │   ├── version_store.py       # Schema & tool version store
│   │   └── analyzer_integration.py# Firewall integration hook
│   └── tests/                     # Quarantine unit test suite
│
├── trust_betray/                  # Phase 4: Post-execution drift & mimicry detection
│   ├── classifier.py              # Threat classification engine
│   ├── drift.py                   # Statistical & semantic drift analyzer
│   ├── fingerprint.py             # Behavioral fingerprinting
│   ├── store.py                   # Behavioral state storage
│   ├── timeline.py                # Event timeline generator
│   └── attacks/                   # Attack simulation modules (drift, mimicry, pivot)
│
└── tests/                         # Comprehensive pytest test suite
    ├── test_cli.py
    ├── test_config_patcher.py
    ├── test_firewall_cli.py
    ├── test_intent_analyser.py
    ├── test_intent_quarantine_integration.py
    ├── test_mcp_firewall_client.py
    ├── test_mcp_proxy.py
    ├── test_runtime_firewall.py
    ├── test_sentinel_logger.py
    └── test_trust_betray.py
```

---

## 🧪 Running Tests

Run the full pytest suite from the `mcpsentinel/` directory:

```bash
# Using pytest directly
python3 -m pytest

# Or using uv
uv run --with pytest pytest
```
