mcp-guard-lite 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.
- mcp_guard_lite-0.1.0/.gitignore +6 -0
- mcp_guard_lite-0.1.0/CHANGELOG.md +15 -0
- mcp_guard_lite-0.1.0/LICENSE +21 -0
- mcp_guard_lite-0.1.0/PKG-INFO +151 -0
- mcp_guard_lite-0.1.0/README.md +131 -0
- mcp_guard_lite-0.1.0/SECURITY.md +9 -0
- mcp_guard_lite-0.1.0/benchmarks/inspect_guard.py +41 -0
- mcp_guard_lite-0.1.0/examples/approval.py +36 -0
- mcp_guard_lite-0.1.0/examples/host_check.py +29 -0
- mcp_guard_lite-0.1.0/examples/refund_approval.py +79 -0
- mcp_guard_lite-0.1.0/pyproject.toml +37 -0
- mcp_guard_lite-0.1.0/src/mcp_guard_lite/__init__.py +716 -0
- mcp_guard_lite-0.1.0/src/mcp_guard_lite/call_checks.py +44 -0
- mcp_guard_lite-0.1.0/src/mcp_guard_lite/canonical.py +117 -0
- mcp_guard_lite-0.1.0/src/mcp_guard_lite/checks.py +311 -0
- mcp_guard_lite-0.1.0/src/mcp_guard_lite/policy.py +141 -0
- mcp_guard_lite-0.1.0/src/mcp_guard_lite/py.typed +0 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
Initial development checkpoint for standalone inspection, canonical JSON, schema pinning, and tool handler wrappers.
|
|
6
|
+
|
|
7
|
+
Added versioned portable policy validation, scope selectors, default-deny decisions, and shared policy vectors.
|
|
8
|
+
|
|
9
|
+
Added bounded audit events, privacy regression tests, and fail-closed audit policy enforcement.
|
|
10
|
+
|
|
11
|
+
Added tenant-scoped session budgets, repeat detection, idle expiration, and wrapped-handler concurrency limits.
|
|
12
|
+
|
|
13
|
+
Added tool, path, network, and content checks, output modes, and single-use asynchronous approvals.
|
|
14
|
+
|
|
15
|
+
Added configurable resource limits, scoped host call checks, safe-field preservation, and optional output framing.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mcp-guard-lite contributors
|
|
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,151 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mcp-guard-lite
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency Model Context Protocol (MCP) security SDK for AI agents. Enforce tool policies, require approval, and redact sensitive results.
|
|
5
|
+
Project-URL: Homepage, https://github.com/mkkotcherla/mcp-guard-lite
|
|
6
|
+
Project-URL: Documentation, https://github.com/mkkotcherla/mcp-guard-lite/blob/main/docs/integration.md
|
|
7
|
+
Project-URL: Repository, https://github.com/mkkotcherla/mcp-guard-lite
|
|
8
|
+
Project-URL: Issues, https://github.com/mkkotcherla/mcp-guard-lite/issues
|
|
9
|
+
Author: Kotcherla Murali Krishna
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai-agents,audit-logging,human-in-the-loop,mcp,mcp-security,model-context-protocol,policy-engine,prompt-injection,ssrf,tool-security
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Security
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# mcp-guard-lite
|
|
22
|
+
|
|
23
|
+
 [](LICENSE) 
|
|
24
|
+
|
|
25
|
+
Development checkpoint for a zero-runtime-dependency MCP policy enforcement and risk detection SDK.
|
|
26
|
+
|
|
27
|
+
The standalone guard checks exact tool denials, validates the restricted JSON domain, caps serialized request, result and tool-list bytes, and pins tool schemas by trusted application, tenant, server and session. A handler wrapper checks calls before execution and results before returning them to the caller.
|
|
28
|
+
|
|
29
|
+
Canonical JSON accepts null, booleans, strings containing Unicode scalar values, arrays, string-keyed objects and integers in the inclusive range −9007199254740991 through 9007199254740991. Whole-valued floats encode as integers. Keys sort by UTF-16 code units. Strings preserve their original Unicode normalization. The default ceilings are 4,096 entries per collection and 32 levels of nesting. Applications can lower either bound. Use `parse_guard_json` with bounded raw JSON text to reject duplicate keys and unsafe numeric literals. The raw parser accepts integer tokens only. Parsed objects can only represent the keys and numeric values preserved by the host parser.
|
|
30
|
+
|
|
31
|
+
The standalone guard runs locally and can be used at a host application's tool boundary.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
python -m pip install mcp-guard-lite
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quickstart
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from mcp_guard_lite import Config, Context, create_mcp_guard
|
|
43
|
+
ctx = Context("app", "tenant", "mock", "demo")
|
|
44
|
+
guard = create_mcp_guard(Config(allowed_tools=("lookup_*",)))
|
|
45
|
+
guard.inspect_tool_call({"name": "lookup_label", "arguments": {"label": "demo"}}, ctx)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Portable policies
|
|
49
|
+
|
|
50
|
+
Pass the document as `create_mcp_guard(Config(policy=policy))`, or inspect decisions with `compile_policy(policy).evaluate(target)`. The same JSON document is accepted by both runtimes.
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"schemaVersion": 1,
|
|
55
|
+
"id": "workspace",
|
|
56
|
+
"version": "1.0.0",
|
|
57
|
+
"defaultAction": "deny",
|
|
58
|
+
"rules": [
|
|
59
|
+
{
|
|
60
|
+
"id": "lookup",
|
|
61
|
+
"action": "allow",
|
|
62
|
+
"severity": "info",
|
|
63
|
+
"match": { "serverId": "search", "toolName": "lookup" }
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Selectors match exact values for `applicationId`, `tenantId`, `serverId`, `toolName`, and `phase`. Omitted fields match every value. The target phase is `TOOLS_LIST`, `TOOL_CALL`, or `TOOL_RESULT`. A rule applies only when every selector field matches and none of its `exclude` selectors match. Set `enabled` to false to disable an ordinary rule.
|
|
70
|
+
|
|
71
|
+
The engine ranks applicable actions in this order: deny, approval, redact, allow, audit. Within an action, mandatory rules win, then rules with more selector fields, then the first rule ID in ASCII order. Mandatory restrictions apply to deny, approval, and redact, and cannot be disabled or excluded. An audit rule cannot grant access under default-deny. Hard JSON, byte, explicit deny, and schema pinning checks retain precedence over portable allow rules.
|
|
72
|
+
|
|
73
|
+
The guard enforces allow, deny, audit, approval, and redact. An audit decision requires a working audit hook. Approval rules require an asynchronous admission path and a working approval hook. Approval applies only to tool calls and redaction only to tool results.
|
|
74
|
+
|
|
75
|
+
The fingerprint is SHA-256 over the canonical JSON of the validated document. The fingerprint includes the original rule order, including disabled rules.
|
|
76
|
+
|
|
77
|
+
## Audit events
|
|
78
|
+
|
|
79
|
+
Configure `on_audit` and `max_audit_event_bytes` to send bounded audit events to a trusted, synchronous callback. The default byte limit is 4,096. The hook receives one event for each allow or block decision at the inspection boundary. Events carry a generated ID, timestamp, trusted session ID, phase, decision, violation IDs, and inspection latency. Supply opaque session IDs. Tool names, descriptions, arguments, and results are omitted.
|
|
80
|
+
|
|
81
|
+
Under the default `FAIL_CLOSED`, failed delivery raises `AUDIT_FAILED` for an otherwise allowed inspection. Set `fail_mode` to `FAIL_OPEN` to continue after failure of audit delivery or an explicitly nonmandatory custom check. Required approvals and hard restrictions still block. An existing block keeps its original rule ID. Use a synchronous callback that enqueues locally if delivery requires I/O. The callback runs inline and must return promptly. The SDK does not time out synchronous callbacks.
|
|
82
|
+
|
|
83
|
+
## Session circuit breaker
|
|
84
|
+
|
|
85
|
+
| Option | Default | Behavior |
|
|
86
|
+
| --- | ---: | --- |
|
|
87
|
+
| `max_consecutive_identical_calls` | 3 | Blocks the third consecutive call with the same tool name and canonical arguments. Omitted and null arguments are equivalent. |
|
|
88
|
+
| `max_calls_per_minute` | 60 | Limits admitted calls in a rolling minute. |
|
|
89
|
+
| `max_calls_per_session` | 250 | Limits admitted calls over the lifetime of the retained session. |
|
|
90
|
+
| `max_active_sessions` | 128 | Caps retained sessions per guard instance. New sessions are blocked at capacity. |
|
|
91
|
+
| `session_idle_ms` | 900,000 | Expires sessions idle for 15 minutes, using a monotonic clock. |
|
|
92
|
+
| `max_pending_requests` | 128 | Caps in-flight wrapped handlers per guard instance. Standalone callers manage their own in-flight execution. |
|
|
93
|
+
|
|
94
|
+
All session state is keyed by trusted application, tenant, server, and session IDs. A successful admission consumes budget even if audit delivery or the handler later fails. Concurrent wrapped handlers release their pending slot when they finish, throw, or are cancelled. Outstanding wrapped handlers keep the session active while running. Expiration is lazy and runs on later tool registrations or calls. Expiry or reset clears schema pins as well as call history. Align the lifetime of any cached tool registrations with the guard session, and register fresh schemas before dispatching calls for a new or expired session.
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
## Findings and modes
|
|
98
|
+
|
|
99
|
+
`BLOCK` rejects flagged registrations, calls, and results. `SANITIZE` redacts detected credential and PII spans in MCP text blocks and structured string fields. It replaces instruction-bearing or private-key fields, preserves safe fields, and uses a single safe MCP text block if findings remain in unmodifiable fields. Call and registration restrictions stay active. A portable redact rule replaces the result in every mode. `SHADOW_AUDIT` reports hypothetical blocks for registration and result heuristics while keeping mandatory policy and argument restrictions active.
|
|
100
|
+
|
|
101
|
+
| Rule | Meaning |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `PROMPT_INJECTION` | Description, schema text, or result contains an instruction or Unicode marker matched by a heuristic. |
|
|
104
|
+
| `TOOL_SHADOWING` | A listed name collides with a reserved name after Unicode compatibility normalization. |
|
|
105
|
+
| `TOOL_DENIED`, `POLICY_DENIED` | An allowlist, denylist, or portable allow/deny rule rejected the operation. Tool globs support the asterisk wildcard. |
|
|
106
|
+
| `TOOL_SCHEMA_MUTATED` | An existing schema pin no longer matches. |
|
|
107
|
+
| `PATH_DENIED`, `NETWORK_DENIED` | A lexical path or network destination restriction matched. |
|
|
108
|
+
| `COMMAND_RISK`, `SQL_RISK` | An opted-in tool received shell or destructive SQL syntax matched by a heuristic. |
|
|
109
|
+
| `ARGUMENT_SECRET`, `RESULT_SECRET`, `RESULT_PII` | Text matched indicators such as known token prefixes, a private-key marker, an SSN-like value, or a Luhn-valid card-like value. |
|
|
110
|
+
| `POLICY_REDACTED` | A portable result-redaction rule replaced the output. |
|
|
111
|
+
| `INVALID_JSON`, `PAYLOAD_LIMIT` | The value violated the restricted JSON contract or a byte limit. |
|
|
112
|
+
| `AGENT_LOOP_DETECTED`, `CALL_RATE_LIMIT`, `SESSION_CALL_LIMIT`, `SESSION_CAPACITY`, `PENDING_CALL_LIMIT` | The session circuit breaker refused admission. |
|
|
113
|
+
| `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, `POLICY_ACTION_UNAVAILABLE` | A required approval or audit obligation could not be satisfied. |
|
|
114
|
+
| `AUDIT_FAILED` | The audit hook could not accept an otherwise allowed event. |
|
|
115
|
+
|
|
116
|
+
## Human approval
|
|
117
|
+
|
|
118
|
+
Use `ainspect_tool_call` or `wrap_tool_handler` with `on_approval_required`. The callback receives metadata and runs as a cancellable asyncio task. Run the interactive example with `PYTHONPATH=src python examples/approval.py`. Decisions are single-use and tied to the exact canonical call, trusted identity, compiled policy, session lifetime, and deadline. The hook gets an arguments fingerprint instead of raw arguments. Keep application-side approval channels trusted and bind any records you display to that fingerprint. If a timed-out hook ignores cancellation, it can retain a pending slot until it settles. A synchronous callback that blocks the event loop cannot be preempted.
|
|
119
|
+
|
|
120
|
+
## Refund approval demo
|
|
121
|
+
|
|
122
|
+
Run from the source package directory.
|
|
123
|
+
|
|
124
|
+
```sh
|
|
125
|
+
PYTHONPATH=src python examples/refund_approval.py
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The demo uses a mock refund handler and scripted supervisor decisions. It checks that approval records a refund, denial leaves the ledger empty, and a changed amount requires a fresh approval. The supervisor sees a snapshot of the order and amount, which the demo checks against the guard's arguments fingerprint. The demo uses an in-memory ledger and makes no payment or network calls.
|
|
129
|
+
|
|
130
|
+
## Integration
|
|
131
|
+
|
|
132
|
+
Call standalone inspections at the application boundary or wrap an individual handler. The [integration guide](https://github.com/mkkotcherla/mcp-guard-lite/blob/main/docs/integration.md) shows where to inspect registrations, calls, and results in an MCP application. The [refund approval example](https://github.com/mkkotcherla/mcp-guard-lite/blob/main/mcp-guard-lite-python/examples/refund_approval.py) demonstrates approvals and an in-memory refund ledger. Automatic MCP SDK wrappers and the transparent stdio process proxy are deferred. See SECURITY.md for responsibilities and limitations.
|
|
133
|
+
|
|
134
|
+
| Layer | Package |
|
|
135
|
+
| --- | --- |
|
|
136
|
+
| Input | ai-guardrail-lite |
|
|
137
|
+
| Tool execution | mcp-guard-lite |
|
|
138
|
+
| Output | llm-output-guard-lite |
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
## Configurable limits and host checks
|
|
142
|
+
|
|
143
|
+
Configure `max_depth`, `max_collection_size`, `max_tools_per_list`, `max_decode_passes`, and `rate_window_ms` to tighten structural, tool-list, and decoding limits or change the rolling rate window. The existing calls-per-minute setting caps calls in the configured rolling window. A zero decode budget skips optional Base64 inspection and still rejects ambiguous encoded path delimiters. Use `denied_path_patterns` to add case-insensitive literal path component sequences. The built-in protected paths remain active.
|
|
144
|
+
|
|
145
|
+
In sanitize mode, `output_framing` optionally prefixes trusted framing to MCP text blocks. Structured fields remain unframed. The transformed result must still fit the configured output limits.
|
|
146
|
+
|
|
147
|
+
Configure `call_checks`, `filesystem_check`, `dns_check`, `final_destination_check`, and `rule_timeout_ms` to add trusted call admission checks. Checks match tool names using asterisk patterns and receive the canonical call JSON and trusted context. A false result denies admission. Asynchronous checks require the async inspection API or a wrapped handler. The host-specific check slots always fail closed, including in `FAIL_OPEN` mode. General custom checks default to mandatory and may explicitly opt out of mandatory failure handling. An explicit denial always blocks.
|
|
148
|
+
|
|
149
|
+
The SDK runs these checks before admission. The host supplies the verification logic and must enforce its decision at the actual filesystem open or network connection, including redirects. Keep callbacks and their handling of raw call JSON trusted. An uncooperative async callback retains its pending slot until it settles. A synchronous check that blocks the thread can only be assessed against its deadline after it returns. The example with an application-supplied destination check runs via `PYTHONPATH=src python examples/host_check.py`.
|
|
150
|
+
|
|
151
|
+
Maintained by [Kotcherla Murali Krishna](https://github.com/mkkotcherla).
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# mcp-guard-lite
|
|
2
|
+
|
|
3
|
+
 [](LICENSE) 
|
|
4
|
+
|
|
5
|
+
Development checkpoint for a zero-runtime-dependency MCP policy enforcement and risk detection SDK.
|
|
6
|
+
|
|
7
|
+
The standalone guard checks exact tool denials, validates the restricted JSON domain, caps serialized request, result and tool-list bytes, and pins tool schemas by trusted application, tenant, server and session. A handler wrapper checks calls before execution and results before returning them to the caller.
|
|
8
|
+
|
|
9
|
+
Canonical JSON accepts null, booleans, strings containing Unicode scalar values, arrays, string-keyed objects and integers in the inclusive range −9007199254740991 through 9007199254740991. Whole-valued floats encode as integers. Keys sort by UTF-16 code units. Strings preserve their original Unicode normalization. The default ceilings are 4,096 entries per collection and 32 levels of nesting. Applications can lower either bound. Use `parse_guard_json` with bounded raw JSON text to reject duplicate keys and unsafe numeric literals. The raw parser accepts integer tokens only. Parsed objects can only represent the keys and numeric values preserved by the host parser.
|
|
10
|
+
|
|
11
|
+
The standalone guard runs locally and can be used at a host application's tool boundary.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
python -m pip install mcp-guard-lite
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quickstart
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from mcp_guard_lite import Config, Context, create_mcp_guard
|
|
23
|
+
ctx = Context("app", "tenant", "mock", "demo")
|
|
24
|
+
guard = create_mcp_guard(Config(allowed_tools=("lookup_*",)))
|
|
25
|
+
guard.inspect_tool_call({"name": "lookup_label", "arguments": {"label": "demo"}}, ctx)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Portable policies
|
|
29
|
+
|
|
30
|
+
Pass the document as `create_mcp_guard(Config(policy=policy))`, or inspect decisions with `compile_policy(policy).evaluate(target)`. The same JSON document is accepted by both runtimes.
|
|
31
|
+
|
|
32
|
+
```json
|
|
33
|
+
{
|
|
34
|
+
"schemaVersion": 1,
|
|
35
|
+
"id": "workspace",
|
|
36
|
+
"version": "1.0.0",
|
|
37
|
+
"defaultAction": "deny",
|
|
38
|
+
"rules": [
|
|
39
|
+
{
|
|
40
|
+
"id": "lookup",
|
|
41
|
+
"action": "allow",
|
|
42
|
+
"severity": "info",
|
|
43
|
+
"match": { "serverId": "search", "toolName": "lookup" }
|
|
44
|
+
}
|
|
45
|
+
]
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Selectors match exact values for `applicationId`, `tenantId`, `serverId`, `toolName`, and `phase`. Omitted fields match every value. The target phase is `TOOLS_LIST`, `TOOL_CALL`, or `TOOL_RESULT`. A rule applies only when every selector field matches and none of its `exclude` selectors match. Set `enabled` to false to disable an ordinary rule.
|
|
50
|
+
|
|
51
|
+
The engine ranks applicable actions in this order: deny, approval, redact, allow, audit. Within an action, mandatory rules win, then rules with more selector fields, then the first rule ID in ASCII order. Mandatory restrictions apply to deny, approval, and redact, and cannot be disabled or excluded. An audit rule cannot grant access under default-deny. Hard JSON, byte, explicit deny, and schema pinning checks retain precedence over portable allow rules.
|
|
52
|
+
|
|
53
|
+
The guard enforces allow, deny, audit, approval, and redact. An audit decision requires a working audit hook. Approval rules require an asynchronous admission path and a working approval hook. Approval applies only to tool calls and redaction only to tool results.
|
|
54
|
+
|
|
55
|
+
The fingerprint is SHA-256 over the canonical JSON of the validated document. The fingerprint includes the original rule order, including disabled rules.
|
|
56
|
+
|
|
57
|
+
## Audit events
|
|
58
|
+
|
|
59
|
+
Configure `on_audit` and `max_audit_event_bytes` to send bounded audit events to a trusted, synchronous callback. The default byte limit is 4,096. The hook receives one event for each allow or block decision at the inspection boundary. Events carry a generated ID, timestamp, trusted session ID, phase, decision, violation IDs, and inspection latency. Supply opaque session IDs. Tool names, descriptions, arguments, and results are omitted.
|
|
60
|
+
|
|
61
|
+
Under the default `FAIL_CLOSED`, failed delivery raises `AUDIT_FAILED` for an otherwise allowed inspection. Set `fail_mode` to `FAIL_OPEN` to continue after failure of audit delivery or an explicitly nonmandatory custom check. Required approvals and hard restrictions still block. An existing block keeps its original rule ID. Use a synchronous callback that enqueues locally if delivery requires I/O. The callback runs inline and must return promptly. The SDK does not time out synchronous callbacks.
|
|
62
|
+
|
|
63
|
+
## Session circuit breaker
|
|
64
|
+
|
|
65
|
+
| Option | Default | Behavior |
|
|
66
|
+
| --- | ---: | --- |
|
|
67
|
+
| `max_consecutive_identical_calls` | 3 | Blocks the third consecutive call with the same tool name and canonical arguments. Omitted and null arguments are equivalent. |
|
|
68
|
+
| `max_calls_per_minute` | 60 | Limits admitted calls in a rolling minute. |
|
|
69
|
+
| `max_calls_per_session` | 250 | Limits admitted calls over the lifetime of the retained session. |
|
|
70
|
+
| `max_active_sessions` | 128 | Caps retained sessions per guard instance. New sessions are blocked at capacity. |
|
|
71
|
+
| `session_idle_ms` | 900,000 | Expires sessions idle for 15 minutes, using a monotonic clock. |
|
|
72
|
+
| `max_pending_requests` | 128 | Caps in-flight wrapped handlers per guard instance. Standalone callers manage their own in-flight execution. |
|
|
73
|
+
|
|
74
|
+
All session state is keyed by trusted application, tenant, server, and session IDs. A successful admission consumes budget even if audit delivery or the handler later fails. Concurrent wrapped handlers release their pending slot when they finish, throw, or are cancelled. Outstanding wrapped handlers keep the session active while running. Expiration is lazy and runs on later tool registrations or calls. Expiry or reset clears schema pins as well as call history. Align the lifetime of any cached tool registrations with the guard session, and register fresh schemas before dispatching calls for a new or expired session.
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
## Findings and modes
|
|
78
|
+
|
|
79
|
+
`BLOCK` rejects flagged registrations, calls, and results. `SANITIZE` redacts detected credential and PII spans in MCP text blocks and structured string fields. It replaces instruction-bearing or private-key fields, preserves safe fields, and uses a single safe MCP text block if findings remain in unmodifiable fields. Call and registration restrictions stay active. A portable redact rule replaces the result in every mode. `SHADOW_AUDIT` reports hypothetical blocks for registration and result heuristics while keeping mandatory policy and argument restrictions active.
|
|
80
|
+
|
|
81
|
+
| Rule | Meaning |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| `PROMPT_INJECTION` | Description, schema text, or result contains an instruction or Unicode marker matched by a heuristic. |
|
|
84
|
+
| `TOOL_SHADOWING` | A listed name collides with a reserved name after Unicode compatibility normalization. |
|
|
85
|
+
| `TOOL_DENIED`, `POLICY_DENIED` | An allowlist, denylist, or portable allow/deny rule rejected the operation. Tool globs support the asterisk wildcard. |
|
|
86
|
+
| `TOOL_SCHEMA_MUTATED` | An existing schema pin no longer matches. |
|
|
87
|
+
| `PATH_DENIED`, `NETWORK_DENIED` | A lexical path or network destination restriction matched. |
|
|
88
|
+
| `COMMAND_RISK`, `SQL_RISK` | An opted-in tool received shell or destructive SQL syntax matched by a heuristic. |
|
|
89
|
+
| `ARGUMENT_SECRET`, `RESULT_SECRET`, `RESULT_PII` | Text matched indicators such as known token prefixes, a private-key marker, an SSN-like value, or a Luhn-valid card-like value. |
|
|
90
|
+
| `POLICY_REDACTED` | A portable result-redaction rule replaced the output. |
|
|
91
|
+
| `INVALID_JSON`, `PAYLOAD_LIMIT` | The value violated the restricted JSON contract or a byte limit. |
|
|
92
|
+
| `AGENT_LOOP_DETECTED`, `CALL_RATE_LIMIT`, `SESSION_CALL_LIMIT`, `SESSION_CAPACITY`, `PENDING_CALL_LIMIT` | The session circuit breaker refused admission. |
|
|
93
|
+
| `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, `POLICY_ACTION_UNAVAILABLE` | A required approval or audit obligation could not be satisfied. |
|
|
94
|
+
| `AUDIT_FAILED` | The audit hook could not accept an otherwise allowed event. |
|
|
95
|
+
|
|
96
|
+
## Human approval
|
|
97
|
+
|
|
98
|
+
Use `ainspect_tool_call` or `wrap_tool_handler` with `on_approval_required`. The callback receives metadata and runs as a cancellable asyncio task. Run the interactive example with `PYTHONPATH=src python examples/approval.py`. Decisions are single-use and tied to the exact canonical call, trusted identity, compiled policy, session lifetime, and deadline. The hook gets an arguments fingerprint instead of raw arguments. Keep application-side approval channels trusted and bind any records you display to that fingerprint. If a timed-out hook ignores cancellation, it can retain a pending slot until it settles. A synchronous callback that blocks the event loop cannot be preempted.
|
|
99
|
+
|
|
100
|
+
## Refund approval demo
|
|
101
|
+
|
|
102
|
+
Run from the source package directory.
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
PYTHONPATH=src python examples/refund_approval.py
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The demo uses a mock refund handler and scripted supervisor decisions. It checks that approval records a refund, denial leaves the ledger empty, and a changed amount requires a fresh approval. The supervisor sees a snapshot of the order and amount, which the demo checks against the guard's arguments fingerprint. The demo uses an in-memory ledger and makes no payment or network calls.
|
|
109
|
+
|
|
110
|
+
## Integration
|
|
111
|
+
|
|
112
|
+
Call standalone inspections at the application boundary or wrap an individual handler. The [integration guide](https://github.com/mkkotcherla/mcp-guard-lite/blob/main/docs/integration.md) shows where to inspect registrations, calls, and results in an MCP application. The [refund approval example](https://github.com/mkkotcherla/mcp-guard-lite/blob/main/mcp-guard-lite-python/examples/refund_approval.py) demonstrates approvals and an in-memory refund ledger. Automatic MCP SDK wrappers and the transparent stdio process proxy are deferred. See SECURITY.md for responsibilities and limitations.
|
|
113
|
+
|
|
114
|
+
| Layer | Package |
|
|
115
|
+
| --- | --- |
|
|
116
|
+
| Input | ai-guardrail-lite |
|
|
117
|
+
| Tool execution | mcp-guard-lite |
|
|
118
|
+
| Output | llm-output-guard-lite |
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
## Configurable limits and host checks
|
|
122
|
+
|
|
123
|
+
Configure `max_depth`, `max_collection_size`, `max_tools_per_list`, `max_decode_passes`, and `rate_window_ms` to tighten structural, tool-list, and decoding limits or change the rolling rate window. The existing calls-per-minute setting caps calls in the configured rolling window. A zero decode budget skips optional Base64 inspection and still rejects ambiguous encoded path delimiters. Use `denied_path_patterns` to add case-insensitive literal path component sequences. The built-in protected paths remain active.
|
|
124
|
+
|
|
125
|
+
In sanitize mode, `output_framing` optionally prefixes trusted framing to MCP text blocks. Structured fields remain unframed. The transformed result must still fit the configured output limits.
|
|
126
|
+
|
|
127
|
+
Configure `call_checks`, `filesystem_check`, `dns_check`, `final_destination_check`, and `rule_timeout_ms` to add trusted call admission checks. Checks match tool names using asterisk patterns and receive the canonical call JSON and trusted context. A false result denies admission. Asynchronous checks require the async inspection API or a wrapped handler. The host-specific check slots always fail closed, including in `FAIL_OPEN` mode. General custom checks default to mandatory and may explicitly opt out of mandatory failure handling. An explicit denial always blocks.
|
|
128
|
+
|
|
129
|
+
The SDK runs these checks before admission. The host supplies the verification logic and must enforce its decision at the actual filesystem open or network connection, including redirects. Keep callbacks and their handling of raw call JSON trusted. An uncooperative async callback retains its pending slot until it settles. A synchronous check that blocks the thread can only be assessed against its deadline after it returns. The example with an application-supplied destination check runs via `PYTHONPATH=src python examples/host_check.py`.
|
|
130
|
+
|
|
131
|
+
Maintained by [Kotcherla Murali Krishna](https://github.com/mkkotcherla).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Security boundaries
|
|
2
|
+
|
|
3
|
+
This SDK applies deterministic policy and text-based risk detection to parsed MCP data. It uses local computation with zero runtime dependencies, network requests, DNS resolution, filesystem access, or tool-command execution. The host supplies trusted application, tenant, server, and session identifiers. Enforce wire-byte limits while reading frames. Use `parse_guard_json` before inspection when raw JSON text is available so duplicate keys and ambiguous numbers are rejected.
|
|
4
|
+
|
|
5
|
+
Tool denials, portable policy decisions, limits, schema pins, and the exact-argument approval check are deterministic. The prompt, credential, PII, command, SQL, and reserved-name checks cover selected patterns and can miss obfuscated or domain-specific content. Legitimate security documentation, commands, and identifier strings can trigger false positives. Where result structure permits, credential and PII spans are redacted and safe fields are preserved. A finding in unmodifiable fields triggers whole-result replacement. Encoded images and attachments are outside the text heuristics.
|
|
6
|
+
|
|
7
|
+
Path checks are lexical. Relative paths still require a trusted working directory and OS-level confinement. Enforce authorization when opening files and account for symlinks, junctions, mount changes, and races. Network checks cover selected literal destinations and URLs. The optional filesystem, DNS, and destination hooks execute host-supplied admission checks. Resolve and check final destinations in the host, including redirects, DNS rebinding, proxies, and alternative resolver interpretations. Use parameterized SQL, constrained command invocation, least-privilege credentials, and OS or network isolation where needed.
|
|
8
|
+
|
|
9
|
+
Audit callbacks receive opaque trusted IDs and rule codes. Approval hooks receive identity, tool name, and an arguments hash, which can still be sensitive for low-entropy arguments. Keep both channels local or apply host access controls. Async approval hooks must cooperate with cancellation. Synchronous callbacks must return promptly. Always use the inspected result returned by the guard. Treat expired or reset sessions as fresh and refresh cached tool registrations before dispatch.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Run with PYTHONPATH=src python benchmarks/inspect_guard.py."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
from time import perf_counter_ns
|
|
6
|
+
|
|
7
|
+
from mcp_guard_lite import Config, Context, create_mcp_guard
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main():
|
|
11
|
+
ctx = Context("bench", "bench", "mock", "bench")
|
|
12
|
+
guard = create_mcp_guard(Config(max_calls_per_minute=5000, max_calls_per_session=5000))
|
|
13
|
+
tools = [{"name": f"lookup_{i}", "inputSchema": {"type": "object"}} for i in range(20)]
|
|
14
|
+
result = lambda size: {"content": [{"type": "text", "text": "a" * size}]}
|
|
15
|
+
fast, large, repeated = (result(size) for size in (4096, 32768, 102400))
|
|
16
|
+
near_miss = {"content": [{"type": "text", "text": "eyJx " * 20480}]}
|
|
17
|
+
workloads = {
|
|
18
|
+
"list20": lambda _: guard.inspect_tools_list(tools, ctx),
|
|
19
|
+
"nestedCall": lambda i: guard.inspect_tool_call(
|
|
20
|
+
{"name": "lookup", "arguments": {"query": {"parts": ["x", i]}}}, ctx,
|
|
21
|
+
),
|
|
22
|
+
"result4KiB": lambda _: guard.inspect_tool_result("lookup", fast, ctx),
|
|
23
|
+
"result32KiB": lambda _: guard.inspect_tool_result("lookup", large, ctx),
|
|
24
|
+
"result100KiB": lambda _: guard.inspect_tool_result("lookup", repeated, ctx),
|
|
25
|
+
"nearMiss100KiB": lambda _: guard.inspect_tool_result("lookup", near_miss, ctx),
|
|
26
|
+
}
|
|
27
|
+
for name, call in workloads.items():
|
|
28
|
+
for i in range(100):
|
|
29
|
+
call(i)
|
|
30
|
+
samples = []
|
|
31
|
+
for i in range(100, 1100):
|
|
32
|
+
start = perf_counter_ns()
|
|
33
|
+
call(i)
|
|
34
|
+
samples.append((perf_counter_ns() - start) / 1e6)
|
|
35
|
+
samples.sort()
|
|
36
|
+
metrics = {f"p{p}": round(samples[math.ceil(p * len(samples) / 100) - 1], 3) for p in (50, 95, 99)}
|
|
37
|
+
print(json.dumps({"name": name, **metrics}))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
if __name__ == "__main__":
|
|
41
|
+
main()
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Run with PYTHONPATH=src python examples/approval.py from the package directory."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from mcp_guard_lite import ApprovalRequest, Config, Context, McpGuardBlockedError, create_mcp_guard
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def approve(request: ApprovalRequest) -> bool:
|
|
10
|
+
answer = await asyncio.to_thread(input, f"Approve {request['toolName']}? [y/N] ")
|
|
11
|
+
return answer.strip().lower() == "y"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def mock_export(arguments, context):
|
|
15
|
+
return {"content": [{"type": "text", "text": "Synthetic export complete"}]}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def main():
|
|
19
|
+
guard = create_mcp_guard(Config(
|
|
20
|
+
policy={
|
|
21
|
+
"schemaVersion": 1, "id": "example", "version": "1", "defaultAction": "allow",
|
|
22
|
+
"rules": [{"id": "review", "action": "approval", "severity": "high", "mandatory": True,
|
|
23
|
+
"match": {"toolName": "mock_export", "phase": "TOOL_CALL"}}],
|
|
24
|
+
},
|
|
25
|
+
on_approval_required=approve,
|
|
26
|
+
on_audit=lambda event: print(json.dumps(event)),
|
|
27
|
+
))
|
|
28
|
+
wrapped = guard.wrap_tool_handler("mock_export", mock_export)
|
|
29
|
+
try:
|
|
30
|
+
print(await wrapped({"category": "demo"}, Context("demo", "local", "mock", "demo-session")))
|
|
31
|
+
except McpGuardBlockedError as error:
|
|
32
|
+
print(error.rule_id)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
if __name__ == "__main__":
|
|
36
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Run with PYTHONPATH=src python examples/host_check.py."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from mcp_guard_lite import CallCheck, CallCheckRequest, Config, Context, create_mcp_guard, parse_guard_json
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
async def destination_check(request: CallCheckRequest) -> bool:
|
|
9
|
+
call = parse_guard_json(request["callJson"])
|
|
10
|
+
if not isinstance(call, dict):
|
|
11
|
+
return False
|
|
12
|
+
arguments = call.get("arguments")
|
|
13
|
+
return isinstance(arguments, dict) and arguments.get("destination") == "https://example.com/demo"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def mock_fetch(arguments, ctx):
|
|
17
|
+
return {"content": [{"type": "text", "text": "Mock result"}]}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def main():
|
|
21
|
+
guard = create_mcp_guard(Config(final_destination_check=CallCheck(
|
|
22
|
+
"demo-destination", destination_check, tools=("mock_fetch",), asynchronous=True,
|
|
23
|
+
)))
|
|
24
|
+
ctx = Context("demo", "local", "mock", "demo-session")
|
|
25
|
+
print(await guard.wrap_tool_handler("mock_fetch", mock_fetch)({"destination": "https://example.com/demo"}, ctx))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
if __name__ == "__main__":
|
|
29
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Run a synthetic refund approval workflow with an in-memory ledger."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from mcp_guard_lite import Config, Context, McpGuardBlockedError, create_mcp_guard, fingerprint
|
|
6
|
+
|
|
7
|
+
CONTEXT = Context("shop", "demo", "mock-refunds", "demo")
|
|
8
|
+
POLICY = {
|
|
9
|
+
"schemaVersion": 1, "id": "refund-policy", "version": "1", "defaultAction": "allow",
|
|
10
|
+
"rules": [{
|
|
11
|
+
"id": "supervisor-approval", "action": "approval", "severity": "high", "mandatory": True,
|
|
12
|
+
"match": {"toolName": "refund_order", "phase": "TOOL_CALL"},
|
|
13
|
+
}],
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def create_demo(votes):
|
|
18
|
+
ledger = []
|
|
19
|
+
reviews = []
|
|
20
|
+
scripted_reviews = iter(votes)
|
|
21
|
+
|
|
22
|
+
async def approve(request):
|
|
23
|
+
displayed, allow, on_review = next(scripted_reviews)
|
|
24
|
+
assert request["argumentsFingerprint"] == fingerprint(displayed)
|
|
25
|
+
reviews.append(displayed.copy())
|
|
26
|
+
if on_review is not None:
|
|
27
|
+
on_review()
|
|
28
|
+
return allow
|
|
29
|
+
|
|
30
|
+
async def refund_handler(arguments, context):
|
|
31
|
+
ledger.append(arguments.copy())
|
|
32
|
+
return {"status": "recorded_in_mock_ledger"}
|
|
33
|
+
|
|
34
|
+
guard = create_mcp_guard(Config(policy=POLICY, on_approval_required=approve))
|
|
35
|
+
return guard.wrap_tool_handler("refund_order", refund_handler), ledger, reviews
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def expect_denied(refund, arguments):
|
|
39
|
+
try:
|
|
40
|
+
await refund(arguments, CONTEXT)
|
|
41
|
+
except McpGuardBlockedError as error:
|
|
42
|
+
assert error.rule_id == "APPROVAL_DENIED"
|
|
43
|
+
else:
|
|
44
|
+
raise AssertionError("Expected the guard to deny the refund")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def main():
|
|
48
|
+
order = {"orderId": "DEMO-1042", "amountCents": 2500}
|
|
49
|
+
refund, ledger, _ = create_demo([(order.copy(), True, None)])
|
|
50
|
+
await refund(order, CONTEXT)
|
|
51
|
+
assert ledger == [order]
|
|
52
|
+
print("Approved: $25.00 recorded in the mock ledger.")
|
|
53
|
+
|
|
54
|
+
refund, ledger, _ = create_demo([(order.copy(), False, None)])
|
|
55
|
+
await expect_denied(refund, order)
|
|
56
|
+
assert ledger == []
|
|
57
|
+
print("Denied: no refund was recorded.")
|
|
58
|
+
|
|
59
|
+
amended = order.copy()
|
|
60
|
+
revised = {**order, "amountCents": 3500}
|
|
61
|
+
|
|
62
|
+
def change_amount():
|
|
63
|
+
amended["amountCents"] = 3500
|
|
64
|
+
|
|
65
|
+
refund, ledger, reviews = create_demo([
|
|
66
|
+
(order.copy(), True, change_amount),
|
|
67
|
+
(revised.copy(), True, None),
|
|
68
|
+
])
|
|
69
|
+
await expect_denied(refund, amended)
|
|
70
|
+
assert ledger == []
|
|
71
|
+
print("Changed to $35.00 during review: the $25.00 approval was rejected.")
|
|
72
|
+
await refund(amended, CONTEXT)
|
|
73
|
+
assert [review["amountCents"] for review in reviews] == [2500, 3500]
|
|
74
|
+
assert ledger == [revised]
|
|
75
|
+
print("Fresh approval: $35.00 recorded in the mock ledger.")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == "__main__":
|
|
79
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mcp-guard-lite"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Zero-dependency Model Context Protocol (MCP) security SDK for AI agents. Enforce tool policies, require approval, and redact sensitive results."
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
dependencies = []
|
|
11
|
+
license = "MIT"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
authors = [{name = "Kotcherla Murali Krishna"}]
|
|
14
|
+
keywords = ["mcp", "model-context-protocol", "mcp-security", "ai-agents", "tool-security", "policy-engine", "prompt-injection", "human-in-the-loop", "audit-logging", "ssrf"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
"Topic :: Security",
|
|
20
|
+
"Topic :: Software Development :: Libraries",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/mkkotcherla/mcp-guard-lite"
|
|
25
|
+
Documentation = "https://github.com/mkkotcherla/mcp-guard-lite/blob/main/docs/integration.md"
|
|
26
|
+
Repository = "https://github.com/mkkotcherla/mcp-guard-lite"
|
|
27
|
+
Issues = "https://github.com/mkkotcherla/mcp-guard-lite/issues"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.wheel]
|
|
30
|
+
packages = ["src/mcp_guard_lite"]
|
|
31
|
+
|
|
32
|
+
[tool.mypy]
|
|
33
|
+
strict = true
|
|
34
|
+
files = ["src"]
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.sdist]
|
|
37
|
+
exclude = ["/tests"]
|