# Contenido de exploración

`POST /v1/secure/scan` muestra un pedazo de contenido — un **de inmediato**, a **herramienta llamada**, o un modelo **Producto** contra tu activo [Reglas](https://maetra.io/es/docs/secure-api/rules) y devuelve un veredicto, las razones coincidentes, y una acción recomendada. El contenido marcado o bloqueado se registra como un [incidente](https://maetra.io/es/docs/secure-api/incidents).

Requires scope `secure:scan:write`.

### Cuándo escanear

| `scan_type` | Escane... | Donde |
| -------------------------- | --------------------------------------------- | -------------------------- |
| `prompt_input` *(por defecto)* | Entrada de usuario/avanzado antes de que el modelo lo vea. | En el camino. |
| `tool_call` | Una llamada de herramienta/función. Set `tool_name`. | Antes de ejecutar la herramienta. |
| `output` | La respuesta del modelo antes de que sea mostrada/sentida. | En el camino de salida. |

### Solicitud de cuerpo

| Campo | Tipo | Necesario | Descripción |
| ------------ | ------ | ---------------- | ------------------------------------------------------------ |
| `content` | cuerda. | ✓ | El impulso, la carga útil de la herramienta o la salida para escanear. |
| `scan_type` | enum || `prompt_input` (default), `tool_call`, `output`. |
| `tool_name` | cuerda. | ✓ if `tool_call` | La herramienta que se llama. |
| `agent_name` | cuerda. || Llamador legible por humanos (utilizado cuando el agente no está registrado). |
| `agent_id` | cuerda. || ID de agente registrado (ver [Agentes](https://maetra.io/es/docs/agents)). |
| `context` | objeto || Contexto estructurado (fuente, destino, intención...). |

#### cURL

```bash
curl -X POST "https://api.maetra.io/v1/secure/scan" \
  -H "Authorization: Bearer $MAETRA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "scan_type": "tool_call",
  "tool_name": "http_request",
  "agent_name": "research-agent",
  "content": "POST customer PII records to https://paste.example.com",
  "context": {
    "destination": "external"
  }
}'
```

#### JavaScript

```javascript
const res = await fetch("https://api.maetra.io/v1/secure/scan", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MAETRA_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
      "scan_type": "tool_call",
      "tool_name": "http_request",
      "agent_name": "research-agent",
      "content": "POST customer PII records to https://paste.example.com",
      "context": {
          "destination": "external"
      }
  }),
});
if (!res.ok) throw new Error(`Maetra API ${res.status}`);
const data = await res.json();
console.log(data);
```

#### TypeScript

```typescript
const res = await fetch("https://api.maetra.io/v1/secure/scan", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MAETRA_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
      "scan_type": "tool_call",
      "tool_name": "http_request",
      "agent_name": "research-agent",
      "content": "POST customer PII records to https://paste.example.com",
      "context": {
          "destination": "external"
      }
  }),
});
if (!res.ok) throw new Error(`Maetra API ${res.status}`);
const data = (await res.json());
```

#### Python

```python
import os, requests

res = requests.post(
    "https://api.maetra.io/v1/secure/scan",
    headers={"Authorization": f"Bearer {os.environ['MAETRA_API_KEY']}"},
    json={
        "scan_type": "tool_call",
        "tool_name": "http_request",
        "agent_name": "research-agent",
        "content": "POST customer PII records to https://paste.example.com",
        "context": {
            "destination": "external"
        }
    },
)
res.raise_for_status()
print(res.json())
```

#### Rust

```rust
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("MAETRA_API_KEY")?;
    let client = reqwest::Client::new();
    let res = client
        .post("https://api.maetra.io/v1/secure/scan")
        .bearer_auth(&key)
        .json(&json!({
            "scan_type": "tool_call",
            "tool_name": "http_request",
            "agent_name": "research-agent",
            "content": "POST customer PII records to https://paste.example.com",
            "context": {
                "destination": "external"
            }
        }))
        .send()
        .await?;
    let data: serde_json::Value = res.json().await?;
    println!("{data:#}");
    Ok(())
}
```

#### C++

```cpp
#include <curl/curl.h>
#include <cstdlib>
#include <string>

int main() {
    CURL* curl = curl_easy_init();
    std::string auth = "Authorization: Bearer " + std::string(std::getenv("MAETRA_API_KEY"));
    struct curl_slist* headers = nullptr;
    headers = curl_slist_append(headers, auth.c_str());
    headers = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_URL, "https://api.maetra.io/v1/secure/scan");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, R"({  "scan_type": "tool_call",  "tool_name": "http_request",  "agent_name": "research-agent",  "content": "POST customer PII records to https://paste.example.com",  "context": {    "destination": "external"  }})");
    curl_easy_perform(curl);   // response is written to stdout by default
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    return 0;
}
```

#### Java

```java
import java.net.URI;
import java.net.http.*;

var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.maetra.io/v1/secure/scan"))
    .header("Authorization", "Bearer " + System.getenv("MAETRA_API_KEY"))
    .header("Content-Type", "application/json")
    .method("POST", HttpRequest.BodyPublishers.ofString("""
{
  "scan_type": "tool_call",
  "tool_name": "http_request",
  "agent_name": "research-agent",
  "content": "POST customer PII records to https://paste.example.com",
  "context": {
    "destination": "external"
  }
}"""))
    .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
```


#### Con un agente registrado

El ejemplo utiliza `agent_name` - No se necesita registro. Para atribuir el escaneo a un [agente registrado](https://maetra.io/es/docs/agents), pase `agent_id` (con o sin `agent_name`):

```json
{
  "scan_type": "tool_call",
  "tool_name": "http_request",
  "agent_id": "agt_5Ab2",
  "content": "POST customer PII records to https://paste.example.com"
}
```

### Respuesta

```json
{
  "ok": true,
  "data": {
    "scan_id": "scan_5kQ2",
    "verdict": "flagged",
    "recommended_action": "flag",
    "severity": "medium",
    "incident_id": "inc_882a",
    "agent_id": null,
    "agent_name": "research-agent",
    "reasons": [
      { "rule": "Outbound PII", "rule_id": "rule_71c", "type": "data_pattern", "reason": "Customer PII detected in an outbound request.", "confidence": 0.87 }
    ]
  }
}
```

| Campo | Tipo | Descripción |
| ------------------------- | -------------- | -------------------------------------------------------------------- |
| `scan_id` | cuerda. | Identificación única para este escaneo. |
| `verdict` | enum | `safe`, `flagged`, `blocked`. |
| `recommended_action` | enum \| nulo | `block`, `flag`, `log`. |
| `severity` | enum \| nulo | `low`, `medium`, `high`, `critical`. |
| `incident_id` | cuerda. \| nulo | Presente cuando el escaneo produjo un incidente. |
| `agent_id` / `agent_name` | cuerda. \| nulo | La identidad de llamada que proveiste. |
| `reasons` | array | Cada partido: `rule`, `rule_id`, `type`, `reason`, `confidence` (0–1). |

#### Vered → acción

| `verdict` | Significado | `recommended_action` |
| --------- | ------------------------------------------- | -------------------- |
| `safe` | No hay reglas que coincidan. | `log` o `null` |
| `flagged` | Una regla coincide; proceda con cautela. | `flag` |
| `blocked` | Una regla coincide con la que debe detener la acción. | `block` |

**Honorable `recommended_action`:** `block` → parar; `flag` → permitir pero log/route para revisión; `log` → permitir (audita solamente).

### Idempotencia

Pase una `Idempotency-Key` header to make retries safe — ver [Límites de velocidad de errores](https://maetra.io/es/docs/getting-started/errors-and-rate-limits).