Skip to main content

mcp-guard-lite

Version 0.1.0 MIT license Supported runtime

Development checkpoint for a zero-runtime-dependency MCP policy enforcement and risk detection SDK.

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.

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.

The standalone guard runs locally and can be used at a host application's tool boundary.

Installation

python -m pip install mcp-guard-lite

Quickstart

from mcp_guard_lite import Config, Context, create_mcp_guard
ctx = Context("app", "tenant", "mock", "demo")
guard = create_mcp_guard(Config(allowed_tools=("lookup_*",)))
guard.inspect_tool_call({"name": "lookup_label", "arguments": {"label": "demo"}}, ctx)

Portable policies

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.

{
  "schemaVersion": 1,
  "id": "workspace",
  "version": "1.0.0",
  "defaultAction": "deny",
  "rules": [
    {
      "id": "lookup",
      "action": "allow",
      "severity": "info",
      "match": { "serverId": "search", "toolName": "lookup" }
    }
  ]
}

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.

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.

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.

The fingerprint is SHA-256 over the canonical JSON of the validated document. The fingerprint includes the original rule order, including disabled rules.

Audit events

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.

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.

Session circuit breaker

Option Default Behavior
max_consecutive_identical_calls 3 Blocks the third consecutive call with the same tool name and canonical arguments. Omitted and null arguments are equivalent.
max_calls_per_minute 60 Limits admitted calls in a rolling minute.
max_calls_per_session 250 Limits admitted calls over the lifetime of the retained session.
max_active_sessions 128 Caps retained sessions per guard instance. New sessions are blocked at capacity.
session_idle_ms 900,000 Expires sessions idle for 15 minutes, using a monotonic clock.
max_pending_requests 128 Caps in-flight wrapped handlers per guard instance. Standalone callers manage their own in-flight execution.

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.

Findings and modes

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.

Rule Meaning
PROMPT_INJECTION Description, schema text, or result contains an instruction or Unicode marker matched by a heuristic.
TOOL_SHADOWING A listed name collides with a reserved name after Unicode compatibility normalization.
TOOL_DENIED, POLICY_DENIED An allowlist, denylist, or portable allow/deny rule rejected the operation. Tool globs support the asterisk wildcard.
TOOL_SCHEMA_MUTATED An existing schema pin no longer matches.
PATH_DENIED, NETWORK_DENIED A lexical path or network destination restriction matched.
COMMAND_RISK, SQL_RISK An opted-in tool received shell or destructive SQL syntax matched by a heuristic.
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.
POLICY_REDACTED A portable result-redaction rule replaced the output.
INVALID_JSON, PAYLOAD_LIMIT The value violated the restricted JSON contract or a byte limit.
AGENT_LOOP_DETECTED, CALL_RATE_LIMIT, SESSION_CALL_LIMIT, SESSION_CAPACITY, PENDING_CALL_LIMIT The session circuit breaker refused admission.
APPROVAL_DENIED, APPROVAL_TIMEOUT, POLICY_ACTION_UNAVAILABLE A required approval or audit obligation could not be satisfied.
AUDIT_FAILED The audit hook could not accept an otherwise allowed event.

Human approval

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.

Refund approval demo

Run from the source package directory.

PYTHONPATH=src python examples/refund_approval.py

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.

Integration

Call standalone inspections at the application boundary or wrap an individual handler. The integration guide shows where to inspect registrations, calls, and results in an MCP application. The refund approval example 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.

Layer Package
Input ai-guardrail-lite
Tool execution mcp-guard-lite
Output llm-output-guard-lite

Configurable limits and host checks

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.

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.

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.

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.

Maintained by Kotcherla Murali Krishna.

Metadata

Release files for mcp-guard-lite 0.1.0

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

Source distribution (sdist)

Source distribution for mcp-guard-lite 0.1.0
File Size Uploaded Provenance Actions
mcp_guard_lite-0.1.0.tar.gz 23.7 kB Without provenance Details for mcp_guard_lite-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mcp-guard-lite 0.1.0
File Interpreter ABI Platform Actions
mcp_guard_lite-0.1.0-py3-none-any.whl Python 3 none any Details for mcp_guard_lite-0.1.0-py3-none-any.whl

Total release size: 46.7 kB

Release files / mcp_guard_lite-0.1.0.tar.gz

Download URL mcp_guard_lite-0.1.0.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
3b2138508edeb513904706ca41f921c79e9b1d4264e9acfde43ec40952cc763f
BLAKE2b-256 checksum
How to use checksums
6abab651fa3fab26c24b79aa30ab252cc1ebf768508e2f695d09e947371d390a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Release files / mcp_guard_lite-0.1.0-py3-none-any.whl

Download URL mcp_guard_lite-0.1.0-py3-none-any.whl
Size 23.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c38f2f589a67eb486d78e8d391748300358ac67d582ce308357aa1420da47b49
BLAKE2b-256 checksum
How to use checksums
82e380543fe8de61ce20e027e8a6f9da71cf346fed88fbc1c52fe00d77fa4bd7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Security for mcp-guard-lite 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

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

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page