This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Protecting Agentic Workflows

Protect sensitive data at every stage of an agentic pipeline using AI Developer Edition with Cursor.

Use AI Developer Edition to detect and protect sensitive data across prompts, tool calls, and outputs in agent workflows. This guide provides sample prompts for Cursor to protect the entire agent pipeline using AI Developer Edition.

For a complete walkthrough that demonstrates all capabilities in a single scenario, refer to End-to-End Scenario: Privacy-Safe Employee Insights Agent.

The Protected Agent Pipeline

┌─────────────────────────────────────────────────────────────────────┐
│  PROTECTED AGENT WORKFLOW                                            │
│                                                                      │
│  ┌─────────┐     ┌──────────┐    ┌──────────┐    ┌─────────────┐   │
│  │  Input  │───▶│ Reasoning│───▶│Tool Call │───▶│   Output    │   │
│  │ Sanitize│     │  (Safe)  │    │(Validated)│   │ Re-protect  │   │
│  └─────────┘     └──────────┘    └──────────┘    └─────────────┘   │
│       ▲              ▲               ▲                ▲             │
│       │              │               │                │             │
│  ┌────┴──────────────┴───────────────┴────────────────┴────────┐   │
│  │            SEMANTIC GUARDRAILS (Continuous Monitoring)        │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

With AI Developer Edition, developers secure every step:

  • Sanitize input → Safe reasoning → Controlled execution → Protected output → Continuous monitoring

Sample Prompts for Cursor to Protect Agent Workflows

1. End-to-End Protected Workflow

Placement: System prompt / middleware layer (before agent run)

Purpose: Enforces full pipeline protection from entry

In Cursor’s AI chat, enter the following prompt:

Using AI Developer Edition, wrap my agent workflow with end-to-end protection. Scan every input for PII and secrets using Find and Protect, tokenize what is found, validate each tool call through Semantic Guardrails, block any request that looks like a data-extraction attempt, re-protect all outputs, and log every protection event for audit.

Implementation:

import protegrity_developer_python
import requests

protegrity_developer_python.configure(
    endpoint_url="http://localhost:8580/pty/data-discovery/v2/classify",
    classification_score_threshold=0.6,
    enable_logging=True,
    log_level="info"
)

GUARDRAIL_URL = "http://localhost:8581/pty/semantic-guardrail/v1.1/conversations/messages/scan"

class EndToEndProtectedAgent:
    """Agent with full AI Developer Edition protection pipeline."""
    
    def __init__(self, system_prompt: str):
        self.system_prompt = system_prompt
    
    def run(self, user_input: str) -> str:
        # Step 1: Scan and protect input
        safe_input = protegrity_developer_python.find_and_protect(user_input)
        
        # Step 2: Evaluate through guardrails
        payload = {
            "messages": [{"role": "user", "content": safe_input}],
            "processors": ["semantic", "pii"]
        }
        guard_check = requests.post(GUARDRAIL_URL, json=payload).json()
        if guard_check.get("action") == "BLOCK":
            return f"Request blocked: {guard_check.get('reason')}"
        
        # Step 3: Agent reasons on safe data
        response = self._reason(safe_input)
        
        # Step 4: Re-protect output
        safe_output = protegrity_developer_python.find_and_protect(response)
        
        return safe_output
    
    def _reason(self, safe_input: str) -> str:
        """Agent reasoning on protected data."""
        return llm.generate(self.system_prompt + "\n" + safe_input)

2. Secure Code with API Usage

Placement: Input pre-processing before Cursor call.

Purpose: Secures code, secrets, API usage

In Cursor’s AI chat, enter the following prompt:

Using AI Developer Edition, review my repository for hardcoded API keys, connection strings with credentials, tokens in .env files, and PII in comments or test fixtures. Use Data Discovery to detect the secrets, replace each one with a token in TKN-XXX format before Cursor processes the code, and apply Semantic Guardrails so only read-only API calls are allowed. Block any write or delete operation unless explicitly approved, and log every detected secret for security review.

Implementation:

import protegrity_developer_python
import os

class SecureCodeAgent:
    """Agent that safely processes code repositories."""
    
    def analyze_repo(self, repo_path: str) -> dict:
        # Step 1: Discover and protect secrets in codebase
        secrets_found = 0
        for root, dirs, files_list in os.walk(repo_path):
            for file in files_list:
                if file.endswith((".py", ".js", ".java", ".yml", ".env")):
                    filepath = os.path.join(root, file)
                    with open(filepath, "r") as f:
                        content = f.read()
                    protected = protegrity_developer_python.find_and_protect(content)
                    if protected != content:
                        secrets_found += 1
                        with open(filepath + ".safe", "w") as f:
                            f.write(protected)
        
        # Step 2: Agent analyzes safe codebase
        analysis = agent.analyze(repo_path)
        
        return {
            "secrets_found": secrets_found,
            "secrets_protected": True,
            "analysis": analysis
        }

3. Safe Multi-Agent Execution

Placement: Agent orchestrator / controller

Purpose: Secures agent chaining and data flow between agents

In Cursor’s AI chat, enter the following prompt:

Using AI Developer Edition, orchestrate my multi-agent pipeline safely. Give each agent only the data it needs (least privilege), tokenize sensitive fields between agent handoffs, validate every agent action through Semantic Guardrails, and prevent any agent from accessing another agent's raw context. Log and audit all inter-agent communication.

Implementation:

import protegrity_developer_python
import requests

GUARDRAIL_URL = "http://localhost:8581/pty/semantic-guardrail/v1.1/conversations/messages/scan"

class SecureOrchestrator:
    """Orchestrates multiple agents with data protection between them."""
    
    def execute_pipeline(self, task: str, agents: list) -> str:
        context = task
        
        for i, agent in enumerate(agents):
            # Protect data before passing to next agent
            safe_context = protegrity_developer_python.find_and_protect(context)
            
            # Validate agent action through guardrails
            payload = {
                "messages": [{"role": "user", "content": f"Agent {agent.name}: {agent.planned_action}"}],
                "processors": ["semantic"]
            }
            action_check = requests.post(GUARDRAIL_URL, json=payload).json()
            
            if action_check.get("action") == "BLOCK":
                return f"Pipeline halted: Agent '{agent.name}' blocked - {action_check.get('reason')}"
            
            # Agent processes safe data
            result = agent.execute(safe_context)
            
            # Re-protect output before passing to next agent
            context = protegrity_developer_python.find_and_protect(result)
        
        return context

4. Safe Log Debugging

Placement: Tool wrapper (before sending logs to Cursor)

Purpose: Enables safe debugging without PII exposure

In Cursor’s AI chat, enter the following prompt:

Using AI Developer Edition, help me debug production logs safely. Anonymize all user identifiers (emails, IDs, names) and mask tokens and session data, but preserve timestamps, error types, and stack traces so I still have enough context for root-cause analysis. Never expose real user data in the debug output.

Implementation:

import protegrity_developer_python

class SafeDebugger:
    """Debug production issues without exposing user data."""
    
    def debug(self, log_content: str) -> str:
        # Redact user data from logs
        safe_logs = protegrity_developer_python.find_and_redact(log_content)
        
        # Send to AI for analysis
        diagnosis = ai_model.analyze(safe_logs)
        
        return diagnosis

5. Data Protection with RAG Pipelines

Placement: RAG pipeline after retrieval and before LLM.

Purpose: Secures retrieval, reasoning, and output

In Cursor’s AI chat, enter the following prompt:

Using AI Developer Edition, protect my RAG pipeline. Anonymize sensitive fields in retrieved documents before they reach the LLM context, use Semantic Guardrails to prevent PII in the output, allow aggregate insights but block responses about individual records, and re-protect any response that references specific people.

Implementation:

import protegrity_developer_python
import requests

GUARDRAIL_URL = "http://localhost:8581/pty/semantic-guardrail/v1.1/conversations/messages/scan"

class ProtectedRAG:
    """RAG pipeline with full data protection."""
    
    def query(self, user_query: str) -> str:
        # Step 1: Evaluate query through guardrails
        payload = {
            "messages": [{"role": "user", "content": user_query}],
            "processors": ["semantic", "pii"]
        }
        query_check = requests.post(GUARDRAIL_URL, json=payload).json()
        if query_check.get("action") == "BLOCK":
            return "Query blocked: potential data extraction attempt"
        
        # Step 2: Retrieve documents
        documents = vector_db.retrieve(user_query, top_k=5)
        
        # Step 3: Redact PII from retrieved content
        safe_docs = [protegrity_developer_python.find_and_redact(doc) for doc in documents]
        
        # Step 4: LLM reasons on redacted context
        response = llm.generate(
            context=safe_docs,
            query=user_query,
            system="Provide insights without mentioning specific individuals."
        )
        
        # Step 5: Validate response for PII leakage
        resp_payload = {
            "messages": [{"role": "assistant", "content": response}],
            "processors": ["pii"]
        }
        response_check = requests.post(GUARDRAIL_URL, json=resp_payload).json()
        if response_check.get("action") == "BLOCK":
            response = protegrity_developer_python.find_and_redact(response)
        
        return response

Complete Sample Code: Protected Agent Pipeline

"""
Complete Cursor Agent with AI Developer Edition Protection
-------------------------------------------------------
Demonstrates: protect → reason → validate → execute → re-protect
"""
import protegrity_developer_python
import requests

protegrity_developer_python.configure(
    endpoint_url="http://localhost:8580/pty/data-discovery/v2/classify",
    classification_score_threshold=0.6,
    enable_logging=True,
    log_level="info"
)

GUARDRAIL_URL = "http://localhost:8581/pty/semantic-guardrail/v1.1/conversations/messages/scan"

# ═══════════════════════════════════════════════════════════════
# PROMPT PROTECTION: Sanitize input before AI processing
# ═══════════════════════════════════════════════════════════════
def protect_input(user_input: str) -> str:
    """Scans input for PII/secrets and replaces with tokens."""
    return protegrity_developer_python.find_and_protect(user_input)

# ═══════════════════════════════════════════════════════════════
# REASONING: Agent processes safe data only
# ═══════════════════════════════════════════════════════════════
def reason(safe_prompt: str) -> str:
    """Agent reasons on safe data only."""
    response = agent.run(safe_prompt)
    return response

# ═══════════════════════════════════════════════════════════════
# TOOL CALL: Validate intent and restore data for execution
# ═══════════════════════════════════════════════════════════════
def execute_tool(action: str, data: dict, auth) -> any:
    """Restores real data only for approved execution."""
    payload = {
        "messages": [{"role": "user", "content": f"Execute action: {action}"}],
        "processors": ["semantic"]
    }
    guard_check = requests.post(GUARDRAIL_URL, json=payload).json()
    if guard_check.get("action") != "BLOCK":
        real_data = protegrity_developer_python.find_and_unprotect(str(data))
        result = call_tool(action, real_data)
        return result
    else:
        raise SecurityError(f"Action '{action}' blocked by guardrails")

# ═══════════════════════════════════════════════════════════════
# OUTPUT PROTECTION: Re-apply protection to response
# ═══════════════════════════════════════════════════════════════
def protect_output(response: str) -> str:
    """Re-applies protection to response to prevent data leakage."""
    return protegrity_developer_python.find_and_protect(response)

# ═══════════════════════════════════════════════════════════════
# CONTINUOUS GUARDRAILS: Monitor for unsafe behavior
# ═══════════════════════════════════════════════════════════════
def monitor_workflow(step: str, data: any) -> None:
    """Semantic Guardrails continuously score risk across the workflow."""
    payload = {
        "messages": [{"role": "user", "content": str(data)}],
        "processors": ["semantic", "pii"]
    }
    risk = requests.post(GUARDRAIL_URL, json=payload).json()
    if risk.get("action") == "BLOCK":
        block_or_escalate(risk)

# ═══════════════════════════════════════════════════════════════
# FULL WORKFLOW: End-to-end protected execution
# ═══════════════════════════════════════════════════════════════
def protected_workflow(user_input: str, auth) -> str:
    """
    Complete protected agent workflow:
    Input → Protect → Reason → Validate → Execute → Re-protect → Output
    """
    
    # 1. Protect input
    safe_input = protect_input(user_input)
    monitor_workflow("input", safe_input)
    
    # 2. Agent reasons on safe data
    response = reason(safe_input)
    monitor_workflow("reasoning", response)
    
    # 3. If tool call needed, validate and execute
    if requires_tool_call(response):
        action, data = parse_tool_call(response)
        monitor_workflow("tool_call", {"action": action, "data": data})
        result = execute_tool(action, data, auth)
        monitor_workflow("tool_result", result)
    else:
        result = response
    
    # 4. Protect output
    safe_output = protect_output(str(result))
    monitor_workflow("output", safe_output)
    
    return safe_output
# ═══════════════════════════════════════════════════════════════
# EXAMPLE: Cursor agent reads repo and calls API
# ═══════════════════════════════════════════════════════════════
# AI Developer Edition:
# - Masks secrets in prompt
# - Enforces safe tool access
# - Blocks data leakage across steps
user_request = "Analyze my repo and deploy the payment service"
result = protected_workflow(user_request, auth=developer_credentials)
# 1. Discovery finds API keys in code → tokenized
# 2. Agent analyzes code structure safely
# 3. Guardrails validate deployment action
# 4. Real credentials restored only for approved deploy
# 5. Output re-protected before returning to developer

1 - Security Coverage Matrix

Protection applied and threats mitigated at each pipeline stage.

The following table shows the protection applied at each stage of the agent pipeline and the threat each control is designed to mitigate.

Pipeline StepProtection AppliedThreat Mitigated
InputDiscovery and TokenizationSecret/PII in prompts
ReasoningGuardrails monitoringPrompt injection
Tool CallsIntent validation and AuthenticationUnauthorized actions
Cross-AgentRe-tokenizationData leakage between agents
OutputPII scanning and Re-protectSensitive data in responses
LogsAnonymizationIdentity exposure in debug
StorageTokenizationPII at rest
ContinuousSemantic GuardrailsPolicy violations, anomalies

2 - Sample Code

Code samples for protecting sensitive data in agentic workflows and RAG pipelines.

This section covers the full working implementation of the Privacy-Safe Employee Insights Agent, including project structure, module reference, and language-specific examples. Each code snippet includes a brief description, sample prompt for Cursor, and implementation details.

Project Structure

employee-insights-agent/
├── main.py                        # End-to-end demo (run this)
├── config.py                      # Configuration
├── requirements.txt               # Dependencies
├── modules/
│   ├── synthetic_data.py          # Step 1: Generate data
│   ├── discovery.py               # Step 2: Classify fields
│   ├── anonymization.py           # Step 3: Anonymize for training
│   ├── masking.py                 # Step 4: Mask for operations
│   ├── tokenization.py            # Step 5: Tokenize for storage
│   ├── unprotect.py               # Step 6: Authorized access
│   └── guardrails.py              # Step 7: Semantic guardrails
├── webapp/
│   ├── app.py                     # Flask web portal
│   └── templates/index.html       # Dashboard UI
├── samples/
│   ├── synthetic_data/            # Domain-specific generation
│   ├── guardrails/                # Attack scenario tests
│   ├── discovery/                 # Codebase scanning
│   ├── protection/                # Tokenization workflows
│   ├── anonymization/             # RAG + debugging
│   └── agentic_workflows/         # Multi-agent protection
└── docs/                          # This documentation

Running the Demo

# Install dependencies
pip install -r requirements.txt
# Run complete end-to-end demo
python main.py
# Launch web portal
python webapp/app.py
# Open: http://localhost:5000

Module Reference

Each module covers a distinct stage of the data protection pipeline, from generating synthetic data and classifying sensitive fields to tokenizing, masking, anonymizing, and controlling access to real values.

modules/synthetic_data.py - Data Generation

This module generates realistic synthetic employee datasets with correlated fields such as department, salary, and demographic data. Use it to create test data that mirrors production characteristics without exposing real employee records.

Cursor Code:

from modules.synthetic_data import generate_employee_records, save_employee_data
# Generate 1000 synthetic employee records
df = generate_employee_records(num_records=1000)
# Save to CSV
save_employee_data(df, "data/employees.csv")

Key functions:

  • generate_employee_records(num_records) - Creates realistic employee dataset
  • generate_salary(department) - Department-correlated salary generation
  • generate_ssn() - Synthetic SSN format generation
  • save_employee_data(df, filepath) - Persist to CSV

modules/discovery.py - Sensitive Data Classification

This module scans a DataFrame and classifies each column as sensitive or non-sensitive using a combination of name-based heuristics and content pattern analysis. It returns confidence scores for each detected category so you can decide which fields require protection.

Cursor Code:

from modules.discovery import discover, print_discovery_report
# Run discovery on DataFrame
results = discover(employee_data)
# Print formatted report
print_discovery_report(results)

Key functions:

  • discover(data) - Classify all columns with confidence scores
  • classify_column_by_name(name) - Name-based heuristics
  • classify_column_by_content(series) - Pattern-based content analysis
  • print_discovery_report(results) - Formatted output

modules/anonymization.py - Identity Removal

This module removes or replaces identifying fields while preserving the structural patterns and statistical relationships that make the data useful for AI training. After anonymization, use validate_anonymization to confirm that utility is retained before passing the data to a model.

Cursor Code:

from modules.anonymization import anonymize, validate_anonymization
# Anonymize for AI training
anonymized = anonymize(data, preserve_utility=True)
# Validate utility preservation
validation = validate_anonymization(original, anonymized)

Key functions:

  • anonymize(data, columns, preserve_utility) - Remove identities
  • validate_anonymization(original, anonymized) - Verify utility preserved

modules/masking.py - Partial Data Hiding

This module applies role-based masking strategies that partially obscure sensitive fields for operational use. Unlike tokenization, masking is irreversible it is intended for display surfaces and logs where users need to see the shape of the data but not the actual values.

Cursor Code:

from modules.masking import mask
# Apply role-based masking
masked = mask(data, strategy="hr_analyst")  # or "full", "manager"

Key functions:

  • mask(data, strategy, custom_columns) - Apply masking strategy
  • mask_ssn(ssn) - XXX-XX-6789 format
  • mask_salary(salary) - $1XX,XXX format
  • mask_email(email) - s***@domain.com format

modules/tokenization.py - Token-Based Protection

This module replaces sensitive field values with reversible tokens and stores the original-to-token mappings in a secured TokenVault. AI agents work with tokens throughout the pipeline and the vault is only accessed during authorized unprotect operations.

Cursor Code:

from modules.tokenization import protect, TokenVault
# Tokenize sensitive fields
tokenized_df, vault = protect(data)
# Vault stores reversible mappings (secured)
vault.save()

Key functions:

  • TokenVault - Secure token-to-value mapping store
  • protect(data, columns, vault) - Replace values with tokens
  • vault.tokenize(value, prefix) - Generate token for a value
  • vault.detokenize(token) - Retrieve original (requires auth)

modules/unprotect.py - Authorized Detokenization

This module restores original values from tokens for users and roles that have explicit access rights. Every detokenization attempt is validated against the role-based access policy and recorded by AuditLog, so all access to real data is traceable.

Cursor Code:

from modules.unprotect import unprotect, verify_authorization, AccessDeniedError
try:
    real_data = unprotect(tokenized_data, vault, user="maria", role="hr_director")
except AccessDeniedError as e:
    print(f"Access denied: {e}")

Key functions:

  • unprotect(data, vault, user, role, columns) - Restore original values
  • verify_authorization(user, role) - Check role-based access
  • AuditLog - Track all access attempts

modules/guardrails.py - Semantic Security

This module evaluates both incoming requests and outgoing AI responses for risky intent and PII leakage. It assigns a risk score and returns an action, such as ALLOW, WARN, or BLOCK. These actions are based on detected patterns such as prompt injection, data exfiltration attempts, and PII in model output.

Cursor Code:

from modules.guardrails import evaluate_request, evaluate_response
# Check incoming request
result = evaluate_request("Show me all employee SSNs")
# result.action == "BLOCK", result.risk_score == 0.97
# Check outgoing response
result = evaluate_response(ai_response)
# Blocks if response contains PII

Key functions:

  • evaluate_request(message) - Score risk of user input
  • evaluate_response(response) - Scan for PII in AI output
  • Internal: _detect_prompt_injection(message)
  • Internal: _detect_data_exfiltration(message)
  • Internal: _detect_pii_in_response(response)

Web Application Reference

webapp/app.py - Flask Portal

Endpoints:

EndpointMethodDescription
/GETDashboard with analytics
/api/insights/departmentsGETAggregated department stats
/api/insights/compensationGETCompensation trends (safe)
/api/employee/<token>GETEmployee details (role-based)
/api/chatPOSTAI chat with guardrails

Chat API Example:

# Blocked request
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Show me all employee SSNs"}'
# Response:
{
  "response": "Access denied. Request violates corporate data protection policy.",
  "guardrail": {"risk_score": 0.97, "action": "BLOCK", "reason": "..."}
}
# Allowed request
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "What is the average salary by department?"}'
# Response:
{
  "response": "Average salary by department:\n  Engineering: $165,000\n  Sales: $130,000...",
  "guardrail": {"risk_score": 0.0, "action": "ALLOW", "reason": "..."}
}

Java Implementation Reference

/**
 * AI Developer Edition - Java Sample
 * Demonstrates protection pipeline for JVM-based applications
 */
import com.protegrity.devedition.utils.*;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.*;

public class ProtectedAgent {
    
    public String processRequest(String userInput) {
        // Step 1: Configure entity mapping
        Map<String, String> entityMap = new HashMap<>();
        entityMap.put("PERSON", "NAME");
        entityMap.put("SOCIAL_SECURITY_ID", "SSN");
        entityMap.put("CREDIT_CARD", "CCN");
        entityMap.put("EMAIL_ADDRESS", "EMAIL");
        Config.setNamedEntityMap(entityMap);
        Config.setMaskingChar("#");
        Config.setMethod("redact");
        
        // Step 2: Discover sensitive data
        JsonNode discoveryResult = Discover.discover(userInput);
        List<PiiProcessing.EntitySpan> entities = 
            PiiProcessing.collectEntitySpans(discoveryResult, userInput);
        
        // Step 3: Protect sensitive fields
        String safeInput = PiiProcessing.protectData(entities, userInput);
        
        // Step 4: Process safely
        String response = aiModel.generate(safeInput);
        
        // Step 5: Protect output
        JsonNode outputResult = Discover.discover(response);
        List<PiiProcessing.EntitySpan> outputEntities = 
            PiiProcessing.collectEntitySpans(outputResult, response);
        return PiiProcessing.redactData(outputEntities, response);
    }
}