WorkingDirectory icon
Queries icon
Script icon
Query icon
OutputValues icon
Log icon
McpToolTrigger icon

Governed Diagnostic Data Slicing and PII Masking Broker for AI Agents

Safely query diagnostic database slices via MCP with automated PII masking, SQL injection filtering, and cryptographic audit receipts in Kestra.

Categories
AI

Production debugging frequently requires inspecting customer or transactional state to diagnose active incidents. However, granting autonomous AI coding assistants direct database access exposes organizations to catastrophic risks: unintentional PII exfiltration violating GDPR Article 30 or HIPAA, destructive SQL execution, and lack of compliance traceability.

This blueprint implements a secure Diagnostic Data Broker exposed directly to AI agents (such as Claude Code, Cursor, or internal assistants) via Kestra 2.0's native McpToolTrigger. The workflow acts as an automated security boundary: it strictly validates query filters against an allowlist, executes read-only extractions inside an isolated engine, applies deterministic HMAC pseudonymization and PII masking, writes full datasets to internal storage, and issues a cryptographic SHA-256 audit receipt before returning results to the calling agent.

flowchart TD
  Agent["AI Assistant (Claude / Cursor)"] -->|"MCP Tool Call: fetch_sanitized_diagnostic_slice"| Trigger["McpToolTrigger"]
  Trigger --> Validate["SQL Safety Guardrail Task"]
  Validate -->|"Passed"| Query["Query DuckDB Relational Store"]
  Validate -->|"Prohibited Token Detected"| Errors["Errors: Policy Rejection Envelope"]
  Query --> Anonymize["HMAC Pseudonymization & PII Redaction"]
  Anonymize --> Receipt["Compute SHA-256 Audit Digest"]
  Receipt --> Output["Format MCP Response Envelope"]
  Output --> Audit["Record Immutable Audit Log"]
  Audit -->|"Return Sanitized JSON + Storage URI"| Agent

How it works

  1. MCP Tool Registration: The mcp_diagnostic_broker trigger registers fetch_sanitized_diagnostic_slice on Kestra's default MCP server. Flow inputs (target_entity, lookup_filter, purpose_justification, max_records, redaction_mode, and dry_run) automatically form the tool's JSON Schema specification.
  2. Isolated Environment Setup: The sandbox_workspace creates an ephemeral relational workspace with mock production schemas for customers, billing_transactions, and audit_events.
  3. SQL Injection Guard: The validate_sql_filter_guard script analyzes the requested lookup_filter for disallowed keywords (including ;, --, /*, DROP, ALTER, TRUNCATE, INSERT, UPDATE, DELETE, GRANT, UNION, and file exfiltration clauses). If any prohibited token is found, the script raises an immediate error.
  4. Bounded Query Execution: The execute_diagnostic_query task runs a read-only parameterized query against DuckDB, enforcing the max_records safety ceiling to prevent bulk exfiltration.
  5. In-Flight Pseudonymization & Redaction: The anonymize_and_mask_records Python script processes extracted rows. Customer IDs are replaced with keyed HMAC-SHA256 pseudonyms so cross-table entity joins remain testable by AI agents without revealing real primary keys. Email addresses, phone numbers, IP addresses, and payment card details are redacted or masked according to the selected redaction_mode.
  6. Integrity Checksum & Audit Artifact: The task computes a SHA-256 digest over the finalized JSON payload, stores sanitized_diagnostic_slice.json in Kestra internal storage, and emits structured outputs.
  7. Audit Record & Envelope Return: The format_mcp_response and record_compliance_audit_log tasks produce an audit trail containing the execution ID, AI session identifier, purpose rationale, and payload checksum before returning the clean JSON envelope to the AI agent.

What you get

  • A production-grade MCP tool endpoint enabling AI assistants to troubleshoot real errors without direct database access.
  • Deterministic HMAC pseudonymization ensuring entity relationships remain correlatable across queries.
  • Multi-tier PII protection covering emails, phone numbers, client IP addresses, and payment details.
  • Cryptographic SHA-256 audit receipts proving exact data states delivered to AI models.
  • Automated policy rejection routing alerting security operations of suspicious queries.

Who it's for

  • Platform Engineers and SecOps teams establishing governed AI integration boundaries.
  • SRE and on-call engineers using AI assistants to debug production incidents.
  • Compliance officers needing verifiable audit trails for AI data access.
  • Data platform architects designing self-service diagnostic APIs.

Why orchestrate this with Kestra

Allowing external AI models to interact with production infrastructure requires strong guardrails, deterministic execution, and complete auditability. Running this workflow in Kestra provides distinct advantages:

  • Native MCP Protocol Integration: Kestra 2.0's McpToolTrigger exposes flows directly to AI agents without requiring external API gateway proxies, custom socket bridges, or bespoke authentication code.
  • Unified Execution Auditing: Every AI agent request creates a standard Kestra execution tagged with system.from: mcp, providing Gantt timing charts, logs, input tracking, and replay capability.
  • Language-Agnostic Isolation: Combines high-speed analytical database processing (DuckDB) with Python data masking inside a unified WorkingDirectory.

Pitfalls

  • Dynamic Filtering Limitations: While the SQL safety guard filters common injection syntax and destructive operations, complex analytical subqueries should be restricted using predefined query templates in high-compliance environments.
  • Masking Salt Rotation: If the DATA_MASKING_SALT secret is rotated, deterministic pseudonyms generated across different executions will no longer correlate with previously generated diagnostic slices.
  • Large Dataset Exfiltration: Always maintain a reasonable max_records ceiling (default 25, recommended maximum 100). Never allow AI agents to request unbounded row counts.

Prerequisites

  • Kestra 2.0.0 or later with the built-in MCP server enabled (standard in default tenant setups).
  • An MCP-compatible AI client (Claude Code, Cursor, Claude Desktop, or custom agent).

Secrets

  • DATA_MASKING_SALT: Cryptographic salt string used to generate HMAC-SHA256 pseudonyms (optional: falls back to a default configuration string if unset).

Inputs

  • target_entity: Select dropdown choosing between customers, billing_transactions, or audit_events.
  • lookup_filter: Parameterized SQL condition (e.g., status = 'SUSPENDED' AND account_tier = 'ENTERPRISE').
  • purpose_justification: Mandatory string describing the incident ticket or operational purpose.
  • max_records: Integer ceiling restricting retrieved rows (default: 25).
  • redaction_mode: Redaction strategy (DETERMINISTIC_HASH or PARTIAL_MASK).
  • dry_run: Boolean switch to test query syntax without serializing record payloads.

Outputs

  • status: Execution outcome (SUCCESS or REJECTED_BY_POLICY).
  • record_count: Total number of sanitized records retrieved.
  • sha256_audit_receipt: Cryptographic hash digest calculated across the redacted payload.
  • records_preview: Truncated JSON preview returned directly in the agent conversation window.
  • storage_uri: Internal storage URI pointing to the full sanitized dataset file.

Quick start

  1. Import this blueprint into your Kestra instance under the company.ai namespace.
  2. Click Execute in the Kestra UI to run with default inputs and review the masked outputs in the execution summary.
  3. Connect your AI assistant (e.g. Claude Code or Cursor) to Kestra's MCP server endpoint (https://<kestra-host>/v1/mcp).
  4. Instruct the agent: "Diagnose suspended enterprise accounts using the diagnostic broker tool."
  5. The agent automatically discovers fetch_sanitized_diagnostic_slice, submits the query, and inspects the sanitized data.

How to extend

  • External Database Integration: Replace DuckDB with PostgreSQL (io.kestra.plugin.jdbc.postgresql.Query) or Snowflake to query real staging or read-replica databases.
  • Incident Ticket Verification: Add an upstream HTTP check against Jira or ServiceNow to verify that purpose_justification corresponds to an active, approved incident ticket.
  • Human-in-the-Loop Escalation: Add an approval gate (io.kestra.plugin.core.flow.Pause) if an AI agent requests more than 50 records or accesses sensitive financial tables.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.