Skip to main content
Glama
GigantesHJI

securedact-mcp

SecuRedact MCP

PyPI Python License: Apache-2.0

SecuRedact — это локальный уровень конфиденциальности и безопасности для ИИ-агентов и ИИ-рабочих процессов. Он обнаруживает и защищает чувствительные данные — персональные данные / PII, информацию, подпадающую под GDPR, учетные данные, ключи API, токены, секреты и чувствительные файлы — до того, как эти данные попадут в модели, инструменты, файлы или внешние назначения.

SecuRedact MCP — это Apache-2.0 сервер MCP с открытым исходным кодом и переиспользуемый Python-движок конфиденциальности. Он обнаруживает чувствительный текст, применяет версионированные политики, выполняет редактирование локально и проверяет остаточный вывод перед тем, как пометить очищенный контент как одобренный.

Режим MCP не перехватывает автоматически каждый запрос. Хост должен вызвать инструмент и отправить только sanitized_text, когда status == "ok"; неправильно настроенный или вредоносный MCP-хост может обойти этот обычный рабочий процесс MCP. Встроенные хуки, применяемые провайдером, являются отдельными интеграционными активами: когда поддерживаемый провайдер вызывает такой хук на границе жизненного цикла запроса, он может применить то же детерминированное решение перед обычной обработкой модели. См. SecuRedact Enforced.

Зачем SecuRedact

ИИ-агенты все чаще читают файлы, вызывают инструменты и отправляют запросы внешним моделям. Это раскрывает PII, учетные данные и чувствительные документы, если только данные не проверяются заранее. SecuRedact — это контроль конфиденциальности и безопасности для ИИ-рабочих процессов:

  • Локальный — все обнаружение, редактирование и оценка политик выполняются на вашей машине. По умолчанию нет сетевого прослушивателя, нет телеметрии, нет вызовов провайдера.

  • Обнаружение PII / GDPR — имена, электронные письма, IBAN, идентификаторы и данные специальных категорий обнаруживаются и псевдонимизируются или редактируются.

  • Защита секретов и учетных данных — ключи API, токены и пароли обнаруживаются и блокируются от выхода из вашей среды.

  • Защита файловой системы — чтение защищено от обхода путей/символических ссылок и блокируется для защищенных путей, таких как .env.

  • Брандмауэр конфиденциальности ИИ-агента — встроенные хуки для Claude Code и Gemini CLI выполняют то же локальное решение перед запросом, вызовом модели или действием инструмента.

  • Осведомленность о сети / исходящем трафике — исходящие вызовы инструментов классифицируются (внутренние/внешние/неизвестные), чтобы политика могла требовать одобрения или блокировать исходящий трафик.

SecuRedact помогает снизить раскрытие чувствительных данных; это не гарантия соответствия требованиям и не заявление о том, что каждая утечка предотвращена. См. Ограничения.

Related MCP server: phi-redact-mcp

Быстрый старт

Установите из PyPI и запустите интерактивную настройку (Windows):

py -3.12 -m pip install "securedact-mcp[ml]"
securedact-mcp setup

Linux / macOS:

python3.12 -m pip install "securedact-mcp[ml]"
securedact-mcp setup

Защитите фрагмент текста за секунды (демо только с детерминированным режимом, модель не требуется):

import os

os.environ["SECUREDACT_REQUIRE_FLAIR"] = "0"  # deterministic detectors only
from securedact_core import RedactionRequest, SecuredactEngine

engine = SecuredactEngine.from_environment()
result = engine.prepare(
    RedactionRequest(
        text="Contact alex@example.test, IBAN NL91ABNA0417164300",
        policy="strict_external_ai",
    )
)
print(result.status)  # "ok"
print(result.sanitized_text)  # "Contact [EMAIL_1], IBAN [IBAN_1]"

Воспроизводимые синтетические демонстрации безопасности: docs/distribution/security-demo.md.

Безопасный рабочий процесс по умолчанию

Используйте prepare_for_external_ai для обычной подготовки к внешнему ИИ:

{
  "text": "Contact alex@example.test",
  "policy": "strict_external_ai",
  "language": "auto",
  "response_mode": "minimal"
}

Одобренный ответ:

{
  "schema_version": "1",
  "status": "ok",
  "sanitized_text": "Contact [EMAIL_1]",
  "counts": {"email": 1},
  "policy": "strict_external_ai",
  "policy_version": 1,
  "policy_digest": "...",
  "reason_codes": []
}

Ответы review_required и blocked никогда не содержат одобренного sanitized_text. Минимальные ответы не содержат исходного текста, необработанных значений сущностей, сопоставлений, тела исключения, трассировки стека, пути к модели или дескриптора восстановления, если только явно не был выбран restore_capable.

Архитектура и граница доверия

flowchart LR
    H["MCP host"] --> M["Securedact MCP"]
    M --> D["deterministic detectors"]
    M --> C["contextual detectors"]
    D --> P["policy engine"]
    C --> P
    P --> R["redactor"]
    R --> V["residual validator"]
    V --> O["approved sanitized output"]
    O --> W["host-controlled downstream workflow"]
    H -. "host may bypass MCP" .-> W

Сервер не имеет клиентов провайдера, прокси, совместимого с OpenAI, обратного прокси, веб-сайта, настольного чат-бота, учетных данных провайдера или пересылки, специфичной для провайдера. См. ADR 0001 и модель угроз.

Инструменты

Инструмент

Предполагаемое использование

Поведение при чувствительном ответе

prepare_for_external_ai

Рекомендуемый полный безопасный рабочий процесс

Минимальный по умолчанию

analyze_text

Низкоуровневый локальный анализ/проверка

Минимальный; смещения в review; необработанные значения только в включенном режиме отладки

redact_text

Низкоуровневая операция совместимости

Минимальный по умолчанию; явный режим legacy чувствителен и устарел

restore_text

Использование локальной непрозрачной сессии

Одноразовый по умолчанию; прямые сопоставления требуют явного доверенного устаревшего режима

create_safe_copy

Запись одобренного содержимого .txt/.md в одном настроенном корне

Не возвращает сопоставление или абсолютный путь

securedact_read_file

Безопасное чтение локального файла и возврат только очищенного текста

Блокирует защищенные пути перед чтением; отклоняет обход путей/символические ссылки/двоичные файлы; minimal по умолчанию

Режимы ответа: minimal, review, debug и restore_capable. Отладка отключена, если процесс не был запущен с SECUREDACT_ENABLE_DEBUG_RESPONSES=1; запрос MCP не может ее включить. Сессии восстановления в памяти используют криптографические случайные дескрипторы, ограниченную емкость, срок действия, защиту от параллелизма и одноразовое потребление. Выход из процесса уничтожает все сессии.

См. Инструменты MCP, конфиденциальность ответов и сессии восстановления.

Установка

Поддерживается Python >=3.12,<3.13.

Для обычной установки из PyPI:

py -3.12 -m pip install "securedact-mcp[ml]"
securedact-mcp setup

В Linux или macOS используйте python3.12 -m pip install "securedact-mcp[ml]"; python -m pip install "securedact-mcp[ml]" также подходит, когда python уже выбирает поддерживаемую среду 3.12.

setup проверяет пакет, зависимости Python и ML, проверяет состояние локальной модели, предлагает существующий установщик моделей на основе согласия, запускает существующий офлайн-верификатор и предлагает встроенные интеграции Claude Code и Gemini CLI, когда эти хосты обнаружены. Он использует официальные команды плагинов/расширений провайдеров и безопасен для повторного запуска. Он не вызывает API модели провайдера, не принимает доверие провайдера автоматически и не загружает контекстную модель, если пользователь явно не выбирает настройку модели и не принимает существующее вышестоящее приглашение.

Ручные команды модели остаются доступными для расширенной или автоматической работы:

securedact-mcp install
securedact-mcp models verify
securedact-mcp

Последняя команда запускает локальный сервер stdio. Стандартный вывод зарезервирован для сообщений протокола MCP. securedact-mcp setup --non-interactive сообщает состояние без подразумевания принятия вышестоящего соглашения или настройки нового провайдера. Используйте --host claude, --host gemini или --host all для целевой интерактивной настройки провайдера.

Установка для разработчиков/из исходников

Чтобы работать с проверенного исходного кода:

git clone https://github.com/GigantesHJI/securedact-mcp.git
cd securedact-mcp
python -m pip install ".[ml]"
securedact-mcp setup

Ни одна контрольная точка модели не включена в репозиторий или wheel, и при запуске она никогда не загружается. Securedact не распространяет эти веса моделей. Веса вышестоящих моделей сохраняют свои собственные лицензии и не перелицензируются под Apache-2.0. См. установка модели и лицензии третьих сторон.

Детерминированная локальная разработка должна быть явно выбрана:

$env:SECUREDACT_REQUIRE_FLAIR = "0"
securedact-mcp

Производственный режим по умолчанию требует контекстную возможность и закрывается с ошибкой, если настроенная модель отсутствует, загружается, повреждена или недоступна.

Пакеты для хостов

Проверенные конфигурационные активы и инструкции по безопасному рабочему процессу находятся в integrations/ для Codex, Cursor и Windsurf. Автоматизированный клиентский стенд MCP проверяет запуск сервера, список инструментов, вызовы, минимальную форму ответа, целостность stdout и завершение работы. Он не доказывает, что реальный хост вызывает инструмент для каждого запроса. См. доказательства совместимости.

Репозиторий также является корнем расширения Gemini CLI: gemini extensions install https://github.com/GigantesHJI/securedact-mcp может установить хуки. Тема gemini-cli-extension и релиз, дерево тегов которого содержит корневой манифест, требуются для разрешения этого пути; без pip install "securedact-mcp[ml]" и локальных моделей установленные хуки ничего не обеспечивают. См. SecuRedact Enforced.

Политики и Python API

Встроенные политики включают default, strict_external_ai, gdpr, identifiers_only и review_all_contextual; политики совместимости остаются доступными. Локальные файлы политик организации загружаются только из контролируемого каталога политик, используют строгую декларативную схему и не могут отключить инварианты закрытия при сбое. Неизвестные, дублирующиеся, слишком большие, некорректные или символически связанные политики закрываются с ошибкой.

from securedact_core import RedactionRequest, SecuredactEngine

engine = SecuredactEngine.from_environment()
result = engine.prepare(
    RedactionRequest(
        text="Contact alex@example.test",
        policy="strict_external_ai",
    )
)

from_environment() сохраняет требование контекстной модели. Автономная детерминированная разработка требует SECUREDACT_REQUIRE_FLAIR=0; приложения также могут внедрять протестированные реализации детекторов. См. публичный API и политики.

Воспроизводимая разработка

Зафиксированный uv.lock разрешает зависимости для runtime, ML, разработки, бенчмарков и безопасности для Python 3.12.

uv sync --frozen --extra dev --extra benchmark
uv run python scripts\verify.py

Никогда не используйте реальную личную информацию, частные документы, учетные данные, журналы клиентов или веса моделей в тестах, issues, скриншотах, фикстурах или pull request. См. CONTRIBUTING.md.

Оценка и производительность

uv run python -m securedact_eval quality --mode deterministic --gate `
  --thresholds benchmarks\thresholds.json `
  --baseline benchmarks\baselines\quality-deterministic.json
uv run python -m securedact_eval performance --mode deterministic

Версионированный синтетический корпус сообщает точность и ослабленную точность по спанам, полноту, F1, частоту ложных срабатываний и ложных пропусков, результаты по сущностям/языкам/доменам/разбиениям, точность действий/категорий и интервалы начальной загрузки для полноты. Истинно отрицательные примеры — это отрицательные примеры на уровне документов, а не безопасность на уровне токенов. Набор, связанный с GDPR, — это оценка обнаружения, а не сертификация юридического соответствия. Реальные бенчмарки Flair и GPU требуют явно настроенной локальной модели и не являются обычным CI. См. бенчмаркинг. Каркас бенчмарков документирует локальные уровни данных и большие профили; план миграции определяет его будущую границу извлечения. При сбое до выполнения шагов репозитория GitHub используйте дерево решений по устранению неполадок CI. Локальный успех не заменяет обязательную проверку GitHub.

Безопасность и ограничения

  • Ни один запрос, находка, сопоставление, дескриптор восстановления, секрет, вход модели или восстановленный вывод не регистрируются кодом приложения.

  • Детерминированное и контекстное обнаружение может пропустить новые, неоднозначные или враждебные раскрытия; устойчивость к кореференции и универсальной обфускации не заявляется.

  • Смещения обзора позволяют доверенному локальному клиенту с исходным вводом восстановить значение; держите ответы обзора локальными.

  • Поведение хоста и поведение нижестоящего провайдера находятся за пределами границы доверия.

  • Параметры безопасности репозитория, задокументированные в файлах, все еще требуют проверки администратором.

Сообщайте об уязвимостях конфиденциально, используя SECURITY.md. Не размещайте детали уязвимостей или реальные данные в публичном issue.

Лицензия

Исходный код и документация репозитория лицензированы под Apache License 2.0. Атрибуция авторских прав записана в NOTICE. Сторонние зависимости и веса моделей сохраняют свои собственные лицензии.

Available Tools

6 tools
analyze_textA
Read-onlyIdempotent

Inspect text locally and report detected sensitive content without producing sanitized output.

Use this when you need to understand what PII, secrets, or credentials are present (counts, entity types, and, with review/debug modes, positions) but do not need redacted text for transmission. The original text is not modified and no sanitized representation is returned. For a policy-approved, ready-to-send result use prepare_for_external_ai; for a sanitized file use create_safe_copy; for reversing a prior local session use restore_text.

Returns a JSON object with 'status' ('ok', 'review_required', or 'blocked'), 'policy', 'policy_version', 'policy_digest', 'counts' (entity-type tallies), and, when response_mode is 'review' or 'debug', a 'findings' list. 'debug' additionally returns 'debug_details'.

NameRequiredDescriptionDefault
textYesFree text to inspect locally for sensitive content. Processing is on this machine only; the original text is never modified or transmitted.
policyNoNamed analysis policy controlling which detectors and entity types apply. Defaults to 'default'. Common values include 'default'; other policies may be registered in your environment. An unknown name returns a policy_not_found error.default
response_modeNoLevel of detail returned. 'minimal' returns only status and entity-type counts; 'review' additionally returns a 'findings' list with spans and entity types; 'debug' additionally returns 'debug_details' (only when debug responses are enabled). Defaults to 'minimal'.minimal

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.9/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already mark the tool read-only and idempotent, and the description adds valuable context: the original text is not modified, no sanitized representation is returned, processing is local, and response modes change the output. No contradiction with annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured into overview, usage guidance, and return contract. It is slightly longer than minimal but every sentence earns its place, and the core purpose is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a read-only analysis tool, the description is complete: it covers what it does, when to use it, alternatives, side-effect behavior, response modes, and return shape. The output schema also exists, so the description does not need to over-explain returns.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the baseline is 3. The description adds extra value by clarifying response_mode behavior and the policy_not_found error case, going beyond the schema without repeating it.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb and resource: 'Inspect text locally and report detected sensitive content without producing sanitized output.' This immediately distinguishes it from redaction/export tools and makes the tool's purpose unmistakable.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It explicitly says when to use the tool ('when you need to understand what PII, secrets, or credentials are present... but do not need redacted text') and names alternatives for other needs: prepare_for_external_ai, create_safe_copy, and restore_text. This gives an agent clear routing guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

create_safe_copyA

Sanitize text locally and write the approved result to a new file in the Safe Copies directory.

Use this when you need a sanitized on-disk copy (for storage, handoff, or archival) rather than an in-memory sanitized string. For the sanitized text only, use prepare_for_external_ai; for inspection-only use analyze_text; for reversing a prior session use restore_text.

Side effects: a new file is written to the directory set by SECUREDACT_SAFE_COPY_DIR. The supplied 'content' is not modified and no existing file is overwritten. The filename must be a bare '.txt' or '.md' basename (no path separators or directory traversal). The operation blocks and reports 'blocked' if the directory is unconfigured, the filename is invalid, or policy blocks the content.

Returns a JSON object with 'status' ('ok' or 'blocked'), 'filename', and 'counts'.

NameRequiredDescriptionDefault
policyNoNamed redaction policy applied before writing. Defaults to 'strict_external_ai'. An unknown name returns a policy_not_found error.strict_external_ai
contentYesText to sanitize locally and write to disk. Processed on this machine; never transmitted.
filenameYesBare target filename (no directory components) ending in '.txt' or '.md'. The file is created inside the configured Safe Copies directory; an existing file is never overwritten.

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.7/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description goes well beyond the annotations by disclosing concrete side effects: writes to SECUREDACT_SAFE_COPY_DIR, never modifies the supplied content, never overwrites existing files, requires a bare '.txt' or '.md' filename, and blocks/reports 'blocked' on unconfigured directory, invalid filename, or policy failure. It also specifies the return shape.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three short paragraphs are used: purpose in the first sentence, usage guidance in the second, and side effects/return in the third. Every sentence earns its place and the description is front-loaded with the primary action.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the side-effecting nature of the tool, the description covers the operation, side effects, blocking/failure conditions, and return format. Combined with the rich output schema and annotations, an agent has all necessary information to invoke it correctly and safely.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema already documents all three parameters with detailed descriptions (100% coverage), so the description's restatements such as 'content is not modified' and 'bare target filename' add little new meaning. The baseline of 3 applies; the description does not need to compensate for missing schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb and resource: 'Sanitize text locally and write the approved result to a new file in the Safe Copies directory.' It explicitly contrasts this with in-memory sanitization and names sibling tools for alternative use cases, so an agent can distinguish it immediately.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It gives an explicit 'Use this when' condition (need a sanitized on-disk copy for storage, handoff, or archival) and names three sibling tools with their respective conditions: prepare_for_external_ai for sanitized text only, analyze_text for inspection-only, and restore_text for reversing a prior session. This is clear decision guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

prepare_for_external_aiA
Read-onlyIdempotent

Use this before sending user-supplied or potentially sensitive text to an external AI service.

SecuRedact inspects and sanitizes the text locally and returns the policy-approved representation; this tool does not transmit the text externally. It is the recommended default for outbound AI workflows. Use analyze_text for inspection-only classifications, redact_text for the lower-level compatibility path, create_safe_copy when a sanitized file is required, and restore_text only to reverse a prior local session in a trusted context.

Returns a JSON object with 'status' ('ok', 'review_required', or 'blocked'), 'sanitized_text' (present only when approved), 'counts', 'policy', and optionally 'restoration_session' (when response_mode is 'restore_capable').

NameRequiredDescriptionDefault
textYesFree text to inspect and sanitize locally before it is sent to an external AI service. All processing happens on this machine; this tool never transmits the text to any provider.
policyNoNamed redaction policy controlling which entity types are masked or blocked. Defaults to 'strict_external_ai'. Common values include 'strict_external_ai' and 'default'; other policies may be registered in your environment. An unknown name returns a policy_not_found error.strict_external_ai
languageNoHint for the contextual detection language. One of 'auto' (detect automatically), 'en', or 'nl'. Defaults to 'auto'.auto
response_modeNoAmount of detail returned. 'minimal' returns only the approved result and counts; 'review' adds per-detection findings for human review; 'debug' adds engine internals (only when debug responses are enabled); 'restore_capable' additionally returns a local restoration_session for later trusted restore_text. Defaults to 'minimal'.minimal

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, idempotentHint=true, and destructiveHint=false, so the agent knows the safety profile. The description adds valuable context: it explicitly states that the tool does not transmit text externally and that processing is local. It also discloses that unknown policy names return a policy_not_found error and describes the response structure (status field with values). This goes beyond annotations to explain operational behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is focused and well-structured. It opens with a clear directive and then alternates between contrasts and return-format details. Every sentence adds value, and the return format is clearly specified. It loses one point for being slightly longer than necessary, but it is still quite efficient with no fluff.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool is moderately complex with 4 optional parameters and an output schema, so the description does not need to explain return values in detail. It covers key aspects: what it does, when to use it, distinctions from siblings, policy parameter semantics, and the response_mode conditional field. It does not mention rate limits or auth, but given the annotations indicate a safe read-only operation and the schema is fully documented, a 4 is appropriate for completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the baseline is 3. The description adds significant parameter semantics beyond the schema: it explains the 'policy' parameter with default value and common values, warns about unknown policies causing errors; it clarifies 'response_mode' values including 'restore_capable' and mentions the conditional 'restoration_session' field in the output. It also explains 'language' options globally. This enriches parameter understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description begins with a clear directive: 'Use this before sending user-supplied or potentially sensitive text to an external AI service.' It specifies the action ('inspects and sanitizes'), the resource ('text'), and the local scope ('does not transmit the text externally'). It names its siblings and contrasts with them, making it easy to distinguish from alternatives like analyze_text and redact_text.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly states when to use it ('before sending... to an external AI service') and what it is not for. It enumerates alternative tools by name and explains their different purposes: 'analyze_text for inspection-only classifications, redact_text for the lower-level compatibility path, create_safe_copy when a sanitized file is required, and restore_text only to reverse a prior local session.' This gives clear routing guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

redact_textA
Read-onlyIdempotent

Direct/lower-level redaction entry point; prefer prepare_for_external_ai for normal outbound workflows.

In its normal modes this performs the same local sanitization as prepare_for_external_ai and returns the approved result, so most agents should call prepare_for_external_ai instead. Use redact_text when you specifically need this lower-level compatibility path, or the 'legacy' mode for local review of raw redaction internals. The 'legacy' mode returns potentially sensitive local-review details and is never selected by default.

Returns, for normal modes, the same approved result as prepare_for_external_ai (status, sanitized_text, counts). For 'legacy' mode it returns a result with deprecation_code 'legacy_sensitive_response' containing local-review redaction data.

NameRequiredDescriptionDefault
textYesFree text to redact locally. Processing is on this machine; nothing is transmitted externally.
policyNoNamed redaction policy controlling which entity types are masked or blocked. Defaults to 'default'. Common values include 'default' and 'strict_external_ai'; other policies may be registered. An unknown name returns a policy_not_found error.default
response_modeNoNormal modes behave like prepare_for_external_ai: 'minimal', 'review', and 'debug' return the approved result with increasing detail. The special value 'legacy' returns raw local-review redaction internals (including a mapping that reveals original values) under deprecation_code 'legacy_sensitive_response'; it must never be sent to an external service. Defaults to 'minimal'.minimal

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.7/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description adds valuable behavioral context beyond the annotations, noting that normal modes return the same approved result as prepare_for_external_ai and that 'legacy' mode returns sensitive local-review details under a deprecation_code and must never be sent externally. This complements the readOnlyHint and idempotentHint annotations without contradiction.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is organized and front-loaded with the most critical routing guidance: prefer prepare_for_external_ai. Each paragraph earns its place, covering normal modes, legacy mode caveats, and return behavior without unnecessary filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given that an output schema exists and the annotations cover read-only, idempotent, non-destructive behavior, the description provides sufficient context for selecting and invoking the tool correctly. It explains when to use it, what modes exist, and the sensitive nature of legacy output, leaving no critical gap for an agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the input schema already documents all parameters well. The description reinforces the response_mode semantics and legacy sensitivity but does not add substantial new meaning beyond what the schema already provides, so the baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly identifies redact_text as a lower-level redaction entry point and contrasts it with prepare_for_external_ai, stating that it performs the same local sanitization in normal modes. It also specifies the distinct 'legacy' mode purpose, making its role unambiguous relative to sibling tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly tells agents to prefer prepare_for_external_ai for normal outbound workflows and to use redact_text only when needing the lower-level compatibility path or 'legacy' mode for local review. This gives clear when-to-use and when-not-to-use guidance, directly addressing the main alternative.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

restore_textA

Reverse a prior SecuRedact protection step in a trusted, local-only context.

Use this ONLY after you previously received a restoration_session from SecuRedact (for example from prepare_for_external_ai with response_mode 'restore_capable') and now need to reconstruct the original text locally for trusted review. Restoration can reveal the original sensitive values (PII, secrets, credentials); it is a trusted-local operation, not a step to prepare data for external transmission. Never call it to sanitize or prepare text for an external AI; for that use prepare_for_external_ai. Never call it on text you did not previously protect with SecuRedact.

Security boundary: all processing is local and nothing leaves the machine. The 'mapping' form requires trusted_local_review=true and exposes raw originals, so its output must never be transmitted. Returns a JSON object with 'status' ('ok' or 'blocked'), 'restored_text' (present only on success), and 'reason_codes' describing any failure.

NameRequiredDescriptionDefault
textYesText containing SecuRedact placeholders (or a prior protected representation) to restore. Processed locally; never transmitted.
mappingNoLegacy direct mapping from placeholder token to original value. Supplying this bypasses the session vault and immediately reveals the original sensitive values. It is only honored when 'trusted_local_review' is true and 'restoration_session' is omitted.
restoration_sessionNoOpaque session token previously returned by SecuRedact (for example from prepare_for_external_ai with response_mode 'restore_capable'). It identifies the trusted local vault entry used to reverse protection and recover the original values. Required unless you supply 'mapping' together with trusted_local_review.
trusted_local_reviewNoExplicit acknowledgment that you are in a trusted local review context and accept that restoration reveals original sensitive values. Required (true) to use the 'mapping' form. It has no effect on the 'restoration_session' form.

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations carry almost no signal (all hints false), so the description bears full responsibility for behavioral disclosure, and it delivers: local-only processing, that restored values are raw PII/secrets never to be transmitted, that the mapping form bypasses the session vault, and the exact response contract (status, restored_text, reason_codes). This goes well beyond what the annotations provide and directly informs safe invocation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The purpose is front-loaded and the structure flows from what-it-does to when-to-use to security boundary to return format. It is somewhat longer than necessary — the mapping/trusted_local_review constraint is stated both in the description and in the schema — but the repeated security warnings are justified given the sensitivity of restored data.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With an output schema present and 100% parameter coverage, the description needs only to add selection and safety context, which it does thoroughly. An agent has everything needed to decide when to call it, which parameters to supply, what security posture to assume, and what the response will contain.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the baseline is 3; the description raises it by explaining the two mutually exclusive invocation forms (restoration_session vs mapping + trusted_local_review) and adding the security consequence of the mapping form. It adds semantic cohesion among the parameters that the schema's individual field descriptions do not provide.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb and resource ('Reverse a prior SecuRedact protection step') and clearly frames the operation as trusted-local reconstruction. It also differentiates itself from the key sibling by explicitly naming prepare_for_external_ai as the tool for the opposite direction, so an agent can disambiguate without opening schemas.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage conditions are explicit: call it only after receiving a restoration_session from a prior SecuRedact step, never to sanitize data, and never on text not previously protected. It names the alternative tool (prepare_for_external_ai) and states the exact precondition ('restore_capable'), leaving no ambiguity about when this tool applies.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

securedact_read_fileA
Read-onlyIdempotent

Safely read a local file and return only its sanitized (PII/secrets removed) text.

Use this when you must ingest a local file's contents for use with an external AI but want path-traversal, size, and binary defenses plus sanitization applied first. If the content is already in memory, use prepare_for_external_ai; for a sanitized file on disk, use create_safe_copy.

Side effects: reads a file from local disk and never transmits it. Sensitive paths and escapes are blocked before any file content is read. The returned 'sanitized_text' is safe to forward.

Returns a JSON object with 'status' ('ok' or 'blocked'), 'path', and 'sanitized_text' (present only when approved).

NameRequiredDescriptionDefault
pathYesLocal filesystem path to read. It is resolved and defended against path traversal, symlink/UNC escapes, and oversized or binary content (FW-011/012/013); sensitive paths are blocked before any file content is read.
policyNoNamed redaction policy applied to the file contents. Defaults to 'strict_external_ai'. An unknown name returns a policy_not_found error.strict_external_ai
max_bytesNoOptional cap on the number of bytes read from the file. When omitted, the engine's configured size limit applies.

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, idempotentHint=true, destructiveHint=false. The description adds useful context beyond those: side effects ('reads a file from local disk and never transmits it'), defense ordering ('Sensitive paths and escapes are blocked before any file content is read'), and return safety ('sanitized_text is safe to forward'). This aligns with and complements the annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose, then usage guidance, then side effects. It is moderately sized and each sentence earns its place, though the three-paragraph structure could be tightened slightly without losing information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

There is an output schema, and the description still gives a concise summary of return fields (status, path, sanitized_text) and edge cases (blocked/ok). It covers when to use the tool, alternatives, side effects, and defense guarantees. With schema and annotations carrying the rest, nothing an agent needs to invoke or react to this tool correctly is missing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with each parameter (path, policy, max_bytes) already described with details about defenses and defaults. The description adds no additional parameter-level semantics, so the baseline of 3 is appropriate—it doesn't degrade or enhance schema-provided meaning.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb+resource: 'Safely read a local file and return only its sanitized (PII/secrets removed) text.' It explicitly differentiates from siblings by naming prepare_for_external_ai and create_safe_copy, so an agent can distinguish it without opening schemas.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It gives explicit when-to-use: 'Use this when you must ingest a local file's contents for use with an external AI but want path-traversal, size, and binary defenses plus sanitization applied first.' It also provides concrete when-not and alternatives: 'If the content is already in memory, use prepare_for_external_ai; for a sanitized file on disk, use create_safe_copy.'

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 6 tool updatesv0.4.2
    • Changedanalyze_text3 fields changed
      • addedInput schema / properties / policy / description
        Added value: +"Named analysis policy controlling which detectors and entity types apply. Defaults to 'default'. Common values include 'default'; other policies may be registered in your environment. An unknown name returns a policy_not_found error."
      • addedInput schema / properties / response_mode / description
        Added value: +"Level of detail returned. 'minimal' returns only status and entity-type counts; 'review' additionally returns a 'findings' list with spans and entity types; 'debug' additionally returns 'debug_details' (only when debug responses are enabled). Defaults to 'minimal'."
      • addedInput schema / properties / text / description
        Added value: +"Free text to inspect locally for sensitive content. Processing is on this machine only; the original text is never modified or transmitted."
    • Changedcreate_safe_copy3 fields changed
      • addedInput schema / properties / content / description
        Added value: +"Text to sanitize locally and write to disk. Processed on this machine; never transmitted."
      • addedInput schema / properties / filename / description
        Added value: +"Bare target filename (no directory components) ending in '.txt' or '.md'. The file is created inside the configured Safe Copies directory; an existing file is never overwritten."
      • addedInput schema / properties / policy / description
        Added value: +"Named redaction policy applied before writing. Defaults to 'strict_external_ai'. An unknown name returns a policy_not_found error."
    • Changedprepare_for_external_ai4 fields changed
      • addedInput schema / properties / language / description
        Added value: +"Hint for the contextual detection language. One of 'auto' (detect automatically), 'en', or 'nl'. Defaults to 'auto'."
      • addedInput schema / properties / policy / description
        Added value: +"Named redaction policy controlling which entity types are masked or blocked. Defaults to 'strict_external_ai'. Common values include 'strict_external_ai' and 'default'; other policies may be registered in your environment. An unknown name returns a policy_not_found error."
      • addedInput schema / properties / response_mode / description
        Added value: +"Amount of detail returned. 'minimal' returns only the approved result and counts; 'review' adds per-detection findings for human review; 'debug' adds engine internals (only when debug responses are enabled); 'restore_capable' additionally returns a local restoration_session for later trusted restore_text. Defaults to 'minimal'."
      • addedInput schema / properties / text / description
        Added value: +"Free text to inspect and sanitize locally before it is sent to an external AI service. All processing happens on this machine; this tool never transmits the text to any provider."
    • Changedredact_text3 fields changed
      • addedInput schema / properties / policy / description
        Added value: +"Named redaction policy controlling which entity types are masked or blocked. Defaults to 'default'. Common values include 'default' and 'strict_external_ai'; other policies may be registered. An unknown name returns a policy_not_found error."
      • addedInput schema / properties / response_mode / description
        Added value: +"Normal modes behave like prepare_for_external_ai: 'minimal', 'review', and 'debug' return the approved result with increasing detail. The special value 'legacy' returns raw local-review redaction internals (including a mapping that reveals original values) under deprecation_code 'legacy_sensitive_response'; it must never be sent to an external service. Defaults to 'minimal'."
      • addedInput schema / properties / text / description
        Added value: +"Free text to redact locally. Processing is on this machine; nothing is transmitted externally."
    • Changedrestore_text4 fields changed
      • addedInput schema / properties / mapping / description
        Added value: +"Legacy direct mapping from placeholder token to original value. Supplying this bypasses the session vault and immediately reveals the original sensitive values. It is only honored when 'trusted_local_review' is true and 'restoration_session' is omitted."
      • addedInput schema / properties / restoration_session / description
        Added value: +"Opaque session token previously returned by SecuRedact (for example from prepare_for_external_ai with response_mode 'restore_capable'). It identifies the trusted local vault entry used to reverse protection and recover the original values. Required unless you supply 'mapping' together with trusted_local_review."
      • addedInput schema / properties / text / description
        Added value: +"Text containing SecuRedact placeholders (or a prior protected representation) to restore. Processed locally; never transmitted."
      • addedInput schema / properties / trusted_local_review / description
        Added value: +"Explicit acknowledgment that you are in a trusted local review context and accept that restoration reveals original sensitive values. Required (true) to use the 'mapping' form. It has no effect on the 'restoration_session' form."
    • Addedsecuredact_read_file
  2. 5 tool updatesv0.2.0
    • Changedanalyze_text1 field changed
      • addedInput schema / properties / response_mode
        Added value: +{
        +  "default": "minimal",
        +  "title": "Response Mode",
        +  "type": "string"
        +}
    • Changedcreate_safe_copy1 field changed
      • changedInput schema / properties / policy / default
        Previous value: -"default"New value: +"strict_external_ai"
    • Addedprepare_for_external_ai
    • Changedredact_text1 field changed
      • addedInput schema / properties / response_mode
        Added value: +{
        +  "default": "minimal",
        +  "title": "Response Mode",
        +  "type": "string"
        +}
    • Changedrestore_text11 fields changed
      • removedInput schema / properties / mapping / additionalProperties
        Removed value: -{
        -  "type": "string"
        -}
      • addedInput schema / properties / mapping / anyOf
        Added value: +[
        +  {
        +    "additionalProperties": {
        +      "type": "string"
        +    },
        +    "type": "object"
        +  },
        +  {
        +    "type": "null"
        +  }
        +]
      • addedInput schema / properties / mapping / default
        Added value: +null
      • removedInput schema / properties / mapping / type
        Removed value: -"object"
      • addedInput schema / properties / restoration_session
        Added value: +{
        +  "anyOf": [
        +    {
        +      "type": "string"
        +    },
        +    {
        +      "type": "null"
        +    }
        +  ],
        +  "default": null,
        +  "title": "Restoration Session"
        +}
      • addedInput schema / properties / trusted_local_review
        Added value: +{
        +  "default": false,
        +  "title": "Trusted Local Review",
        +  "type": "boolean"
        +}
      • changedInput schema / required
        Previous value: -[
        -  "text",
        -  "mapping"
        -]New value: +[
        +  "text"
        +]
      • addedOutput schema / additionalProperties
        Added value: +true
      • removedOutput schema / properties
        Removed value: -{
        -  "result": {
        -    "title": "Result",
        -    "type": "string"
        -  }
        -}
      • removedOutput schema / required
        Removed value: -[
        -  "result"
        -]
      • changedOutput schema / title
        Previous value: -"restore_textOutput"New value: +"restore_textDictOutput"
  3. 4 tool updatesv0.1.0
    • First observedanalyze_text
    • First observedcreate_safe_copy
    • First observedredact_text
    • First observedrestore_text

TDQS

A4.5/5.0

Scored across 6 tools

Disambiguation4/5

Most tools have clearly distinct outputs (in-memory text, file write, file read, inspection, restoration), but prepare_for_external_ai and redact_text perform identical sanitization in normal modes, with redact_text explicitly deferring to prepare_for_external_ai. This creates a potential misselection point despite the helpful cross-references.

Naming Consistency4/5

The majority of tools follow a clean verb_noun pattern (analyze_text, redact_text, restore_text, create_safe_copy). prepare_for_external_ai and securedact_read_file deviate with a prepositional phrase and a brand prefix, but the overall naming remains readable and predictable.

Tool Count5/5

Six tools is well within the ideal scope for a focused sanitization server. Each tool maps to a distinct workflow step, and none feel extraneous enough to bloat the surface.

Completeness4/5

The set covers the core lifecycle: inspection, in-memory sanitization, safe file output, safe file input, and session restoration. Minor gaps exist around policy management and the redundant redact_text path, but there are no critical dead ends for the stated purpose.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    B
    maintenance
    An MCP server that redacts PII/PHI from text before it ever reaches an LLM — self-hosted, fail-closed, and HIPAA-aware.
    3
    24 PyPI
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    MCP server providing on-prem PII detection and anonymization tools (scan and is_sensitive) for AI agents, ensuring data stays local.
    4
    MIT
  • F
    license
    A
    quality
    B
    maintenance
    MCP server for local, verifiable PDF redaction. Enables AI agents to find sensitive regions, locate text, redact PDFs on-device, verify redaction and tamper-evidence seals, and generate PDFs—without uploading confidential documents.
    8
    1,457 npm
    -