mcp-guard-gateway 0.2.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 (35) hide show
  1. mcp_guard_gateway-0.2.0/LICENSE +21 -0
  2. mcp_guard_gateway-0.2.0/PKG-INFO +200 -0
  3. mcp_guard_gateway-0.2.0/README.md +175 -0
  4. mcp_guard_gateway-0.2.0/mcp_guard/__init__.py +0 -0
  5. mcp_guard_gateway-0.2.0/mcp_guard/api.py +113 -0
  6. mcp_guard_gateway-0.2.0/mcp_guard/audit.py +51 -0
  7. mcp_guard_gateway-0.2.0/mcp_guard/cli.py +142 -0
  8. mcp_guard_gateway-0.2.0/mcp_guard/demo/__init__.py +0 -0
  9. mcp_guard_gateway-0.2.0/mcp_guard/demo/complaint_server.py +72 -0
  10. mcp_guard_gateway-0.2.0/mcp_guard/demo/rogue_server.py +79 -0
  11. mcp_guard_gateway-0.2.0/mcp_guard/demo/sandbox_demo.py +67 -0
  12. mcp_guard_gateway-0.2.0/mcp_guard/detectors.py +207 -0
  13. mcp_guard_gateway-0.2.0/mcp_guard/engine.py +246 -0
  14. mcp_guard_gateway-0.2.0/mcp_guard/identity.py +36 -0
  15. mcp_guard_gateway-0.2.0/mcp_guard/init.py +159 -0
  16. mcp_guard_gateway-0.2.0/mcp_guard/owasp.py +22 -0
  17. mcp_guard_gateway-0.2.0/mcp_guard/policy.py +162 -0
  18. mcp_guard_gateway-0.2.0/mcp_guard/proxy.py +260 -0
  19. mcp_guard_gateway-0.2.0/mcp_guard/sandbox.py +115 -0
  20. mcp_guard_gateway-0.2.0/mcp_guard_gateway.egg-info/PKG-INFO +200 -0
  21. mcp_guard_gateway-0.2.0/mcp_guard_gateway.egg-info/SOURCES.txt +33 -0
  22. mcp_guard_gateway-0.2.0/mcp_guard_gateway.egg-info/dependency_links.txt +1 -0
  23. mcp_guard_gateway-0.2.0/mcp_guard_gateway.egg-info/entry_points.txt +2 -0
  24. mcp_guard_gateway-0.2.0/mcp_guard_gateway.egg-info/requires.txt +9 -0
  25. mcp_guard_gateway-0.2.0/mcp_guard_gateway.egg-info/top_level.txt +1 -0
  26. mcp_guard_gateway-0.2.0/pyproject.toml +42 -0
  27. mcp_guard_gateway-0.2.0/setup.cfg +4 -0
  28. mcp_guard_gateway-0.2.0/tests/test_api.py +131 -0
  29. mcp_guard_gateway-0.2.0/tests/test_attack_suite.py +12 -0
  30. mcp_guard_gateway-0.2.0/tests/test_detectors.py +53 -0
  31. mcp_guard_gateway-0.2.0/tests/test_engine.py +120 -0
  32. mcp_guard_gateway-0.2.0/tests/test_http.py +160 -0
  33. mcp_guard_gateway-0.2.0/tests/test_init.py +104 -0
  34. mcp_guard_gateway-0.2.0/tests/test_proxy.py +63 -0
  35. mcp_guard_gateway-0.2.0/tests/test_sandbox.py +96 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hardik Bahri
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,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-guard-gateway
3
+ Version: 0.2.0
4
+ Summary: Inline security gateway for AI agents and MCP tool servers: RBAC, prompt-injection and tool-misuse checks, DLP redaction, SIEM-ready audit logs.
5
+ Author: Hardik Bahri
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/hardikbahri/mcp-guard
8
+ Project-URL: Source, https://github.com/hardikbahri/mcp-guard
9
+ Keywords: mcp,model context protocol,ai agents,llm security,prompt injection,guardrails,owasp
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Security
12
+ Classifier: Intended Audience :: Developers
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: mcp>=2.3.0
17
+ Requires-Dist: pyyaml>=6.0
18
+ Requires-Dist: fastapi>=0.115
19
+ Requires-Dist: uvicorn>=0.30
20
+ Requires-Dist: pyjwt>=2.8
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=8; extra == "dev"
23
+ Requires-Dist: httpx>=0.27; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # MCP Guard
27
+
28
+ [![CI](https://github.com/hardikbahri/mcp-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/hardikbahri/mcp-guard/actions/workflows/ci.yml)
29
+
30
+ Inline security gateway for AI agents and MCP tool servers. It sits between an agent and its tools and checks every
31
+ tool listing, call and result, then **allows, alerts, redacts, blocks or terminates** by policy.
32
+
33
+ ```
34
+ agent <--MCP--> mcp-guard (policy + detectors + audit) <--MCP--> tool server
35
+ ```
36
+
37
+ Either side can be **stdio** (local processes) or **Streamable HTTP** (remote): put it in front of a local server, a
38
+ remote one, or serve a whole team's agents over HTTP.
39
+
40
+ Built in front of the [ComplaintOps](https://github.com/hardikbahri/complaintops) triage agent.
41
+
42
+ ## What it checks
43
+
44
+ | Check | OWASP Agentic Top 10 | Action |
45
+ | --- | --- | --- |
46
+ | Tool not granted to the user's role (RBAC, default deny); roles an agent claims are ignored unless the policy grants them | ASI03 Identity & Privilege Abuse | block, tool hidden from listing |
47
+ | Prompt injection in tool arguments (override phrases, chat markup, hidden Unicode, exfiltration directives) | ASI01 Agent Goal Hijack | alert or block, per tool |
48
+ | Instructions planted in tool **results** (indirect injection) before they reach the model | ASI06 Memory & Context Poisoning | injected sentence removed |
49
+ | Argument contract: unknown args, ranges, lengths, per-tool rate limits | ASI02 Tool Misuse | block |
50
+ | Shell, SQL, Python and path-traversal payloads in arguments | ASI05 Unexpected Code Execution | block |
51
+ | Poisoned tool descriptions, tool definitions changed after review (sha256 pins) | ASI04 Supply Chain | tool hidden |
52
+ | PII (email, phone, card with Luhn, SSN, Aadhaar, PAN, IBAN) and secrets leaving the boundary or entering model context | ASI03 / DLP | redacted |
53
+ | Session call budget exceeded, repeated violations | ASI08 Cascading Failures / ASI10 Rogue Agents | session terminated |
54
+ | A compromised tool server acting inside its own process (reading secrets, writing files, calling out, exhausting resources) | ASI05 Unexpected Code Execution / ASI04 Supply Chain | contained by the sandbox |
55
+
56
+ Every decision is written as one JSON line with Elastic Common Schema fields (`@timestamp`, `event.*`, `user.*`,
57
+ `rule.*`) so a log forwarder can ship it to Elastic, Splunk or Microsoft Sentinel. Values that were redacted are never logged.
58
+
59
+ ## Quickstart: put it in front of your MCP server
60
+
61
+ ```bash
62
+ pip install mcp-guard-gateway # or: pip install git+https://github.com/hardikbahri/mcp-guard
63
+
64
+ # 1. discover your server's tools and write a starter policy (mcp-guard.yaml)
65
+ mcp-guard init --upstream "python -m your_package.mcp_server" # or --upstream https://host/mcp
66
+
67
+ # 2. review it (every setting: docs/policy.md): split tools into roles, tighten limits, read the REVIEW comments
68
+ # leave tools out up front with --exclude run_report,notify_customer; then validate
69
+ mcp-guard check --upstream "python -m your_package.mcp_server"
70
+
71
+ # 3. point your MCP client at the gateway instead of the server (init prints this snippet)
72
+ ```
73
+
74
+ ```json
75
+ {
76
+ "mcpServers": {
77
+ "guarded-tools": {
78
+ "command": "mcp-guard",
79
+ "args": ["proxy"],
80
+ "env": {
81
+ "MCP_GUARD_UPSTREAM": "python -m your_package.mcp_server",
82
+ "MCP_GUARD_POLICY": "/path/to/mcp-guard.yaml",
83
+ "MCP_GUARD_USER": "my-agent",
84
+ "MCP_GUARD_AUDIT_LOG": "/path/to/audit.jsonl"
85
+ }
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ ### As an agent skill
92
+
93
+ `skill/mcp-guard/` is a `SKILL.md` skill that walks a coding agent (Claude Code, Cursor, Copilot and others) through
94
+ installing MCP Guard, generating and reviewing a policy with the user, and rewiring the client config, asking before
95
+ each change.
96
+
97
+ ### How configuration works
98
+
99
+ The full policy reference, with every setting, action and environment variable, is [docs/policy.md](docs/policy.md).
100
+
101
+
102
+ | What | Where | Example |
103
+ | --- | --- | --- |
104
+ | **Rules**: roles, users, per-tool argument limits, what to do on injection, PII, budgets, pins, sandbox | the policy YAML (`mcp-guard.yaml`) | `notify_customer: {egress: external, redact_pii_in_args: true}` |
105
+ | **Wiring**: which server, which policy, who the agent is, where the audit log goes | `MCP_GUARD_*` environment variables, or flags on `mcp-guard proxy` (flags win) | `mcp-guard proxy --upstream ... --policy ... --user my-agent` |
106
+ | **Secrets**: JWT secret, upstream token | environment variables only, never the YAML | `MCP_GUARD_JWT_SECRET`, `MCP_GUARD_UPSTREAM_TOKEN` |
107
+
108
+ `init` builds the starter policy from the server's own tool schemas: string limits from `maxLength`, number ranges from
109
+ `minimum`/`maximum`, `enum`s kept. Tools whose names suggest sending data out (email, notify, post, upload, webhook)
110
+ are marked `egress: external` with PII redaction, and the recipient field is allowed through. Tools whose names
111
+ suggest destructive or code-running actions (delete, exec, run, write) get a one-call budget and a REVIEW comment.
112
+ Every tool is pinned, so `mcp-guard check --upstream ...` reports a tool whose description or schema has changed.
113
+
114
+ `check` explains mistakes in plain language: a role granting a tool with no rules, a user with an undefined role, a
115
+ tool no role can reach, a misspelt setting, an external tool without PII redaction.
116
+
117
+ ## Run it (this repo)
118
+
119
+ ```bash
120
+ pip install -e ".[dev]"
121
+ # stdio gateway: point any MCP client at this instead of the real server
122
+ MCP_GUARD_UPSTREAM="python -m mcp_guard.demo.complaint_server" MCP_GUARD_USER=triage-bot python -m mcp_guard.proxy
123
+ # in front of a remote MCP server (Streamable HTTP)
124
+ MCP_GUARD_UPSTREAM="https://tools.example.com/mcp" MCP_GUARD_UPSTREAM_TOKEN=... python -m mcp_guard.proxy
125
+ # serve agents over HTTP at http://127.0.0.1:8090/mcp
126
+ MCP_GUARD_UPSTREAM="python -m mcp_guard.demo.complaint_server" MCP_GUARD_JWT_SECRET=... mcp-guard proxy --http --port 8090
127
+ # HTTP policy decision point (FastAPI), optional JWT identity via MCP_GUARD_JWT_SECRET
128
+ mcp-guard api --port 8080
129
+ # Docker (published image, or build it yourself)
130
+ docker run -p 8080:8080 ghcr.io/hardikbahri/mcp-guard:latest
131
+ docker build -t mcp-guard . && docker run -p 8080:8080 mcp-guard
132
+ # tests and the attack suite
133
+ pytest && python attacks/evaluate.py
134
+ ```
135
+
136
+ With `MCP_GUARD_JWT_SECRET` set, the API takes the user from the token's `sub` (claimed roles are kept only where the policy grants them), a session can only be used with a token for the same user, and `/v1/audit` needs a token with the `audit` scope.
137
+
138
+ CI runs the unit, API, proxy (stdio and HTTP) and attack-suite tests on Python 3.11 and 3.12, then builds the Docker image and checks that the container serves the API as a non-root user and blocks an out-of-role call. A third job builds the sandbox image and runs the compromised-server demo against a real container.
139
+
140
+ With ComplaintOps: `ComplaintAgent(server_module="mcp_guard.proxy")` with `MCP_GUARD_UPSTREAM="python -m complaintops.mcp_server"`.
141
+ In tests, a poisoned similar-complaint result reaches the agent's LLM without the gateway; through it, the planted
142
+ instruction and the personal data are removed.
143
+
144
+ ## Remote servers and HTTP agents
145
+
146
+ **Remote upstream.** Set `MCP_GUARD_UPSTREAM` to a URL and the gateway connects over Streamable HTTP, with
147
+ `MCP_GUARD_UPSTREAM_TOKEN` sent as a bearer token. A remote server runs on someone else's machine, so the risk shifts
148
+ from host compromise to what you send it and what it sends back: the same DLP redaction (for tools marked
149
+ `egress: external`), injection removal, RBAC and call budgets apply. The gateway refuses plain `http://` to anything
150
+ but this machine, and `upstream_allowed_hosts: [tools.example.com]` in the policy pins where tool traffic may go.
151
+
152
+ **HTTP downstream.** `mcp-guard proxy --http` serves MCP over Streamable HTTP. Each agent connection gets its own
153
+ Guard session (call budget, violation count, termination). With `MCP_GUARD_JWT_SECRET` set, every request needs a
154
+ bearer JWT and the user is its `sub`, so one gateway serves agents with different roles; a session cannot change
155
+ user mid-way. The gateway refuses to listen beyond localhost without JWT identity.
156
+
157
+ ## Sandbox
158
+
159
+ The checks above see what crosses the MCP boundary. They cannot see what a tool server does inside its own process: a
160
+ poisoned package or a bad update can read the host's API keys, write files or call out to the internet while its MCP
161
+ traffic stays perfectly clean. With a `sandbox:` section in the policy, the gateway starts the tool server in a
162
+ locked-down container instead of as a local process:
163
+
164
+ - no network (`--network none`), read-only filesystem, all Linux capabilities dropped, `no-new-privileges`
165
+ - non-root user, capped memory, CPU and process count, a small `noexec` `/tmp`
166
+ - only the environment variables the policy names, passed by name so values never appear on a command line
167
+
168
+ ```yaml
169
+ sandbox:
170
+ enabled: true
171
+ image: mcp-guard-sandbox:demo
172
+ network: none
173
+ memory: 256m
174
+ pids_limit: 64
175
+ env: [] # e.g. [COMPLAINTOPS_DB_URL]
176
+ ```
177
+
178
+ `mcp_guard/demo/sandbox_demo.py` runs the same compromised server (`mcp_guard/demo/rogue_server.py`) through the gateway twice. Both calls
179
+ are allowed, because the MCP traffic is harmless; the table shows what the hidden payload managed to do. CI runs it on
180
+ every push and fails if anything escapes the sandbox. Result from CI (GitHub Actions runner):
181
+
182
+ | What the compromised server tried | Without sandbox | With sandbox |
183
+ | --- | --- | --- |
184
+ | Read an API key from the gateway's environment | yes | no |
185
+ | Wrote a file next to its code | yes | no |
186
+ | Opened a connection to the internet | yes | no |
187
+ | Threads started (of 200) | 200 | 61 (process limit 64) |
188
+
189
+ ```bash
190
+ docker build -f Dockerfile.sandbox -t mcp-guard-sandbox:demo .
191
+ python -m mcp_guard.demo.sandbox_demo
192
+ ```
193
+
194
+ Without the sandbox, a policy can still limit what an unsandboxed server inherits with `upstream_env: [NAME, ...]`.
195
+
196
+ ## Limits
197
+
198
+ Detectors are rule-based and deterministic, so every decision is explainable and testable. The attack suite in
199
+ `attacks/` was written alongside the rules, so it shows coverage, not real-world accuracy; paraphrased or translated
200
+ injections can get past regex rules. A learned classifier and an external benchmark are next.
@@ -0,0 +1,175 @@
1
+ # MCP Guard
2
+
3
+ [![CI](https://github.com/hardikbahri/mcp-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/hardikbahri/mcp-guard/actions/workflows/ci.yml)
4
+
5
+ Inline security gateway for AI agents and MCP tool servers. It sits between an agent and its tools and checks every
6
+ tool listing, call and result, then **allows, alerts, redacts, blocks or terminates** by policy.
7
+
8
+ ```
9
+ agent <--MCP--> mcp-guard (policy + detectors + audit) <--MCP--> tool server
10
+ ```
11
+
12
+ Either side can be **stdio** (local processes) or **Streamable HTTP** (remote): put it in front of a local server, a
13
+ remote one, or serve a whole team's agents over HTTP.
14
+
15
+ Built in front of the [ComplaintOps](https://github.com/hardikbahri/complaintops) triage agent.
16
+
17
+ ## What it checks
18
+
19
+ | Check | OWASP Agentic Top 10 | Action |
20
+ | --- | --- | --- |
21
+ | Tool not granted to the user's role (RBAC, default deny); roles an agent claims are ignored unless the policy grants them | ASI03 Identity & Privilege Abuse | block, tool hidden from listing |
22
+ | Prompt injection in tool arguments (override phrases, chat markup, hidden Unicode, exfiltration directives) | ASI01 Agent Goal Hijack | alert or block, per tool |
23
+ | Instructions planted in tool **results** (indirect injection) before they reach the model | ASI06 Memory & Context Poisoning | injected sentence removed |
24
+ | Argument contract: unknown args, ranges, lengths, per-tool rate limits | ASI02 Tool Misuse | block |
25
+ | Shell, SQL, Python and path-traversal payloads in arguments | ASI05 Unexpected Code Execution | block |
26
+ | Poisoned tool descriptions, tool definitions changed after review (sha256 pins) | ASI04 Supply Chain | tool hidden |
27
+ | PII (email, phone, card with Luhn, SSN, Aadhaar, PAN, IBAN) and secrets leaving the boundary or entering model context | ASI03 / DLP | redacted |
28
+ | Session call budget exceeded, repeated violations | ASI08 Cascading Failures / ASI10 Rogue Agents | session terminated |
29
+ | A compromised tool server acting inside its own process (reading secrets, writing files, calling out, exhausting resources) | ASI05 Unexpected Code Execution / ASI04 Supply Chain | contained by the sandbox |
30
+
31
+ Every decision is written as one JSON line with Elastic Common Schema fields (`@timestamp`, `event.*`, `user.*`,
32
+ `rule.*`) so a log forwarder can ship it to Elastic, Splunk or Microsoft Sentinel. Values that were redacted are never logged.
33
+
34
+ ## Quickstart: put it in front of your MCP server
35
+
36
+ ```bash
37
+ pip install mcp-guard-gateway # or: pip install git+https://github.com/hardikbahri/mcp-guard
38
+
39
+ # 1. discover your server's tools and write a starter policy (mcp-guard.yaml)
40
+ mcp-guard init --upstream "python -m your_package.mcp_server" # or --upstream https://host/mcp
41
+
42
+ # 2. review it (every setting: docs/policy.md): split tools into roles, tighten limits, read the REVIEW comments
43
+ # leave tools out up front with --exclude run_report,notify_customer; then validate
44
+ mcp-guard check --upstream "python -m your_package.mcp_server"
45
+
46
+ # 3. point your MCP client at the gateway instead of the server (init prints this snippet)
47
+ ```
48
+
49
+ ```json
50
+ {
51
+ "mcpServers": {
52
+ "guarded-tools": {
53
+ "command": "mcp-guard",
54
+ "args": ["proxy"],
55
+ "env": {
56
+ "MCP_GUARD_UPSTREAM": "python -m your_package.mcp_server",
57
+ "MCP_GUARD_POLICY": "/path/to/mcp-guard.yaml",
58
+ "MCP_GUARD_USER": "my-agent",
59
+ "MCP_GUARD_AUDIT_LOG": "/path/to/audit.jsonl"
60
+ }
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ ### As an agent skill
67
+
68
+ `skill/mcp-guard/` is a `SKILL.md` skill that walks a coding agent (Claude Code, Cursor, Copilot and others) through
69
+ installing MCP Guard, generating and reviewing a policy with the user, and rewiring the client config, asking before
70
+ each change.
71
+
72
+ ### How configuration works
73
+
74
+ The full policy reference, with every setting, action and environment variable, is [docs/policy.md](docs/policy.md).
75
+
76
+
77
+ | What | Where | Example |
78
+ | --- | --- | --- |
79
+ | **Rules**: roles, users, per-tool argument limits, what to do on injection, PII, budgets, pins, sandbox | the policy YAML (`mcp-guard.yaml`) | `notify_customer: {egress: external, redact_pii_in_args: true}` |
80
+ | **Wiring**: which server, which policy, who the agent is, where the audit log goes | `MCP_GUARD_*` environment variables, or flags on `mcp-guard proxy` (flags win) | `mcp-guard proxy --upstream ... --policy ... --user my-agent` |
81
+ | **Secrets**: JWT secret, upstream token | environment variables only, never the YAML | `MCP_GUARD_JWT_SECRET`, `MCP_GUARD_UPSTREAM_TOKEN` |
82
+
83
+ `init` builds the starter policy from the server's own tool schemas: string limits from `maxLength`, number ranges from
84
+ `minimum`/`maximum`, `enum`s kept. Tools whose names suggest sending data out (email, notify, post, upload, webhook)
85
+ are marked `egress: external` with PII redaction, and the recipient field is allowed through. Tools whose names
86
+ suggest destructive or code-running actions (delete, exec, run, write) get a one-call budget and a REVIEW comment.
87
+ Every tool is pinned, so `mcp-guard check --upstream ...` reports a tool whose description or schema has changed.
88
+
89
+ `check` explains mistakes in plain language: a role granting a tool with no rules, a user with an undefined role, a
90
+ tool no role can reach, a misspelt setting, an external tool without PII redaction.
91
+
92
+ ## Run it (this repo)
93
+
94
+ ```bash
95
+ pip install -e ".[dev]"
96
+ # stdio gateway: point any MCP client at this instead of the real server
97
+ MCP_GUARD_UPSTREAM="python -m mcp_guard.demo.complaint_server" MCP_GUARD_USER=triage-bot python -m mcp_guard.proxy
98
+ # in front of a remote MCP server (Streamable HTTP)
99
+ MCP_GUARD_UPSTREAM="https://tools.example.com/mcp" MCP_GUARD_UPSTREAM_TOKEN=... python -m mcp_guard.proxy
100
+ # serve agents over HTTP at http://127.0.0.1:8090/mcp
101
+ MCP_GUARD_UPSTREAM="python -m mcp_guard.demo.complaint_server" MCP_GUARD_JWT_SECRET=... mcp-guard proxy --http --port 8090
102
+ # HTTP policy decision point (FastAPI), optional JWT identity via MCP_GUARD_JWT_SECRET
103
+ mcp-guard api --port 8080
104
+ # Docker (published image, or build it yourself)
105
+ docker run -p 8080:8080 ghcr.io/hardikbahri/mcp-guard:latest
106
+ docker build -t mcp-guard . && docker run -p 8080:8080 mcp-guard
107
+ # tests and the attack suite
108
+ pytest && python attacks/evaluate.py
109
+ ```
110
+
111
+ With `MCP_GUARD_JWT_SECRET` set, the API takes the user from the token's `sub` (claimed roles are kept only where the policy grants them), a session can only be used with a token for the same user, and `/v1/audit` needs a token with the `audit` scope.
112
+
113
+ CI runs the unit, API, proxy (stdio and HTTP) and attack-suite tests on Python 3.11 and 3.12, then builds the Docker image and checks that the container serves the API as a non-root user and blocks an out-of-role call. A third job builds the sandbox image and runs the compromised-server demo against a real container.
114
+
115
+ With ComplaintOps: `ComplaintAgent(server_module="mcp_guard.proxy")` with `MCP_GUARD_UPSTREAM="python -m complaintops.mcp_server"`.
116
+ In tests, a poisoned similar-complaint result reaches the agent's LLM without the gateway; through it, the planted
117
+ instruction and the personal data are removed.
118
+
119
+ ## Remote servers and HTTP agents
120
+
121
+ **Remote upstream.** Set `MCP_GUARD_UPSTREAM` to a URL and the gateway connects over Streamable HTTP, with
122
+ `MCP_GUARD_UPSTREAM_TOKEN` sent as a bearer token. A remote server runs on someone else's machine, so the risk shifts
123
+ from host compromise to what you send it and what it sends back: the same DLP redaction (for tools marked
124
+ `egress: external`), injection removal, RBAC and call budgets apply. The gateway refuses plain `http://` to anything
125
+ but this machine, and `upstream_allowed_hosts: [tools.example.com]` in the policy pins where tool traffic may go.
126
+
127
+ **HTTP downstream.** `mcp-guard proxy --http` serves MCP over Streamable HTTP. Each agent connection gets its own
128
+ Guard session (call budget, violation count, termination). With `MCP_GUARD_JWT_SECRET` set, every request needs a
129
+ bearer JWT and the user is its `sub`, so one gateway serves agents with different roles; a session cannot change
130
+ user mid-way. The gateway refuses to listen beyond localhost without JWT identity.
131
+
132
+ ## Sandbox
133
+
134
+ The checks above see what crosses the MCP boundary. They cannot see what a tool server does inside its own process: a
135
+ poisoned package or a bad update can read the host's API keys, write files or call out to the internet while its MCP
136
+ traffic stays perfectly clean. With a `sandbox:` section in the policy, the gateway starts the tool server in a
137
+ locked-down container instead of as a local process:
138
+
139
+ - no network (`--network none`), read-only filesystem, all Linux capabilities dropped, `no-new-privileges`
140
+ - non-root user, capped memory, CPU and process count, a small `noexec` `/tmp`
141
+ - only the environment variables the policy names, passed by name so values never appear on a command line
142
+
143
+ ```yaml
144
+ sandbox:
145
+ enabled: true
146
+ image: mcp-guard-sandbox:demo
147
+ network: none
148
+ memory: 256m
149
+ pids_limit: 64
150
+ env: [] # e.g. [COMPLAINTOPS_DB_URL]
151
+ ```
152
+
153
+ `mcp_guard/demo/sandbox_demo.py` runs the same compromised server (`mcp_guard/demo/rogue_server.py`) through the gateway twice. Both calls
154
+ are allowed, because the MCP traffic is harmless; the table shows what the hidden payload managed to do. CI runs it on
155
+ every push and fails if anything escapes the sandbox. Result from CI (GitHub Actions runner):
156
+
157
+ | What the compromised server tried | Without sandbox | With sandbox |
158
+ | --- | --- | --- |
159
+ | Read an API key from the gateway's environment | yes | no |
160
+ | Wrote a file next to its code | yes | no |
161
+ | Opened a connection to the internet | yes | no |
162
+ | Threads started (of 200) | 200 | 61 (process limit 64) |
163
+
164
+ ```bash
165
+ docker build -f Dockerfile.sandbox -t mcp-guard-sandbox:demo .
166
+ python -m mcp_guard.demo.sandbox_demo
167
+ ```
168
+
169
+ Without the sandbox, a policy can still limit what an unsandboxed server inherits with `upstream_env: [NAME, ...]`.
170
+
171
+ ## Limits
172
+
173
+ Detectors are rule-based and deterministic, so every decision is explainable and testable. The attack suite in
174
+ `attacks/` was written alongside the rules, so it shows coverage, not real-world accuracy; paraphrased or translated
175
+ injections can get past regex rules. A learned classifier and an external benchmark are next.
File without changes
@@ -0,0 +1,113 @@
1
+ """HTTP policy decision point, for gateways that are not MCP-over-stdio (an AI gateway, an API management layer, a
2
+ developer agent's hook). The caller asks before forwarding a tool call and again before handing a result to the model.
3
+
4
+ uvicorn mcp_guard.api:app --port 8080
5
+
6
+ Identity: when MCP_GUARD_JWT_SECRET is set, every call needs `Authorization: Bearer <JWT>` (HS256). Opening a session
7
+ makes the token's `sub` the user; roles claimed in the token are kept only where the policy grants them to that user.
8
+ Later calls on a session must carry a token for the same user, and reading the audit log needs a token whose `scope`
9
+ includes `audit`. Without the secret (local development) the user is taken from the request body and nothing is checked.
10
+ """
11
+ import os
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from fastapi import FastAPI, Header, HTTPException
16
+ from pydantic import BaseModel
17
+
18
+ from mcp_guard import identity
19
+ from mcp_guard import policy as policy_mod
20
+ from mcp_guard.audit import AuditLog
21
+ from mcp_guard.engine import Decision, Guard, Session
22
+
23
+ POLICY = str(policy_mod.default_path())
24
+ guard = Guard(policy_mod.load(POLICY), AuditLog())
25
+ sessions: dict[str, Session] = {}
26
+ app = FastAPI(title="MCP Guard", version="0.1.0",
27
+ description="Security checks for AI agent tool traffic: RBAC, prompt injection, tool misuse, DLP.")
28
+
29
+
30
+ class OpenSession(BaseModel):
31
+ user: str | None = None
32
+
33
+
34
+ class ToolList(BaseModel):
35
+ tools: list[dict[str, Any]]
36
+
37
+
38
+ class ToolCall(BaseModel):
39
+ tool: str
40
+ arguments: dict[str, Any] = {}
41
+
42
+
43
+ class ToolResult(BaseModel):
44
+ tool: str
45
+ result: Any
46
+
47
+
48
+ def _claims(authorization: str | None) -> dict | None:
49
+ try:
50
+ return identity.claims(authorization)
51
+ except identity.AuthError as e:
52
+ raise HTTPException(e.status, str(e)) from e
53
+
54
+
55
+ def _identity(authorization: str | None, body_user: str | None) -> tuple[str, list[str] | None]:
56
+ claims = _claims(authorization)
57
+ if claims is None:
58
+ if not body_user:
59
+ raise HTTPException(400, "user is required")
60
+ return body_user, None
61
+ return claims["sub"], claims.get("roles")
62
+
63
+
64
+ def _session(sid: str, authorization: str | None) -> Session:
65
+ if sid not in sessions:
66
+ raise HTTPException(404, "unknown session")
67
+ s = sessions[sid]
68
+ claims = _claims(authorization)
69
+ if claims is not None and claims["sub"] != s.user:
70
+ raise HTTPException(403, "session belongs to another user")
71
+ return s
72
+
73
+
74
+ def _out(d: Decision) -> dict:
75
+ return {"action": d.action, "forward": d.forwarded, "message": d.message,
76
+ "findings": [f.to_dict() for f in d.findings], "arguments": d.arguments, "result": d.result}
77
+
78
+
79
+ @app.get("/healthz")
80
+ def healthz():
81
+ return {"status": "ok", "tools_in_policy": sorted(guard.policy.tools)}
82
+
83
+
84
+ @app.post("/v1/sessions")
85
+ def open_session(body: OpenSession, authorization: str | None = Header(default=None)):
86
+ user, claimed = _identity(authorization, body.user)
87
+ s = guard.open_session(user, claimed)
88
+ sessions[s.id] = s
89
+ return {"session_id": s.id, "user": s.user, "roles": sorted(s.roles),
90
+ "permitted_tools": sorted(guard.policy.permitted_tools(s.roles))}
91
+
92
+
93
+ @app.post("/v1/sessions/{sid}/tools")
94
+ def filter_tools(sid: str, body: ToolList, authorization: str | None = Header(default=None)):
95
+ return {"tools": guard.visible_tools(_session(sid, authorization), body.tools)}
96
+
97
+
98
+ @app.post("/v1/sessions/{sid}/check-call")
99
+ def check_call(sid: str, body: ToolCall, authorization: str | None = Header(default=None)):
100
+ return _out(guard.check_call(_session(sid, authorization), body.tool, body.arguments))
101
+
102
+
103
+ @app.post("/v1/sessions/{sid}/check-result")
104
+ def check_result(sid: str, body: ToolResult, authorization: str | None = Header(default=None)):
105
+ return _out(guard.check_result(_session(sid, authorization), body.tool, body.result))
106
+
107
+
108
+ @app.get("/v1/audit")
109
+ def audit(limit: int = 50, authorization: str | None = Header(default=None)):
110
+ claims = _claims(authorization)
111
+ if claims is not None and "audit" not in str(claims.get("scope", "")).split():
112
+ raise HTTPException(403, "audit scope required")
113
+ return {"events": list(guard.audit.recent)[-max(1, min(limit, 1000)):]}
@@ -0,0 +1,51 @@
1
+ """Audit log: one JSON object per decision, one per line (JSON Lines).
2
+
3
+ Field names follow the Elastic Common Schema (`@timestamp`, `event.*`, `user.*`, `rule.*`), so the file can be shipped
4
+ as-is to Elastic, Splunk or Microsoft Sentinel by any log forwarder. Redacted values are never written; only the kind
5
+ of data found and where.
6
+ """
7
+ import collections
8
+ import json
9
+ import os
10
+ import sys
11
+ import threading
12
+ from datetime import datetime, timezone
13
+
14
+ SEVERITY = {"low": 21, "medium": 47, "high": 73, "critical": 99} # ECS risk-score style numbers
15
+
16
+
17
+ class AuditLog:
18
+ def __init__(self, path: str | None = None, keep: int = 1000, echo_stderr: bool = False):
19
+ self.path = path if path is not None else os.environ.get("MCP_GUARD_AUDIT_LOG", "audit.jsonl")
20
+ self.recent = collections.deque(maxlen=keep)
21
+ self.echo_stderr = echo_stderr
22
+ self._lock = threading.Lock()
23
+
24
+ def write(self, *, action: str, decision, session, tool: str | None = None) -> dict:
25
+ findings = [f.to_dict() for f in decision.findings]
26
+ worst = max((f["severity"] for f in findings), key=lambda s: SEVERITY[s], default=None)
27
+ rec = {
28
+ "@timestamp": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
29
+ "event": {
30
+ "kind": "alert" if findings else "event",
31
+ "category": ["intrusion_detection"] if findings else ["process"],
32
+ "action": action,
33
+ "outcome": "success" if decision.action in ("allow", "alert", "redact") else "failure",
34
+ "severity": SEVERITY[worst] if worst else 0,
35
+ },
36
+ "user": {"name": session.user, "roles": sorted(session.roles)},
37
+ "session": {"id": session.id, "calls": session.total_calls, "violations": session.violations},
38
+ "mcp_guard": {"decision": decision.action, "tool": tool, "message": decision.message,
39
+ "owasp": sorted({f["owasp"] for f in findings})},
40
+ "rule": {"name": [f["rule"] for f in findings]},
41
+ "findings": findings,
42
+ }
43
+ line = json.dumps(rec, ensure_ascii=False)
44
+ with self._lock:
45
+ self.recent.append(rec)
46
+ if self.path:
47
+ with open(self.path, "a", encoding="utf-8") as fh:
48
+ fh.write(line + "\n")
49
+ if self.echo_stderr:
50
+ print(line, file=sys.stderr, flush=True)
51
+ return rec