Skip to main content
skill

azure-ai-contentsafety-ts — Claude Code skill for content checks

Use this skill to add Azure AI Content Safety checks to TypeScript projects, including text and image analysis and custom blocked-term lists.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add microsoft/skills --skill azure-ai-contentsafety-ts -a claude-code
Open on GitHub

What azure-ai-contentsafety-ts does

The skill demonstrates the @azure-rest/ai-content-safety REST SDK for checking text and images. Responses include harmful-content categories and severity levels. For text checks, you can also maintain blocklists and inspect matches.

Its examples cover client authentication with an API key or Azure credentials, analysis requests, and blocklist operations such as creating a list, adding entries, listing it, and deleting it. The project needs @azure-rest/ai-content-safety, @azure/identity, and @azure/core-auth, plus CONTENT_SAFETY_ENDPOINT. Key-based authentication also needs CONTENT_SAFETY_KEY. Without the Azure resource endpoint, the client has nowhere to send requests.

What it helps with

  • check text for hate, violence, and self-harm
  • analyze images for harmful-content categories
  • create a blocklist and add prohibited terms
  • find blocklist matches in submitted text
  • compare severity results against an allowed threshold

Example prompts for the agent

  • Add Azure AI Content Safety text analysis to this TypeScript project.
  • Show how to analyze ./image.png and print each category’s severity.
  • Set up my-blocklist and check text for matching entries.

How to install azure-ai-contentsafety-ts

1Skills CLI (Vercel)

npx skills add microsoft/skills --skill azure-ai-contentsafety-ts -a claude-code

2Manually: put the files in place

~/.claude/skills/azure-ai-contentsafety-ts/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/azure-ai-contentsafety-ts/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about azure-ai-contentsafety-ts

How do I install azure-ai-contentsafety-ts in Claude Code?

Run npx skills add microsoft/skills --skill azure-ai-contentsafety-ts -a claude-code. The skill file is at ~/.claude/skills/azure-ai-contentsafety-ts/SKILL.md.

What does azure-ai-contentsafety-ts do?

It guides TypeScript projects through Azure AI Content Safety requests for text and images, plus blocklist management and match checks.

What does azure-ai-contentsafety-ts need to run?

Install @azure-rest/ai-content-safety, @azure/identity, and @azure/core-auth, and set CONTENT_SAFETY_ENDPOINT. Key authentication also requires CONTENT_SAFETY_KEY; production use of DefaultAzureCredential requires AZURE_TOKEN_CREDENTIALS=prod.

Source text

SKILL.md · MIT
---
name: azure-ai-contentsafety-ts
description: Analyze text and images for harmful content using Azure AI Content Safety (@azure-rest/ai-content-safety). Use when moderating user-generated content, detecting hate speech, violence, sexual content, or self-harm, or managing custom blocklists.
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: '@azure-rest/ai-content-safety'
---

# Azure AI Content Safety REST SDK for TypeScript

Analyze text and images for harmful content with customizable blocklists.

## Installation

```bash
npm install @azure-rest/ai-content-safety @azure/identity @azure/core-auth
```

## Environment Variables

```bash
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com
CONTENT_SAFETY_KEY=<api-key>
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication

**Important**: This is a REST client. `ContentSafetyClient` is a **function**, not a class.

### API Key

```typescript
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";

const client = ContentSafetyClient(
  process.env.CONTENT_SAFETY_ENDPOINT!,
  new AzureKeyCredential(process.env.CONTENT_SAFETY_KEY!)
);
```

### DefaultAzureCredential

```typescript
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

const client = ContentSafetyClient(
  process.env.CONTENT_SAFETY_ENDPOINT!,
  credential
);
```

## Analyze Text

```typescript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const result = await client.path("/text:analyze").post({
  body: {
    text: "Text content to analyze",
    categories: ["Hate", "Sexual", "Violence", "SelfHarm"],
    outputType: "FourSeverityLevels"  // or "EightSeverityLevels"
  }
});

if (isUnexpected(result)) {
  throw result.body;
}

for (const analysis of result.body.categoriesAnalysis) {
  console.log(`${analysis.category}: severity ${analysis.severity}`);
}
```

## Analyze Image

### Base64 Content

```typescript
import { readFileSync } from "node:fs";

const imageBuffer = readFileSync("./image.png");
const base64Image = imageBuffer.toString("base64");

const result = await client.path("/image:analyze").post({
  body: {
    image: { content: base64Image }
  }
});

if (isUnexpected(result)) {
  throw result.body;
}

for (const analysis of result.body.categoriesAnalysis) {
  console.log(`${analysis.category}: severity ${analysis.severity}`);
}
```

### Blob URL

```typescript
const result = await client.path("/image:analyze").post({
  body: {
    image: { blobUrl: "https://storage.blob.core.windows.net/container/image.png" }
  }
});
```

## Blocklist Management

### Create Blocklist

```typescript
const result = await client
  .path("/text/blocklists/{blocklistName}", "my-blocklist")
  .patch({
    contentType: "application/merge-patch+json",
    body: {
      description: "Custom blocklist for prohibited terms"
    }
  });

if (isUnexpected(result)) {
  throw result.body;
}

console.log(`Created: ${result.body.blocklistName}`);
```

### Add Items to Blocklist

```typescript
const result = await client
  .path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", "my-blocklist")
  .post({
    body: {
      blocklistItems: [
        { text: "prohibited-term-1", description: "First blocked term" },
        { text: "prohibited-term-2", description: "Second blocked term" }
      ]
    }
  });

if (isUnexpected(result)) {
  throw result.body;
}

for (const item of result.body.blocklistItems ?? []) {
  console.log(`Added: ${item.blocklistItemId}`);
}
```

### Analyze with Blocklist

```typescript
const result = await client.path("/text:analyze").post({
  body: {
    text: "Text that might contain blocked terms",
    blocklistNames: ["my-blocklist"],
    haltOnBlocklistHit: false
  }
});

if (isUnexpected(result)) {
  throw result.body;
}

// Check blocklist matches
if (result.body.blocklistsMatch) {
  for (const match of result.body.blocklistsMatch) {
    console.log(`Blocked: "${match.blocklistItemText}" from ${match.blocklistName}`);
  }
}
```

### List Blocklists

```typescript
const result = await client.path("/text/blocklists").get();

if (isUnexpected(result)) {
  throw result.body;
}

for (const blocklist of result.body.value ?? []) {
  console.log(`${blocklist.blocklistName}: ${blocklist.description}`);
}
```

### Delete Blocklist

```typescript
await client.path("/text/blocklists/{blocklistName}", "my-blocklist").delete();
```

## Harm Categories

| Category | API Term | Description |
|----------|----------|-------------|
| Hate and Fairness | `Hate` | Discriminatory language targeting identity groups |
| Sexual | `Sexual` | Sexual content, nudity, pornography |
| Violence | `Violence` | Physical harm, weapons, terrorism |
| Self-Harm | `SelfHarm` | Self-injury, suicide, eating disorders |

## Severity Levels

| Level | Risk | Recommended Action |
|-------|------|-------------------|
| 0 | Safe | Allow |
| 2 | Low | Review or allow with warning |
| 4 | Medium | Block or require human review |
| 6 | High | Block immediately |

**Output Types**:
- `FourSeverityLevels` (default): Returns 0, 2, 4, 6
- `EightSeverityLevels`: Returns 0-7

## Content Moderation Helper

```typescript
import ContentSafetyClient, { 
  isUnexpected, 
  TextCategoriesAnalysisOutput 
} from "@azure-rest/ai-content-safety";

interface ModerationResult {
  isAllowed: boolean;
  flaggedCategories: string[];
  maxSeverity: number;
  blocklistMatches: string[];
}

async function moderateContent(
  client: ReturnType<typeof ContentSafetyClient>,
  text: string,
  maxAllowedSeverity = 2,
  blocklistNames: string[] = []
): Promise<ModerationResult> {
  const result = await client.path("/text:analyze").post({
    body: { text, blocklistNames, haltOnBlocklistHit: false }
  });

  if (isUnexpected(result)) {
    throw result.body;
  }

  const flaggedCategories = result.body.categoriesAnalysis
    .filter(c => (c.severity ?? 0) > maxAllowedSeverity)
    .map(c => c.category!);

  const maxSeverity = Math.max(
    ...result.body.categoriesAnalysis.map(c => c.severity ?? 0)
  );

  const blocklistMatches = (result.body.blocklistsMatch ?? [])
    .map(m => m.blocklistItemText!);

  return {
    isAllowed: flaggedCategories.length === 0 && blocklistMatches.length === 0,
    flaggedCategories,
    maxSeverity,
    blocklistMatches
  };
}
```

## API Endpoints

| Operation | Method | Path |
|-----------|--------|------|
| Analyze Text | POST | `/text:analyze` |
| Analyze Image | POST | `/image:analyze` |
| Create/Update Blocklist | PATCH | `/text/blocklists/{blocklistName}` |
| List Blocklists | GET | `/text/blocklists` |
| Delete Blocklist | DELETE | `/text/blocklists/{blocklistName}` |
| Add Blocklist Items | POST | `/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems` |
| List Blocklist Items | GET | `/text/blocklists/{blocklistName}/blocklistItems` |
| Remove Blocklist Items | POST | `/text/blocklists/{blocklistName}:removeBlocklistItems` |

## Key Types

```typescript
import ContentSafetyClient, {
  isUnexpected,
  AnalyzeTextParameters,
  AnalyzeImageParameters,
  TextCategoriesAnalysisOutput,
  ImageCategoriesAnalysisOutput,
  TextBlocklist,
  TextBlocklistItem
} from "@azure-rest/ai-content-safety";
```

## Best Practices

1. **Always use isUnexpected()** - Type guard for error handling
2. **Set appropriate thresholds** - Different categories may need different severity thresholds
3. **Use blocklists for domain-specific terms** - Supplement AI detection with custom rules
4. **Log moderation decisions** - Keep audit trail for compliance
5. **Handle edge cases** - Empty text, very long text, unsupported image formats

© Microsoft · MIT · microsoft/skills

Similar skills

All skills for Cloud: AWS, Azure, GCP →

From the same set143

The whole set →
azure-identity-ts A skill that walks the agent through Azure authentication with the @azure/identity library in TypeScript. Useful once DefaultAzureCredential or managed identity shows up in your code. 1installs azure-cosmos-ts A skill covering the Azure Cosmos DB JavaScript/TypeScript SDK: document CRUD, queries, bulk operations. Useful when the agent writes data-access code. 1installs azure-appconfiguration-ts A skill that gets your agent writing TypeScript against Azure App Configuration: settings, feature flags, Key Vault references and dynamic refresh. 1installs azure-ai-projects-ts Tells your coding agent how to use the Azure AI Projects SDK for JavaScript: agents, connections, deployments, datasets, indexes and evaluations. 1installs azure-storage-file-datalake-py This skill guides Python work with Azure Data Lake Storage Gen2, from file-system setup to file and directory operations. Use it when building or updating ADLS Gen2 code. 1installs azure-servicebus-py This skill guides Python work with Azure Service Bus queues, topics, and subscriptions. Use it when adding message-based communication to an application. 1installs azure-monitor-opentelemetry-exporter-py A skill for low-level OpenTelemetry export of traces, metrics and logs to Application Insights from Python. Useful when you run a custom telemetry pipeline. 1installs azure-mgmt-apicenter-py This skill guides Python work with Azure API Center, from API inventory and metadata to versions, environments, and deployments. 1installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor