Guard

DeepSeek Integration

Integrate AIVory Guard with DeepSeek AI models and coding assistants to add real-time compliance and security scanning to your DeepSeek-powered workflows.

  • Multiple integration options - REST API, MCP server, or custom wrapper
  • Real-time scanning - Validate AI-generated code before deployment
  • Auto-remediation - Let DeepSeek fix detected violations automatically
  • 18+ compliance standards - OWASP, GDPR, HIPAA, PCI-DSS, and more

Prerequisites

Before you begin, ensure you have:

Note DeepSeek Coder models work best for code generation tasks. Make sure you’re using a compatible model version.

Integration Approaches

Choose the integration method that best fits your workflow:

Direct API Integration
Call AIVory Guard’s REST API from your DeepSeek-powered application for maximum control.
MCP Server
Use AIVory Guard’s MCP server if your DeepSeek tool supports Model Context Protocol.
Custom Wrapper
Build a custom integration layer for advanced use cases and workflow automation.

Direct API Integration

The most flexible approach is calling AIVory Guard’s REST API directly from your DeepSeek application.

API Endpoints

Base URL: https://app.aivory.net

Endpoints:
- POST /api/scan          - Scan code for violations
- POST /api/batch-scan    - Batch scan multiple files
- GET  /api/config        - Get compliance configuration
- GET  /api/rules         - List compliance rules
- GET  /api/health        - Health check
Note Use batch scanning when validating multiple files to reduce API calls and improve performance.

Code Examples

Python Example with DeepSeek
import requests
from deepseek import DeepSeek

# Initialize DeepSeek client
deepseek_client = DeepSeek(api_key="your_deepseek_key")

# AIVory Guard configuration
AIVORY_BASE_URL = "https://app.aivory.net"
AIVORY_API_KEY = "your_aivory_api_key"

def generate_and_scan_code(prompt):
    """Generate code with DeepSeek and scan with AIVory Guard"""

    # Generate code with DeepSeek
    response = deepseek_client.chat.completions.create(
        model="deepseek-coder",
        messages=[
            {"role": "system", "content": "You are a coding assistant."},
            {"role": "user", "content": prompt}
        ]
    )

    generated_code = response.choices[0].message.content

    # Scan with AIVory Guard
    scan_result = scan_code(generated_code, language="python")

    return {
        "code": generated_code,
        "scan_result": scan_result
    }

def scan_code(code, language="python", filename="main.py"):
    """Scan code using AIVory Guard API"""
    headers = {
        "Authorization": f"Bearer {AIVORY_API_KEY}",
        "Content-Type": "application/json"
    }

    payload = {
        "code": code,
        "language": language,
        "filename": filename,
        "standards": ["OWASP", "GDPR", "SOC2"]
    }

    response = requests.post(
        f"{AIVORY_BASE_URL}/api/scan",
        headers=headers,
        json=payload,
        timeout=30
    )

    return response.json()

# Usage
result = generate_and_scan_code("Write a secure user authentication function")
print(f"Generated Code:\n{result['code']}")
print(f"\nScan Results:\n{result['scan_result']}")
JavaScript/TypeScript Example
import { DeepSeek } from 'deepseek-sdk';
import fetch from 'node-fetch';

const deepseekClient = new DeepSeek({
  apiKey: process.env.DEEPSEEK_API_KEY
});

const AIVORY_BASE_URL = 'https://app.aivory.net';
const AIVORY_API_KEY = process.env.AIVORY_API_KEY;

async function generateAndScanCode(prompt: string) {
  // Generate code with DeepSeek
  const response = await deepseekClient.chat.completions.create({
    model: 'deepseek-coder',
    messages: [
      { role: 'system', content: 'You are a coding assistant.' },
      { role: 'user', content: prompt }
    ]
  });

  const generatedCode = response.choices[0].message.content;

  // Scan with AIVory Guard
  const scanResult = await scanCode(generatedCode, 'javascript');

  return {
    code: generatedCode,
    scanResult
  };
}

async function scanCode(code: string, language: string, filename: string = 'main.js') {
  const response = await fetch(`${AIVORY_BASE_URL}/api/scan`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${AIVORY_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      code,
      language,
      filename,
      standards: ['OWASP', 'PCI-DSS', 'HIPAA']
    })
  });

  return await response.json();
}

// Usage
const result = await generateAndScanCode('Create a REST API for user management');
console.log('Code:', result.code);
console.log('Scan:', result.scanResult);

MCP Integration

If your DeepSeek tool supports MCP (Model Context Protocol), you can use AIVory Guard’s MCP server directly.

Configuration

Create or edit your MCP configuration file:

{
  "mcpServers": {
    "aivory": {
      "command": "npx",
      "args": ["@aivorynet/guard"],
      "env": {
        "AIVORY_API_KEY": "your_api_key_here"
      }
    }
  }
}
Note The configuration file location depends on your tool. Check your MCP client’s documentation for the correct path.

Building a Secure Coding Agent

Create a complete agent that generates code with DeepSeek and automatically scans and fixes compliance violations.

Complete SecureDeepSeekAgent Example
import os
from deepseek import DeepSeek
import requests

class SecureDeepSeekAgent:
    def __init__(self):
        self.deepseek = DeepSeek(api_key=os.getenv("DEEPSEEK_API_KEY"))
        self.aivory_base = "https://app.aivory.net"
        self.aivory_key = os.getenv("AIVORY_API_KEY")

    def generate_secure_code(self, prompt, language="python"):
        """Generate code and automatically scan for compliance"""

        # Generate code with DeepSeek
        code = self._generate_code(prompt, language)

        # Scan for violations
        scan_result = self._scan_code(code, language)

        # If violations found, ask DeepSeek to fix them
        if scan_result.get("violations"):
            code = self._fix_violations(code, scan_result, language)
            scan_result = self._scan_code(code, language)

        return {
            "code": code,
            "scan_result": scan_result,
            "is_compliant": len(scan_result.get("violations", [])) == 0
        }

    def _generate_code(self, prompt, language):
        """Generate code with DeepSeek"""
        response = self.deepseek.chat.completions.create(
            model="deepseek-coder",
            messages=[
                {
                    "role": "system",
                    "content": f"You are a secure {language} coding assistant. "
                               f"Generate production-ready, secure code."
                },
                {"role": "user", "content": prompt}
            ],
            temperature=0.7
        )
        return response.choices[0].message.content

    def _scan_code(self, code, language):
        """Scan code with AIVory Guard"""
        response = requests.post(
            f"{self.aivory_base}/api/scan",
            headers={"Authorization": f"Bearer {self.aivory_key}"},
            json={
                "code": code,
                "language": language,
                "standards": ["OWASP", "GDPR", "SOC2"]
            },
            timeout=30
        )
        return response.json()

    def _fix_violations(self, code, scan_result, language):
        """Ask DeepSeek to fix violations"""
        violations_summary = "\n".join([
            f"- Line {v['line']}: {v['message']}"
            for v in scan_result.get("violations", [])
        ])

        response = self.deepseek.chat.completions.create(
            model="deepseek-coder",
            messages=[
                {
                    "role": "system",
                    "content": "You are a security expert. Fix the violations."
                },
                {
                    "role": "user",
                    "content": f"Fix these violations in the code:\n\n"
                               f"{violations_summary}\n\n"
                               f"Original code:\n{code}"
                }
            ]
        )
        return response.choices[0].message.content

# Usage
agent = SecureDeepSeekAgent()
result = agent.generate_secure_code(
    "Create a user registration endpoint with JWT authentication",
    language="python"
)

print(f"Code:\n{result['code']}")
print(f"\nCompliant: {result['is_compliant']}")
print(f"Violations: {len(result['scan_result'].get('violations', []))}")
Note The agent automatically re-scans after fixing violations to ensure full compliance. You can add a loop limit to prevent infinite fix cycles.

Best Practices

Iterative Fixing
Automatically re-scan after DeepSeek fixes violations to verify compliance.
Context Preservation
Include scan results in conversation context for better fix suggestions.
Language Detection
Auto-detect programming language from DeepSeek’s output when possible.
Caching
Cache scan results to reduce API calls for identical code blocks.
Error Handling
Gracefully handle both DeepSeek and AIVory API errors.
Async Operations
Use async/await for better performance in production systems.

Error Handling

Error Handling Example
def safe_generate_and_scan(prompt, language="python"):
    try:
        # Generate with DeepSeek
        code = generate_with_deepseek(prompt)

        # Scan with AIVory
        scan_result = scan_code(code, language)

        return {"code": code, "scan_result": scan_result}

    except requests.exceptions.Timeout:
        return {"error": "AIVory scan timeout"}

    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            return {"error": "Invalid AIVory API key"}
        elif e.response.status_code == 429:
            return {"error": "Rate limit exceeded"}
        else:
            return {"error": f"API error: {e.response.status_code}"}

    except Exception as e:
        return {"error": f"Unexpected error: {str(e)}"}
Warning Always implement proper error handling in production. Rate limits and network issues can cause temporary failures.

API Response Format

Example API Response
{
  "status": "completed",
  "violations": [
    {
      "severity": "high",
      "standard": "OWASP",
      "rule": "A02:2021 - Cryptographic Failures",
      "message": "Weak password hashing detected",
      "line": 15,
      "suggestion": "Use bcrypt or Argon2 for password hashing"
    }
  ],
  "summary": {
    "total_violations": 1,
    "critical": 0,
    "high": 1,
    "medium": 0,
    "low": 0
  }
}

Supported Compliance Standards

AIVory Guard checks code against 18+ compliance standards:

OWASP Top 10
Web application security risks
GDPR
EU data protection regulation
HIPAA
Healthcare data protection
PCI-DSS
Payment card security
SOC 2
Service organization controls
ISO 27001
Information security management

See the Configuration Guide for details on enabling specific standards.


Next Steps

Note Need help? Contact support or check the FAQ.