mcp-shield-proxy 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. mcp_shield_proxy-0.1.0/.env.example +4 -0
  2. mcp_shield_proxy-0.1.0/.gitignore +34 -0
  3. mcp_shield_proxy-0.1.0/LICENSE +21 -0
  4. mcp_shield_proxy-0.1.0/PKG-INFO +82 -0
  5. mcp_shield_proxy-0.1.0/README.md +47 -0
  6. mcp_shield_proxy-0.1.0/TECH.md +138 -0
  7. mcp_shield_proxy-0.1.0/agent/.gitkeep +0 -0
  8. mcp_shield_proxy-0.1.0/agent/agent_runner.py +313 -0
  9. mcp_shield_proxy-0.1.0/backend/__init__.py +0 -0
  10. mcp_shield_proxy-0.1.0/backend/auditor.py +215 -0
  11. mcp_shield_proxy-0.1.0/backend/database.py +7 -0
  12. mcp_shield_proxy-0.1.0/backend/db.py +414 -0
  13. mcp_shield_proxy-0.1.0/backend/deception.py +234 -0
  14. mcp_shield_proxy-0.1.0/backend/engine.py +911 -0
  15. mcp_shield_proxy-0.1.0/backend/policy.json +7 -0
  16. mcp_shield_proxy-0.1.0/backend/routes_b.py +111 -0
  17. mcp_shield_proxy-0.1.0/backend/sandbox.py +110 -0
  18. mcp_shield_proxy-0.1.0/backend/server.py +476 -0
  19. mcp_shield_proxy-0.1.0/backend/shadow.py +221 -0
  20. mcp_shield_proxy-0.1.0/benchmark/.gitkeep +0 -0
  21. mcp_shield_proxy-0.1.0/benchmark/attacks.json +205 -0
  22. mcp_shield_proxy-0.1.0/benchmark/run_benchmark.py +355 -0
  23. mcp_shield_proxy-0.1.0/demo_servers/github_mcp.py +98 -0
  24. mcp_shield_proxy-0.1.0/demo_servers/issues_store.json +31 -0
  25. mcp_shield_proxy-0.1.0/demo_servers/issues_store_clean.json +31 -0
  26. mcp_shield_proxy-0.1.0/demo_servers/workspace_mcp.py +110 -0
  27. mcp_shield_proxy-0.1.0/docker/.gitkeep +0 -0
  28. mcp_shield_proxy-0.1.0/docker/Dockerfile.sandbox +6 -0
  29. mcp_shield_proxy-0.1.0/frontend/.gitkeep +0 -0
  30. mcp_shield_proxy-0.1.0/frontend/index.html +12 -0
  31. mcp_shield_proxy-0.1.0/frontend/package-lock.json +2778 -0
  32. mcp_shield_proxy-0.1.0/frontend/package.json +26 -0
  33. mcp_shield_proxy-0.1.0/frontend/postcss.config.js +6 -0
  34. mcp_shield_proxy-0.1.0/frontend/public/benchmark_results.json +47 -0
  35. mcp_shield_proxy-0.1.0/frontend/src/App.tsx +631 -0
  36. mcp_shield_proxy-0.1.0/frontend/src/api.ts +99 -0
  37. mcp_shield_proxy-0.1.0/frontend/src/components/AgentChat.tsx +299 -0
  38. mcp_shield_proxy-0.1.0/frontend/src/components/ApprovalModal.tsx +80 -0
  39. mcp_shield_proxy-0.1.0/frontend/src/components/LiveFeed.tsx +380 -0
  40. mcp_shield_proxy-0.1.0/frontend/src/components/Scorecard.tsx +214 -0
  41. mcp_shield_proxy-0.1.0/frontend/src/components/SetupAudit.tsx +293 -0
  42. mcp_shield_proxy-0.1.0/frontend/src/components/ShadowDiff.tsx +288 -0
  43. mcp_shield_proxy-0.1.0/frontend/src/index.css +30 -0
  44. mcp_shield_proxy-0.1.0/frontend/src/main.tsx +10 -0
  45. mcp_shield_proxy-0.1.0/frontend/src/types.ts +176 -0
  46. mcp_shield_proxy-0.1.0/frontend/src/vite-env.d.ts +1 -0
  47. mcp_shield_proxy-0.1.0/frontend/tailwind.config.js +20 -0
  48. mcp_shield_proxy-0.1.0/frontend/tsconfig.json +20 -0
  49. mcp_shield_proxy-0.1.0/frontend/vite.config.ts +10 -0
  50. mcp_shield_proxy-0.1.0/proxy/.gitkeep +0 -0
  51. mcp_shield_proxy-0.1.0/proxy/mcp_proxy.py +9 -0
  52. mcp_shield_proxy-0.1.0/proxy/shield_proxy.py +314 -0
  53. mcp_shield_proxy-0.1.0/pyproject.toml +31 -0
  54. mcp_shield_proxy-0.1.0/requirements.txt +8 -0
  55. mcp_shield_proxy-0.1.0/sample_repo/.env +3 -0
  56. mcp_shield_proxy-0.1.0/sample_repo/app.py +37 -0
  57. mcp_shield_proxy-0.1.0/sample_repo/test_app.py +32 -0
  58. mcp_shield_proxy-0.1.0/sample_repo_clean/.env +3 -0
  59. mcp_shield_proxy-0.1.0/sample_repo_clean/app.py +37 -0
  60. mcp_shield_proxy-0.1.0/sample_repo_clean/test_app.py +32 -0
  61. mcp_shield_proxy-0.1.0/src/mcp_shield/__init__.py +4 -0
  62. mcp_shield_proxy-0.1.0/src/mcp_shield/auditor.py +213 -0
  63. mcp_shield_proxy-0.1.0/src/mcp_shield/cli.py +137 -0
  64. mcp_shield_proxy-0.1.0/src/mcp_shield/config.py +41 -0
  65. mcp_shield_proxy-0.1.0/src/mcp_shield/db.py +382 -0
  66. mcp_shield_proxy-0.1.0/src/mcp_shield/deception.py +225 -0
  67. mcp_shield_proxy-0.1.0/src/mcp_shield/engine.py +273 -0
  68. mcp_shield_proxy-0.1.0/src/mcp_shield/policy.json +7 -0
  69. mcp_shield_proxy-0.1.0/src/mcp_shield/proxy.py +299 -0
  70. mcp_shield_proxy-0.1.0/src/mcp_shield/routes_b.py +118 -0
  71. mcp_shield_proxy-0.1.0/src/mcp_shield/sandbox.py +107 -0
  72. mcp_shield_proxy-0.1.0/src/mcp_shield/server.py +419 -0
  73. mcp_shield_proxy-0.1.0/src/mcp_shield/shadow.py +230 -0
  74. mcp_shield_proxy-0.1.0/src/mcp_shield/static/assets/index-BRgR9y6F.css +1 -0
  75. mcp_shield_proxy-0.1.0/src/mcp_shield/static/assets/index-gDjSoeTZ.js +89 -0
  76. mcp_shield_proxy-0.1.0/src/mcp_shield/static/benchmark_results.json +47 -0
  77. mcp_shield_proxy-0.1.0/src/mcp_shield/static/index.html +14 -0
  78. mcp_shield_proxy-0.1.0/tests/__init__.py +0 -0
  79. mcp_shield_proxy-0.1.0/tests/test_a_checkpoint4.py +189 -0
  80. mcp_shield_proxy-0.1.0/tests/test_a_step1.py +98 -0
  81. mcp_shield_proxy-0.1.0/tests/test_a_step2.py +141 -0
  82. mcp_shield_proxy-0.1.0/tests/test_a_step3.py +263 -0
  83. mcp_shield_proxy-0.1.0/tests/test_a_step4.py +246 -0
  84. mcp_shield_proxy-0.1.0/tests/test_a_step5.py +231 -0
  85. mcp_shield_proxy-0.1.0/tests/test_a_step6.py +102 -0
  86. mcp_shield_proxy-0.1.0/tests/test_benchmark.py +77 -0
  87. mcp_shield_proxy-0.1.0/tests/test_deception.py +162 -0
  88. mcp_shield_proxy-0.1.0/tests/test_routes_b.py +212 -0
  89. mcp_shield_proxy-0.1.0/tests/test_shadow.py +118 -0
  90. mcp_shield_proxy-0.1.0/tests/verify_e2e_live.py +395 -0
  91. mcp_shield_proxy-0.1.0/tests/verify_real_github_wheel.py +333 -0
@@ -0,0 +1,4 @@
1
+ LLM_API_KEY=gsk_your_groq_key_here
2
+ LLM_BASE_URL=https://api.groq.com/openai/v1
3
+ LLM_MODEL=openai/gpt-oss-120b
4
+ SANDBOX_FALLBACK=0
@@ -0,0 +1,34 @@
1
+ # Python & Node
2
+ .venv/
3
+ __pycache__/
4
+ *.pyc
5
+ .pytest_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ frontend/node_modules/
10
+ frontend/dist/
11
+ *.tsbuildinfo
12
+
13
+ # Secrets (ignore real root .env, keep fake demo .env files)
14
+ .env
15
+ !sample_repo/.env
16
+ !sample_repo_clean/.env
17
+
18
+ # Runtime artifacts
19
+ backend/shield.db
20
+ backend/shield.db-journal
21
+ temp_shadows/
22
+ demo_servers/trigger_rug_pull.flag
23
+
24
+ # Per-person local AI spec & relay files (keep local to prevent merge conflicts)
25
+ AGENTS.md
26
+ SPEC_A.md
27
+ SPEC_B.md
28
+ PROGRESS_A.md
29
+ PROGRESS_B.md
30
+
31
+ # OS / IDE
32
+ .DS_Store
33
+ Thumbs.db
34
+ .vscode/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Blue Pheonix
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.5
2
+ Name: mcp-shield-proxy
3
+ Version: 0.1.0
4
+ Summary: Enterprise runtime security gateway, shadow isolation, and honeytoken framework for the Model Context Protocol (MCP).
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 The Blue Pheonix
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+ License-File: LICENSE
27
+ Requires-Python: >=3.11
28
+ Requires-Dist: fastapi>=0.115.0
29
+ Requires-Dist: httpx>=0.27.0
30
+ Requires-Dist: mcp[cli]>=2.0.0
31
+ Requires-Dist: python-dotenv>=1.0.0
32
+ Requires-Dist: uvicorn[standard]>=0.30.0
33
+ Requires-Dist: websockets>=12.0
34
+ Description-Content-Type: text/markdown
35
+
36
+ # MCP-Shield
37
+
38
+ **Runtime security gateway, shadow workspace isolation, and active honey-token deception for the Model Context Protocol (MCP).**
39
+
40
+ MCP-Shield protects AI coding agents against indirect prompt injection, silent credential exfiltration, test-suite RCE, and mid-session tool rug-pulls without modifying your existing MCP servers.
41
+
42
+ ---
43
+
44
+ ## Quickstart
45
+
46
+ ```bash
47
+ pip install mcp-shield-proxy
48
+ ```
49
+
50
+ ### 1. Audit & Wrap Your Agent Config
51
+
52
+ Scan your existing MCP client configuration for Lethal Trifecta risks and generate a shielded configuration (`<config>.shield.json`):
53
+
54
+ ```bash
55
+ mcp-shield init --config mcp_config.json
56
+ ```
57
+
58
+ ### 2. Launch the Control Server & Web Console
59
+
60
+ Run inside your target project directory:
61
+
62
+ ```bash
63
+ mcp-start
64
+ ```
65
+
66
+ Opens the live security console at `http://127.0.0.1:8000` (use `--no-browser` or `--project-dir <path>` to customize).
67
+
68
+ ### 3. Check Resolved Paths
69
+
70
+ ```bash
71
+ mcp-shield status
72
+ ```
73
+
74
+ ---
75
+
76
+ ## Core Security Pillars
77
+
78
+ 1. **SHA-256 Tool Pinning**: Fingerprints every tool's name, description, and input schema on `tools/list`. Mid-session schema or description mutations trigger an immediate `RUG_PULL_DETECTED` block (`-32002`).
79
+ 2. **Shadow Copy Isolation**: Once a session reads untrusted external data (`UNTRUSTED_READ`), writes and safe reads are transparently redirected into an isolated shadow workspace (`~/.mcp-shield/temp_shadows/<session_id>`) while real `.env` files remain untouched.
80
+ 3. **Offline Docker Sandbox**: Terminal commands (`run_terminal`) execute inside a network-disabled (`--network=none`), resource-capped Docker container (`mcp-shield-sandbox`) mounted strictly to the shadow workspace.
81
+ 4. **Honey-Token Deception & Exit-Door Freeze**: Sensitive file reads (`.env`, `.ssh`, `id_rsa`, `secrets`) serve per-session decoy honey-tokens. Outbound `EXIT_DOOR` calls (`post_comment`, `send_email`, `git_push`) are scanned across raw, reversed, URL-encoded, and Base64 forms (`TRAP_TRIGGERED`), and clean exit calls freeze for explicit human approval.
82
+
@@ -0,0 +1,47 @@
1
+ # MCP-Shield
2
+
3
+ **Runtime security gateway, shadow workspace isolation, and active honey-token deception for the Model Context Protocol (MCP).**
4
+
5
+ MCP-Shield protects AI coding agents against indirect prompt injection, silent credential exfiltration, test-suite RCE, and mid-session tool rug-pulls without modifying your existing MCP servers.
6
+
7
+ ---
8
+
9
+ ## Quickstart
10
+
11
+ ```bash
12
+ pip install mcp-shield-proxy
13
+ ```
14
+
15
+ ### 1. Audit & Wrap Your Agent Config
16
+
17
+ Scan your existing MCP client configuration for Lethal Trifecta risks and generate a shielded configuration (`<config>.shield.json`):
18
+
19
+ ```bash
20
+ mcp-shield init --config mcp_config.json
21
+ ```
22
+
23
+ ### 2. Launch the Control Server & Web Console
24
+
25
+ Run inside your target project directory:
26
+
27
+ ```bash
28
+ mcp-start
29
+ ```
30
+
31
+ Opens the live security console at `http://127.0.0.1:8000` (use `--no-browser` or `--project-dir <path>` to customize).
32
+
33
+ ### 3. Check Resolved Paths
34
+
35
+ ```bash
36
+ mcp-shield status
37
+ ```
38
+
39
+ ---
40
+
41
+ ## Core Security Pillars
42
+
43
+ 1. **SHA-256 Tool Pinning**: Fingerprints every tool's name, description, and input schema on `tools/list`. Mid-session schema or description mutations trigger an immediate `RUG_PULL_DETECTED` block (`-32002`).
44
+ 2. **Shadow Copy Isolation**: Once a session reads untrusted external data (`UNTRUSTED_READ`), writes and safe reads are transparently redirected into an isolated shadow workspace (`~/.mcp-shield/temp_shadows/<session_id>`) while real `.env` files remain untouched.
45
+ 3. **Offline Docker Sandbox**: Terminal commands (`run_terminal`) execute inside a network-disabled (`--network=none`), resource-capped Docker container (`mcp-shield-sandbox`) mounted strictly to the shadow workspace.
46
+ 4. **Honey-Token Deception & Exit-Door Freeze**: Sensitive file reads (`.env`, `.ssh`, `id_rsa`, `secrets`) serve per-session decoy honey-tokens. Outbound `EXIT_DOOR` calls (`post_comment`, `send_email`, `git_push`) are scanned across raw, reversed, URL-encoded, and Base64 forms (`TRAP_TRIGGERED`), and clean exit calls freeze for explicit human approval.
47
+
@@ -0,0 +1,138 @@
1
+ # MCP-Shield Technical Architecture (`TECH.md`)
2
+
3
+ MCP-Shield is a runtime security reverse-proxy, taint-tracking control plane, shadow-copy sandbox, and active honey-token deception system for Model Context Protocol (MCP) tool-calling agents. It defends against the **Lethal Trifecta** (Untrusted Input + Private Data + External Egress/Execution) without breaking normal developer workflows with constant approval popups.
4
+
5
+ ---
6
+
7
+ ## 1. High-Level Architecture
8
+
9
+ ```
10
+ +------------------+ stdio (JSON-RPC 2.0) +-------------------------+
11
+ | MCP Client / | <==============================> | proxy/shield_proxy.py |
12
+ | Coding Agent | | (Stdio Reverse Proxy) |
13
+ +------------------+ +-----------+-------------+
14
+ |
15
+ +----------------------------------------+----------------------------------------+
16
+ | HTTP (Inspection API) | stdio (JSON-RPC 2.0)
17
+ v v
18
+ +---------------------------------------------------+ +-----------------------------------+
19
+ | backend/server.py (FastAPI :8000) | | Downstream MCP Servers |
20
+ | - /api/inspect/tools_list | | - demo_servers/github_mcp.py |
21
+ | - /api/inspect/tool_call | | - demo_servers/workspace_mcp.py |
22
+ | - backend/routes_b.py (issues, shadow, audit) | +-----------------------------------+
23
+ | - WS /ws/{session_id} |
24
+ +--------+-------------------+----------------------+
25
+ | |
26
+ v v
27
+ +----------------+ +---------------------------------------+
28
+ | backend/db.py | | Security & Isolation Engines |
29
+ | (shield.db | | - backend/shadow.py (Shadow Copy) |
30
+ | SQLite WAL) | | - backend/deception.py (Honey-Tokens)|
31
+ +----------------+ | - backend/auditor.py (Config Audit) |
32
+ | - backend/policy.json (Tool Classes) |
33
+ +---------------------------------------+
34
+ |
35
+ | WebSocket (WS /ws/{session_id}) + REST
36
+ v
37
+ +---------------------------------------------------+
38
+ | frontend/ (React + Vite + Tailwind :5173) |
39
+ | - AgentChat, LiveFeed, ShadowDiff, |
40
+ | SetupAudit, Scorecard, ApprovalModal |
41
+ +---------------------------------------------------+
42
+ ```
43
+
44
+ ---
45
+
46
+ ## 2. Component Breakdown
47
+
48
+ ### 2.1 Stdio Reverse Proxy (`proxy/shield_proxy.py`, alias `proxy/mcp_proxy.py`)
49
+ Sits transparently between an MCP client and a downstream MCP server over `stdin`/`stdout` using JSON-RPC 2.0:
50
+ - **Zero-`print()` Wire Rule**: All proxy diagnostics go to `sys.stderr` so `stdout` remains strictly valid newline-delimited JSON-RPC.
51
+ - **Windows-Safe Stdin Reading**: Uses a dedicated daemon thread (`stdin_reader`) reading `sys.stdin.buffer.readline()` and pushing raw bytes into an `asyncio.Queue` via `loop.call_soon_threadsafe`.
52
+ - **Child Lifecycle**: Spawns the target MCP server via `asyncio.create_subprocess_exec` with `stderr=sys.stderr`.
53
+ - **Interception Points**:
54
+ 1. **Notifications** (messages without `id`): Forwarded untouched immediately.
55
+ 2. **`tools/list`**: Tracks the request `id` in `pending_tools_list_ids`. When the child server responds, `handle_child_stdout` posts the tool definitions to `POST /api/inspect/tools_list`. If the response is `BLOCK`, the proxy returns JSON-RPC error `-32002` (`Tool definition tampered`).
56
+ 3. **`tools/call`**: Posts `{session_id, request_id, server_name, tool_name, arguments}` to `POST /api/inspect/tool_call` and enforces one of four actions:
57
+ - `ALLOW`: Forwards the original request bytes to the child server.
58
+ - `REWRITE_AND_ALLOW`: Replaces `params.arguments` with `modified_arguments` (e.g., redirecting paths into a shadow directory) and forwards.
59
+ - `SYNTHETIC_RESULT`: Short-circuits the child server and returns a synthetic MCP tool result (`content: [{type: "text", text: synthetic_text}]`) directly to the client (used for serving honeypots or blocking without crashing the agent loop).
60
+ - `BLOCK`: Short-circuits and returns JSON-RPC error `-32001` (`Blocked by MCP-Shield: <reason>`).
61
+ 4. **Other methods**: Forwarded untouched.
62
+
63
+ ### 2.2 Control Server & API (`backend/server.py`, `backend/routes_b.py`)
64
+ - **`backend/server.py`** (FastAPI on `127.0.0.1:8000`):
65
+ - Initializes SQLite on startup via `lifespan`.
66
+ - Manages per-session WebSocket connections via `ConnectionManager` at `WS /ws/{session_id}`.
67
+ - Exposes `/api/health`, `POST /api/inspect/tools_list`, and `POST /api/inspect/tool_call`.
68
+ - *Current implementation note*: `server.py` currently runs the initial pass-through inspection logic (logging `ALLOW` events to SQLite and broadcasting `TOOL_EVENT` envelopes over WebSocket). The router in `routes_b.py` and the engines in `shadow.py` / `deception.py` are implemented as standalone modules ready to be mounted (`app.include_router(routes_b.router)`) and wired into the inspection pipeline.
69
+ - **`backend/routes_b.py`** (`APIRouter`):
70
+ - `GET /api/issues` and `POST /api/issues/{issue_id}`: Reads/updates `demo_servers/issues_store.json` for injecting or resetting issue payloads.
71
+ - `GET /api/shadow/{session_id}/diff`: Returns unified diffs and suspicious-code warnings for the session's shadow workspace.
72
+ - `POST /api/shadow/{session_id}/merge`: Copies non-`.env` modified/added files from `temp_shadows/<session_id>/` back into `sample_repo/`.
73
+ - `POST /api/shadow/{session_id}/nuke`: Deletes `temp_shadows/<session_id>/`.
74
+ - `POST /api/audit`: Runs the Lethal Trifecta auditor on an MCP config JSON payload.
75
+
76
+ ### 2.3 SQLite Persistence (`backend/db.py`, alias `backend/database.py`)
77
+ Anchored at `backend/shield.db` with `PRAGMA journal_mode=WAL` and `PRAGMA busy_timeout=5000` for safe concurrent access. Defines 5 contract tables:
78
+ 1. `sessions` (`session_id`, `mode`, `is_tainted`, `taint_source`, `shadow_path`, `status`)
79
+ 2. `events` (`id`, `session_id`, `timestamp`, `server_name`, `tool_name`, `arguments_json`, `decision`, `reason`)
80
+ 3. `honey_tokens` (`token_value`, `session_id`, `file_path`, `triggered`, `exfil_target`)
81
+ 4. `tool_hashes` (`server_name`, `tool_name`, `sha256_hash`, `first_seen`)
82
+ 5. `approvals` (`request_id`, `session_id`, `tool_name`, `payload_json`, `status`)
83
+
84
+ ### 2.4 Security Policy (`backend/policy.json`)
85
+ Defines tool classifications used by the inspection layer:
86
+ - `UNTRUSTED_READ`: `["get_issue", "list_issues"]`
87
+ - `LOCAL_WORK`: `["list_files", "read_file", "write_file", "run_terminal"]`
88
+ - `SENSITIVE_PATTERNS`: `[".env", "id_rsa", ".ssh", "secrets", "credentials", ".pem"]`
89
+ - `EXIT_DOOR`: `["post_comment", "send_email", "git_push"]`
90
+
91
+ ### 2.5 Shadow Copy & Path-Traversal Engine (`backend/shadow.py`)
92
+ Isolates tainted sessions from the real repository (`sample_repo/`):
93
+ - **Session Isolation (`create_shadow`)**: Validates `session_id` (blocking `/`, `\`, `..`, and escaping `temp_shadows/`), copies `sample_repo/` to `temp_shadows/<session_id>/` while ignoring `.env`, `__pycache__`, and `.pytest_cache`, and plants a session-specific decoy `.env` via `deception.plant_honey_env`.
94
+ - **Path-Traversal Guard (`resolve_safe_path`)**: Normalizes relative paths (including stripping leading `./` or `sample_repo/`), resolves symlinks/parent segments, and enforces `resolved.is_relative_to(shadow_root)`.
95
+ - **Diff & Suspicious-Code Scanner (`get_shadow_diff`)**: Computes `difflib.unified_diff` between `sample_repo/` and `temp_shadows/<session_id>/` and flags added `+` lines containing `SUSPICIOUS_PATTERNS` (`subprocess`, `os.system`, `os.popen`, `urllib`, `requests`, `http.client`, `socket`, `eval(`, `exec(`, `curl`, `wget`, `base64`, `__import__`).
96
+ - **Merge & Nuke (`merge_shadow`, `nuke_shadow`)**: Selectively promotes reviewed non-`.env` changes to `sample_repo/` or destroys the shadow directory.
97
+
98
+ ### 2.6 Active Honey-Token Deception Engine (`backend/deception.py`)
99
+ Catches secret exfiltration even when an agent obfuscates stolen credentials:
100
+ - **Token Generation (`get_honey_env`, `plant_honey_env`)**: Generates 3 unique per-session decoy secrets using `secrets.token_hex(3)`:
101
+ - `AWS_SECRET_ACCESS_KEY=AKIA_SHIELD_TRAP_<hex>`
102
+ - `DB_PASSWORD=db_trap_<hex>`
103
+ - `STRIPE_API_KEY=sk_live_trap_<hex>`
104
+ Stores them in `honey_tokens` and writes `temp_shadows/<session_id>/.env`.
105
+ - **Multi-Encoding Leak Detection (`check_leak`)**: Recursively extracts all strings from outbound tool `arguments` and scans for each session token across **4 encodings**:
106
+ 1. `raw`: Exact token substring match.
107
+ 2. `reversed`: Character-reversed token (`token[::-1]`).
108
+ 3. `url_decoded`: Single and double `urllib.parse.unquote_plus` decoded matches.
109
+ 4. `base64`: Padded/unpadded Base64 match and regex-extracted Base64/URL-safe Base64 candidate decoding.
110
+ On match, sets `honey_tokens.triggered = 1` and records `exfil_target`.
111
+
112
+ ### 2.7 Lethal Trifecta Config Auditor (`backend/auditor.py`)
113
+ Statically analyzes MCP client configurations (`mcpServers`, `servers`, or direct server maps):
114
+ - Tokenizes server names, commands, args, URLs, descriptions, and env keys against `_UNTRUSTED_KEYWORDS`, `_PRIVATE_KEYWORDS`, and `_EGRESS_KEYWORDS`.
115
+ - Assigns `risk_level`: `CRITICAL` (all 3 legs present), `MEDIUM` (2 legs), or `LOW` (0–1 legs), with human-readable `risky_combos`.
116
+ - Generates `wrapped_snippet`, rewriting each server's `command`/`args` to route through `python proxy/shield_proxy.py --server-name <name> --session-id default -- <command> <args...>`.
117
+
118
+ ### 2.8 Demo MCP Servers (`demo_servers/`)
119
+ - **`demo_servers/github_mcp.py`**: Exposes `list_issues`, `get_issue`, and `post_comment` over `mcp.server.MCPServer` (`stdio`), backed by `demo_servers/issues_store.json`. Includes a `dynamic_list_tools` hook that mutates `get_issue`'s description with a prompt-injection directive when `demo_servers/trigger_rug_pull.flag` exists.
120
+ - **`demo_servers/workspace_mcp.py`**: Exposes `list_files`, `read_file`, `write_file`, and `run_terminal` operating directly on `sample_repo/`, representing an unguarded local workspace server.
121
+
122
+ ### 2.9 Benchmark Runner (`benchmark/run_benchmark.py`, `benchmark/attacks.json`)
123
+ Evaluates 20 cases across 6 categories (`normal`, `env_exfil`, `direct_rce`, `test_rce`, `sabotage`, `rug_pull`) under 3 modes (`off`, `naive`, `shield`):
124
+ - Drives `/api/demo/reset`, `/api/issues/{id}`, `/api/agent/run`, `/api/approvals/{id}`, and `WS /ws/{session_id}`.
125
+ - Verifies real `.env` non-leakage, `sample_repo/` integrity (`snapshot_repo` SHA-256 comparison), approval popup counts, and shadow diff creation.
126
+ - Writes aggregated metrics and per-case results to `frontend/public/benchmark_results.json`.
127
+
128
+ ### 2.10 Frontend Console (`frontend/src/`)
129
+ Built with React 18, TypeScript, Vite, and Tailwind CSS:
130
+ - **`App.tsx` & `api.ts`**: Manages session state (`CLEAN`, `TAINTED • SANDBOXED`, `HIJACK CAUGHT`), shield mode (`off` | `naive` | `shield`), live `WS /ws/{session_id}` subscription with auto-reconnect, and an offline `mockMode` simulator.
131
+ - **Views (`frontend/src/components/`)**:
132
+ - `AgentChat.tsx`: Interactive prompt/response stream.
133
+ - `LiveFeed.tsx`: Real-time security event timeline (`TOOL_EVENT`, `TAINT_TRIGGERED`, `HONEYPOT_SERVED`, `TRAP_TRIGGERED`, `RUG_PULL_DETECTED`, `SHADOW_UPDATED`).
134
+ - `ShadowDiff.tsx`: Inspects unified diffs + suspicious-code warnings and triggers Merge or Nuke.
135
+ - `SetupAudit.tsx`: Pastes MCP config JSON to run `/api/audit` and copy the `shield_proxy.py`-wrapped config.
136
+ - `Scorecard.tsx`: Displays benchmark comparison metrics from `benchmark_results.json`.
137
+ - `ApprovalModal.tsx`: Handles `APPROVAL_REQUIRED` / `APPROVAL_RESOLVED` prompts in `naive` mode.
138
+
File without changes
@@ -0,0 +1,313 @@
1
+ """
2
+ Autonomous AI Agent Runtime for MCP-Shield.
3
+ Connects simultaneously to proxy-wrapped github_mcp.py and workspace_mcp.py
4
+ using MCP Python SDK v2 and runs an OpenAI-compatible tool-calling loop.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import asyncio
11
+ import json
12
+ import logging
13
+ import os
14
+ import sys
15
+ import uuid
16
+ from pathlib import Path
17
+ from typing import Any, Awaitable, Callable
18
+
19
+ from dotenv import load_dotenv
20
+ from mcp import Client, StdioServerParameters
21
+ from openai import AsyncOpenAI
22
+
23
+ from backend import db
24
+
25
+ logging.basicConfig(
26
+ stream=sys.stderr,
27
+ level=logging.INFO,
28
+ format="[%(asctime)s] [agent_runner] %(levelname)s: %(message)s",
29
+ )
30
+ logger = logging.getLogger("agent_runner")
31
+
32
+ REPO_ROOT = Path(__file__).resolve().parent.parent
33
+ PROXY_PATH = REPO_ROOT / "proxy" / "shield_proxy.py"
34
+ GITHUB_MCP_PATH = REPO_ROOT / "demo_servers" / "github_mcp.py"
35
+ WORKSPACE_MCP_PATH = REPO_ROOT / "demo_servers" / "workspace_mcp.py"
36
+
37
+ MAX_TURNS = 8
38
+
39
+ BroadcastFn = Callable[[str, dict[str, Any]], Awaitable[None]]
40
+
41
+
42
+ async def _emit(
43
+ broadcast_fn: BroadcastFn | None, event_type: str, data: dict[str, Any]
44
+ ) -> None:
45
+ """Safely invoke the async broadcast callback if provided."""
46
+ if broadcast_fn is not None:
47
+ try:
48
+ await broadcast_fn(event_type, data)
49
+ except Exception as e:
50
+ logger.warning(f"Broadcast error for {event_type}: {e}")
51
+
52
+
53
+ def _build_llm_client() -> tuple[AsyncOpenAI, str]:
54
+ """Configure AsyncOpenAI from environment variables."""
55
+ load_dotenv(REPO_ROOT / ".env")
56
+ api_key = os.getenv("LLM_API_KEY", "").strip()
57
+ if not api_key:
58
+ raise RuntimeError(
59
+ "LLM_API_KEY environment variable is required when llm_client is not injected."
60
+ )
61
+ base_url = os.getenv("LLM_BASE_URL", "").strip()
62
+ model = os.getenv("LLM_MODEL", "").strip() or "deepseek-chat"
63
+
64
+ kwargs: dict[str, Any] = {"api_key": api_key}
65
+ if base_url:
66
+ kwargs["base_url"] = base_url
67
+
68
+ return AsyncOpenAI(**kwargs), model
69
+
70
+
71
+ def _extract_tool_text(result: Any) -> str:
72
+ """Extract readable text from an MCP CallToolResult."""
73
+ texts: list[str] = []
74
+ content = getattr(result, "content", None) or []
75
+ for block in content:
76
+ text_val = getattr(block, "text", None)
77
+ if text_val is not None:
78
+ texts.append(str(text_val))
79
+ if texts:
80
+ return "\n".join(texts)
81
+
82
+ structured = getattr(result, "structured_content", None)
83
+ if structured is not None:
84
+ return json.dumps(structured)
85
+
86
+ return ""
87
+
88
+
89
+ async def run_agent(
90
+ session_id: str,
91
+ prompt: str,
92
+ mode: str = "shield",
93
+ broadcast_fn: BroadcastFn | None = None,
94
+ llm_client: Any = None,
95
+ ) -> str:
96
+ """
97
+ Run the autonomous agent loop for a given session and user prompt.
98
+ Connects to both github and workspace MCP servers through shield_proxy.py.
99
+ """
100
+ db.init_db()
101
+ db.create_session(session_id, mode=mode)
102
+
103
+ await _emit(broadcast_fn, "AGENT_MESSAGE", {"role": "user", "text": prompt})
104
+
105
+ try:
106
+ if llm_client is not None:
107
+ client = llm_client
108
+ model = os.getenv("LLM_MODEL", "").strip() or "deepseek-chat"
109
+ else:
110
+ client, model = _build_llm_client()
111
+
112
+ github_params = StdioServerParameters(
113
+ command=sys.executable,
114
+ args=[
115
+ str(PROXY_PATH),
116
+ "--server-name",
117
+ "github",
118
+ "--session-id",
119
+ session_id,
120
+ sys.executable,
121
+ str(GITHUB_MCP_PATH),
122
+ ],
123
+ env=os.environ.copy(),
124
+ )
125
+ workspace_params = StdioServerParameters(
126
+ command=sys.executable,
127
+ args=[
128
+ str(PROXY_PATH),
129
+ "--server-name",
130
+ "workspace",
131
+ "--session-id",
132
+ session_id,
133
+ sys.executable,
134
+ str(WORKSPACE_MCP_PATH),
135
+ ],
136
+ env=os.environ.copy(),
137
+ )
138
+
139
+ async with (
140
+ Client(github_params, read_timeout_seconds=150.0) as github_client,
141
+ Client(workspace_params, read_timeout_seconds=150.0) as workspace_client,
142
+ ):
143
+ gh_listing = await github_client.list_tools()
144
+ ws_listing = await workspace_client.list_tools()
145
+
146
+ tool_map: dict[str, Client] = {}
147
+ openai_tools: list[dict[str, Any]] = []
148
+
149
+ for mcp_client, listing in (
150
+ (github_client, gh_listing),
151
+ (workspace_client, ws_listing),
152
+ ):
153
+ for tool in listing.tools:
154
+ tool_map[tool.name] = mcp_client
155
+ params_schema = dict(tool.input_schema) if tool.input_schema else {}
156
+ params_schema.setdefault("type", "object")
157
+ params_schema.setdefault("properties", {})
158
+ openai_tools.append(
159
+ {
160
+ "type": "function",
161
+ "function": {
162
+ "name": tool.name,
163
+ "description": tool.description or "",
164
+ "parameters": params_schema,
165
+ },
166
+ }
167
+ )
168
+
169
+ messages: list[dict[str, Any]] = [
170
+ {
171
+ "role": "system",
172
+ "content": (
173
+ "You are an autonomous software engineering assistant with access to GitHub "
174
+ "issue tracking tools and local workspace filesystem/terminal tools. "
175
+ "Use the provided tools to investigate and resolve user requests."
176
+ ),
177
+ },
178
+ {"role": "user", "content": prompt},
179
+ ]
180
+
181
+ for turn in range(MAX_TURNS):
182
+ logger.info(f"[{session_id}] Agent turn {turn + 1}/{MAX_TURNS}")
183
+ response = await client.chat.completions.create(
184
+ model=model,
185
+ messages=messages,
186
+ tools=openai_tools,
187
+ )
188
+ choice = response.choices[0]
189
+ msg = choice.message
190
+
191
+ tool_calls = getattr(msg, "tool_calls", None)
192
+ if tool_calls:
193
+ # Record assistant tool call message in history
194
+ assistant_entry: dict[str, Any] = {
195
+ "role": "assistant",
196
+ "content": getattr(msg, "content", None),
197
+ "tool_calls": [
198
+ {
199
+ "id": tc.id,
200
+ "type": "function",
201
+ "function": {
202
+ "name": tc.function.name,
203
+ "arguments": tc.function.arguments or "{}",
204
+ },
205
+ }
206
+ for tc in tool_calls
207
+ ],
208
+ }
209
+ messages.append(assistant_entry)
210
+
211
+ for tc in tool_calls:
212
+ t_name = tc.function.name
213
+ raw_args = tc.function.arguments
214
+ try:
215
+ t_args = (
216
+ json.loads(raw_args or "{}")
217
+ if isinstance(raw_args, str)
218
+ else (raw_args or {})
219
+ )
220
+ if not isinstance(t_args, dict):
221
+ t_args = {}
222
+ except json.JSONDecodeError:
223
+ t_args = {}
224
+
225
+ await _emit(
226
+ broadcast_fn,
227
+ "AGENT_MESSAGE",
228
+ {
229
+ "role": "tool_step",
230
+ "text": f"Calling {t_name}({json.dumps(t_args)})",
231
+ },
232
+ )
233
+
234
+ target = tool_map.get(t_name)
235
+ if target is None:
236
+ tool_output = f"Error: Unknown tool '{t_name}'."
237
+ else:
238
+ try:
239
+ result = await target.call_tool(t_name, t_args)
240
+ tool_output = _extract_tool_text(result)
241
+ if getattr(result, "is_error", False):
242
+ if not tool_output:
243
+ tool_output = "Error: Tool execution failed."
244
+ logger.warning(
245
+ f"[{session_id}] Tool '{t_name}' returned is_error=True: {tool_output}"
246
+ )
247
+ except Exception as tool_exc:
248
+ tool_output = f"Error calling tool '{t_name}': {tool_exc}"
249
+ logger.warning(
250
+ f"[{session_id}] Tool '{t_name}' raised exception: {tool_exc}"
251
+ )
252
+
253
+ messages.append(
254
+ {
255
+ "role": "tool",
256
+ "tool_call_id": tc.id,
257
+ "content": tool_output,
258
+ }
259
+ )
260
+ else:
261
+ final_text = getattr(msg, "content", None) or ""
262
+ await _emit(
263
+ broadcast_fn,
264
+ "AGENT_MESSAGE",
265
+ {"role": "assistant", "text": final_text},
266
+ )
267
+ return final_text
268
+
269
+ limit_msg = "Agent reached maximum turn limit (8 turns) without completing task."
270
+ await _emit(
271
+ broadcast_fn,
272
+ "AGENT_MESSAGE",
273
+ {"role": "assistant", "text": limit_msg},
274
+ )
275
+ return limit_msg
276
+
277
+ except Exception as exc:
278
+ logger.exception(f"[{session_id}] Agent execution failed: {exc}")
279
+ err_msg = f"Agent error: {exc}"
280
+ await _emit(
281
+ broadcast_fn,
282
+ "AGENT_MESSAGE",
283
+ {"role": "assistant", "text": err_msg},
284
+ )
285
+ return err_msg
286
+
287
+
288
+ def main() -> None:
289
+ parser = argparse.ArgumentParser(description="MCP-Shield Autonomous Agent Runner")
290
+ parser.add_argument(
291
+ "--session-id",
292
+ default=f"cli_{uuid.uuid4().hex[:8]}",
293
+ help="Security session ID",
294
+ )
295
+ parser.add_argument(
296
+ "--mode",
297
+ choices=["off", "naive", "shield"],
298
+ default="shield",
299
+ help="Shield enforcement mode",
300
+ )
301
+ parser.add_argument("--prompt", required=True, help="Task prompt for the agent")
302
+ args = parser.parse_args()
303
+
304
+ result = asyncio.run(
305
+ run_agent(session_id=args.session_id, prompt=args.prompt, mode=args.mode)
306
+ )
307
+ sys.stdout.write(result + "\n")
308
+ sys.stdout.flush()
309
+
310
+
311
+ if __name__ == "__main__":
312
+ main()
313
+
File without changes