pyveil
Zero-dependency local PII and secret redaction for MCP servers, coding agents, and Python LLM apps.
MCP Proxy · Agent Hooks & Skill · Benchmarks · Korean PII · Quickstart · Manual · Security
Keep emails, phone numbers, Korean PII (--rulepack kr), and supported
credentials out of model prompts, tool arguments, tool results, MCP resources,
memory, logs, and traces. Zero core runtime dependencies, 100% air-gap local,
Python 3.8–3.14 — no model download, API key, or Hub token required.
- Drop-in interception for MCP servers and coding agents: Wrap any stdio or
Streamable HTTP/SSE MCP server with
pyveil proxy, or attachpyveil hook(PreToolUse/PostToolUse) and the portableSKILL.mdto Claude Code, Codex, and GitHub Copilot CLI. - Explicit in-process Python SDK: In Python apps, call
Veildirectly before each boundary you want to protect; installingpyveildoes not monkey-patch or silently intercept Python SDK calls.
Synthetic local CLI demo (PreToolUse .env deny, fail-closed MCP -32001 block, --rulepack kr masking, and raw-free JSONL audit; no live LLM API call) — reproduced by scripts/render_demo_gif.py.
One-Command MCP Proxy
Put pyveil proxy between an MCP client and any stdio or Streamable HTTP/SSE
MCP server. It checks tools/call arguments on tool.call.arguments and
redacts tool outputs (tool.call.result), MCP resources
(mcp.resource.content), and prompts locally before they enter model context.
Stdio drop-in wrapper (auto-detects Content-Length and NDJSON framing):
export PYVEIL_SECRET="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
python3 -m pyveil proxy -- npx -y @modelcontextprotocol/server-filesystem .
Streamable HTTP / SSE local reverse proxy (with Korean PII and raw-free audit logging):
python3 -m pyveil proxy \
--transport http \
--listen 127.0.0.1:8787 \
--upstream http://127.0.0.1:9000/mcp \
--rulepack kr \
--audit-log pyveil-audit.jsonl
- Fail-closed credential blocking (
-32001): Under the default--on-block error,tools/callarguments containing credentials (API_KEY,AUTH_HEADER,JWT,PRIVATE_KEY,KV_SECRET,URL_QUERY_SECRET) are rejected before upstream dispatch with a raw-free JSON-RPC-32001error. Pass--on-block redactto replace blocked credentials with placeholders instead. - Explicit secret required:
PYVEIL_SECRET(or--secret/--secret-env) is required;pyveil proxyfails closed rather than using a hardcoded key. - Streaming and stderr: HTTP mode incrementally redacts
text/event-streamSSEdata:JSON frames; stdio mode supports--redact-stderrunderlog.record.
See MCP Proxy & Python helper guide for Claude Desktop, Claude Code, and Codex configuration snippets.
Agent Hooks and Skill
Guard PreToolUse and PostToolUse tool boundaries in Claude Code,
Codex, and GitHub Copilot CLI locally with zero external dependencies:
export PYVEIL_SECRET="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
python3 -m pyveil hook print-config --target claude-code
python3 -m pyveil hook print-config --target copilot-cli
python3 -m pyveil hook print-config --target codex
Add --rulepack kr --audit-log pyveil-audit.jsonl to bake Korean PII detection
and metadata-only audit logging into the printed config.
pre-tool-use(default--mode block) denies tool calls containing default-blocked credentials or heuristic sensitive file-path references (.env,.env.*excluding safe templates,*.pem,*.key,id_rsa,id_ed25519,.aws/credentials,.netrc), or rewrites arguments under--mode redact.post-tool-useis always non-blocking: it redactstool.call.resultoutputs and emits a raw-freeadditionalContextnotice.- Ready-to-use templates & portable skill:
- Claude Code: hooks/claude-code/settings.json
- Codex: hooks/codex/config.toml
- GitHub Copilot CLI: hooks/copilot-cli/hooks.json
- Portable Agent Skill: skills/pyveil/SKILL.md
- Full Hook Guide: docs/integrations/agent-hooks.md
The .env / key-file check is a string-level filename heuristic complementing
content redaction — it is not an OS sandbox or filesystem access control
layer.
Measured Benchmarks
Measured locally in isolated uv virtual environments on Apple M6 (12
logical cores, arm64, Darwin 27.0.0), Python 3.12.15, at
2026-11-30T05:52:35Z (50 warm passes / 1,950 documents evaluated on
evaluation/corpus.json:
39 cases — 33 positive, 6 negative, 36 expected findings; shared PII
subset: 20 cases — 14 positive, 6 negative, 15 expected findings for
EMAIL, PHONE, CREDIT_CARD). Raw data:
evaluation/benchmark-results.json.
| Metric | pyveil 0.4.0 |
presidio-analyzer 2.2.366 (spacy 3.8.18, en_core_web_sm 3.8.0) |
guardrails-ai 0.11.0 |
|---|---|---|---|
| Runtime dependencies (installed packages) | 0 (1 package) |
51 (52 packages) |
112 (113 packages, base only) |
Installed footprint (excl. __pycache__) |
262.19 KB (0.256 MB) |
113,618.88 KB (110.956 MB) |
313,782.63 KB (306.428 MB, base only) |
| Cold start: import / import + init (median) | 13.018 ms / 13.028 ms (5 runs) |
428.528 ms / 591.644 ms (3 runs) |
923.011 ms (3 runs) / unavailable offline |
| Warm latency per doc: median / p95 | 0.0125 ms / 0.0202 ms (26.635 ms total) |
1.3898 ms / 2.2113 ms (2,844.148 ms total, scoped shared PII); 1.5472 ms / 2.4166 ms (3,161.139 ms total, default all entities) |
Not measured offline |
Warm throughput (1,950 docs) |
73,212.6 docs/sec |
685.6 docs/sec (scoped); 616.9 docs/sec (default) |
Not measured offline |
Shared PII subset (20 cases, 15 expected) P / R |
1.000 / 1.000 (F1 1.000) |
0.9231 / 0.8000 (F1 0.8571) |
Not measured offline |
Full corpus (39 cases, 36 expected) P / R |
1.000 / 1.000 (F1 1.000) |
0.8750 / 0.3889 (F1 0.5385) |
Not measured offline |
| Air-gap / offline PII status | Runnable offline; no model download or Hub token | Runnable offline once spaCy model wheel is pre-installed (en_core_web_sm ~12.2 MiB here vs default en_core_web_lg ~382 MiB) |
airgap_pii_unavailable: 0 bundled PII validators; DetectPII/GuardrailsPII require Guardrails Hub + API token or separate packages + model downloads |
Reproduce locally:
python3 evaluation/benchmark_compare.py --python 3.12 --passes 50 --output evaluation/benchmark-results.json
Scope and fair NER credit: evaluation/corpus.json is a synthetic
supported-shape regression corpus, not a representative real-world NLP
benchmark, and latency numbers are machine-dependent local diagnostics, not
SLAs. Presidio provides spaCy/transformer NER discovery of unknown person
names, locations, organizations, and dates that pyveil deliberately does not
attempt and that are absent from evaluation/corpus.json. Conversely, Presidio
does not ship built-in secret recognizers (API keys, JWTs, PEM private keys,
auth headers, URL/KV secrets), which accounts for its 0.3889 full-corpus
recall. See the
measured comparison guide
and benchmark harness.
Structured Raw-Free Audit Log
Pass --audit-log <file|stderr> to pyveil proxy, pyveil hook,
pyveil redact, or pyveil scan (or use pyveil.AuditLogger in Python) to
record one metadata-only JSONL event per boundary check. Audit logs omit raw
sensitive values, payload bodies, secrets, raw file paths, and placeholder
tokens:
{"schema_version":1,"timestamp":"2026-11-30T05:52:35.000Z","event":"hook.pre_tool_use","direction":"local","channel":"tool.call.arguments","action":"blocked","finding_count":1,"entity_counts":{"SENSITIVE_PATH":1},"rule_ids":["dotenv_file"],"latency_ms":0.214,"scope":"agent-hook","tool_name":"Read","reason":"pyveil blocked tool call: sensitive file path reference (dotenv_file)"}
{"schema_version":1,"timestamp":"2026-11-30T05:52:35.120Z","event":"proxy.response","direction":"upstream_to_client","channel":"tool.call.result","action":"redacted","finding_count":2,"entity_counts":{"EMAIL":1,"KR_RRN":1},"rule_ids":["email_address","kr_rrn_hyphenated"],"latency_ms":0.041,"scope":"mcp-proxy","method":"tools/call","request_id":7}
Optional Korean PII Rulepack
Enable opt-in clean-room Korean PII detection via --rulepack kr on any CLI
command (proxy, hook, redact, scan) or rulepacks=("kr",) in Python:
KR_RRN: Citizen (1–4) and foreigner (5–8) resident registration numbers with century-aware calendar date and mod-11 checksum validation (korean_pii_rules(strict_checksum=False)available for post-October 2020 randomized RRNs;LOWmasks all 13 digits******-*******with zero DOB/gender leakage).KR_BRN: Business registration numbers (사업자등록번호) validated with the National Tax Service (NTS) checksum.KR_BANK_ACCOUNT: Context-anchored 10–14 digit Korean bank accounts near Korean bank names or account keywords.- Korean phone variants: Built-in hyphenated Korean numbers plus
context-anchored contiguous
01[016789]mobile numbers underPHONE.
export PYVEIL_SECRET="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
printf '주민번호 850315-1000025 / 사업자 123-45-67891 / 신한은행 110-123-456789\n' \
| python3 -m pyveil redact - --rulepack kr
import secrets
from pyveil import Veil, korean_pii_rules
veil = Veil.high(secret=secrets.token_bytes(32), scope="kr/session", rulepacks=("kr",))
# Optional relaxed checksum mode for post-October 2020 randomized RRNs
veil_relaxed = Veil.high(
secret=secrets.token_bytes(32),
scope="kr/session",
rules=korean_pii_rules(strict_checksum=False),
)
Verified on the 45-case clean-room synthetic corpus
(evaluation/corpus_kr.json:
31 positive, 14 negative, 41 expected findings, 1.000 precision /
1.000 recall). See
Korean corpus evaluation
and detector provenance.
Quickstart
Requires Python 3.8+. In your Python environment:
python -m pip install pyveil
Run this complete example. It makes no provider request:
import secrets
from pyveil import Channel, Veil
veil = Veil.high(secret=secrets.token_bytes(32), scope="support/session-42")
messages = [
{"role": "user", "content": "Email alice@example.com about ticket 42."},
]
safe = veil.redact_data(messages, channel=Channel.PROMPT_INPUT)
print(safe.data[0]["content"])
Output shape (the 12-hex suffix depends on your key and scope):
Email [EMAIL:...] about ticket 42.
Pass safe.data, not messages, to your SDK. The original input is unchanged;
message roles and ticket 42 are preserved. For plain strings use
veil.redact_text(text).text.
This example creates a random key once per run. Reuse the same Veil within a
session; load a private, stable secret from your environment or secret manager
when placeholders must survive restarts. Never reuse a documentation secret
with real data. Key and scope guidance
Start With Your Integration
| Your stack | Start here | What runs locally |
|---|---|---|
| MCP servers (stdio / HTTP / SSE) | One-command MCP proxy | python3 -m pyveil proxy -- <mcp-server-cmd> or --transport http |
| Claude Code / Codex / Copilot CLI | Coding-agent hooks & skill | python3 -m pyveil hook print-config --target claude-code|copilot-cli|codex |
| OpenAI Agents SDK | Runner wrapper and setup | Redacts initial input before Runner.run; keyless checkout example |
| LiteLLM SDK / Proxy | SDK wrapper and Proxy hook | Redacts completion messages before dispatch; keyless checkout example |
| OpenAI Responses API | Installable helper | python -m pyveil.integrations.openai --dry-run |
| Anthropic / Claude | Installable helper | python -m pyveil.integrations.anthropic --dry-run |
| Azure OpenAI | Env / YAML setup | python -m pyveil.integrations.azure_openai --dry-run |
| Ollama | Local model guide | python -m pyveil.integrations.ollama --dry-run |
| Logs, memory, FastAPI, custom MCP | Cookbook | Explicit wrappers at your application's boundaries |
Provider dry-runs require PYVEIL_SECRET; the linked guides cover configuration
and optional SDK dependencies for live calls. Dry-runs are not model responses.
OpenAI Agents input guardrails validate or block; they do not replace the input,
so the example redacts before dispatch. The LiteLLM Proxy hook covers
list-valued messages, not every endpoint or payload field.
Examples vs installed modules: pyveil.integrations.* ships in the wheel.
examples/*.py does not. To run the OpenAI Agents and LiteLLM recipes without
either SDK or a provider key, start from a checkout:
git clone https://github.com/hyeonsangjeon/pyveil.git
cd pyveil
python -m pip install .
python examples/openai_agents_guardrail.py
python examples/litellm_proxy_filter.py
Use a virtual environment for installation. See the comparison guide for macOS/Linux and Windows setup, expected output, and bypass risks.
What Gets Redacted?
HIGH replaces supported findings with [TYPE:12hex] HMAC placeholders. The same
value, type, key, and scope produce the same placeholder, so repeated references
remain linkable within your chosen scope.
| Type | Supported shapes |
|---|---|
EMAIL |
Email addresses |
PHONE |
Korean, separated international, and compact E.164 shapes |
CREDIT_CARD |
Candidate card numbers that pass Luhn validation |
JWT |
Compact JSON Web Tokens |
AUTH_HEADER |
Bearer, Basic, Token, and ApiKey authorization headers |
PRIVATE_KEY |
PEM private-key blocks |
API_KEY |
Supported OpenAI, GitHub, Slack, Google, and AWS-style patterns |
URL_QUERY_SECRET |
Supported secret-bearing URL query parameters |
KV_SECRET |
Sensitive key-value pairs, including passwords and tokens |
KR_RRN, KR_BRN, KR_BANK_ACCOUNT (--rulepack kr) |
Opt-in Korean resident/foreigner RRNs, NTS-checksummed BRNs, context-anchored bank accounts, and contiguous Korean mobile numbers (PHONE) |
| Custom rules | Exact known values and trusted application regexes |
Unknown names, addresses, images, and documents are not automatically
detected. Use CustomRule.exact(...) for known values, or add a separate semantic
detection layer. The detection board
shows inputs, HIGH/LOW outputs, validation rules, and limits.
Use HIGH for model-facing data. LOW is a human-facing preview, such as
al***@e******.com; it deliberately retains identifying shape. Credentials stay
aggressively hidden in both levels, and LOW KR_RRN masks all 13 digits
(******-*******) with zero DOB/gender leakage. pyveil is not a compliance
guarantee, prompt-injection firewall, DLP suite, or reversible vault.
Protect More Than Prompts
| Task | Channel | Example |
|---|---|---|
| Prepare model input / output | prompt.input, prompt.output |
Provider-neutral boundary |
| Block credentials in tool arguments | tool.call.arguments |
Blocking recipe |
| Redact tool results / MCP resources | tool.call.result, mcp.resource.content |
MCP wrapper |
| Redact before embedding or persistence | memory.write |
Memory example |
| Redact before telemetry export | log.record, trace.span.attributes |
Logging / tracing |
The default policy raises BlockedSensitiveData for credential-like findings in
tool.call.arguments. On failure, do not dispatch the original payload.
Findings omit raw sensitive values by default; your application's original
objects still exist in memory. Policy and failure handling
Process A File
From an empty working directory after installation:
python -m pyveil init --example
python -m pyveil run
This creates synthetic input, pyveil.json, and a random private .pyveil.key,
then writes real redacted output and a receipt under .pyveil-runs/<run-id>/.
No model is called. Run twice with unchanged input, config, key, and version for
identical output bytes in separate directories.
For your own file, use the following instead of init --example:
python -m pyveil init --input /path/to/request.json --input-format json
Keep keys and outputs out of Git; redacted output is not automatically safe to publish. Configuration, Windows commands, error codes, and migration
Verify Before You Integrate
One installed command exercises six synthetic agent boundaries without keys:
python -m pyveil replay --format markdown
The current regression expectation is 6/6 passing cases, 10 findings, and 0 surviving labeled synthetic markers. It checks benign fields, structure, and a second redaction pass. It is not a real-world PII recall benchmark. Replay methodology and limits
CI tests Python 3.8 through 3.14, installs built wheels in clean environments, executes the quickstart above, and verifies file runs. Separate offline tests inspect official OpenAI and Anthropic SDK request bodies through local mock transports; they do not claim live paid API validation.
Test runs · 39-case core corpus · 45-case Korean corpus · Protection-surface contract
Documentation And Support
- Manual, cookbook, and troubleshooting
- MCP proxy guide, coding-agent hooks guide, and portable agent skill
- Threat model, known limitations, detector provenance, and security policy
- pyveil vs Presidio / Guardrails AI / DLP
- Ask an integration question or report a bug. Share synthetic inputs, not real PII or credentials.
- AGENTS.md and llms.txt for coding agents
Development
uv run --extra dev ruff check .
uv run --extra dev mypy pyveil tests
uv run --extra test pytest
uv run --extra test python evaluation/evaluate.py --check
uv run --extra test python evaluation/evaluate.py --corpus evaluation/corpus_kr.json --rulepack kr --check
Metadata
Release files for pyveil 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyveil-0.4.0.tar.gz | 1.3 MB | With provenance | Details for pyveil-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyveil-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for pyveil-0.4.0-py3-none-any.whl |
Total release size: 1.4 MB
Release files / pyveil-0.4.0.tar.gz
| Download URL | pyveil-0.4.0.tar.gz |
|---|---|
| Size | 1.3 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
aa048c22520405106f437061d516b1a2bfb3b3413137f86c7dc5d990a9b54dee
|
|
BLAKE2b-256 checksum How to use checksums |
c423ea27326089032161593b8572be7f3ec6ca46c9e272fbb178703b4fcb1017
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / pyveil-0.4.0-py3-none-any.whl
| Download URL | pyveil-0.4.0-py3-none-any.whl |
|---|---|
| Size | 87.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
8b43d1738d951a12dad66297b38161dc3fde4908e07149a3b68421fcde9f6eb1
|
|
BLAKE2b-256 checksum How to use checksums |
2d0f3f751cc8b4c9e92a6fc7a13736b1ba0c18934316d47f6135255f2b575c16
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for pyveil 0.4.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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pyveil-0.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA 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.