# Herramientas del agente

> Lista, agrega y quita los servicios y acciones que el agente puede usar con Tool Calling.

Fuente: https://developers.plazbot.com/cli/agent/tools/

### Herramientas (Tool Calling)

Gestiona las herramientas del agente: servicios (llamadas a tus APIs) y acciones (etiquetar, cambiar fase, derivar a un humano, agendar eventos, enviar archivos...). Sin flags abre un menú interactivo; con `--list` o `--json` solo imprime las herramientas configuradas.

```bash
plazbot agent tools <agentId> [options]
```

### Parámetros

| Parámetro | Flag | Requerido | Descripción |
|-----------|------|-----------|-------------|
| `agentId` | (posicional) | Sí | ID del agente, por ejemplo `age_AbcDef123`. |
| Listar | `--list` | No | Imprime los servicios y acciones actuales y termina, sin preguntas. |
| JSON | `--json` | No | Imprime las herramientas como JSON (implica `--list`). Por defecto: `false`. |

### Ejemplos

```bash
# Abrir el menú interactivo
plazbot agent tools age_AbcDef123

# Ver los servicios y acciones configurados
plazbot agent tools age_AbcDef123 --list

# Exportar servicios y acciones en JSON (headers secretos enmascarados)
plazbot agent tools age_AbcDef123 --list --json
```

### Menú interactivo

Primero muestra las herramientas actuales y luego ofrece:

| Opción | Qué hace |
|--------|----------|
| `List services and actions` | Vuelve a mostrar las tablas de servicios y acciones. |
| `Add service (API call)` | Agrega un servicio (ver preguntas abajo). |
| `Add action` | Agrega una acción (ver tipos abajo). |
| `Remove service` / `Remove action` | Permite marcar varios elementos y pide confirmación antes de quitarlos. Deshabilitado si no hay ninguno. |
| `Enable Tool Calling` / `Disable Tool Calling` | Activa o desactiva Tool Calling en el agente. |
| `Exit` | Sale del menú. |

Cada cambio se guarda en el momento. Si agregas una herramienta con Tool Calling desactivado, el CLI pregunta si quieres activarlo; nunca lo activa sin preguntar. Si ya existe un servicio o acción con el mismo nombre, no se guarda nada.

#### Preguntas al agregar un servicio

1. Nombre o intent (por ejemplo `check_order_status`).
2. Cuándo debe usarlo el agente (descripción o palabras clave).
3. Método HTTP: `GET`, `POST`, `PUT`, `PATCH` o `DELETE`.
4. URL del endpoint (http o https; puede incluir `{{campo}}`).
5. Campos requeridos (opcional): datos que el agente debe pedir al usuario antes de llamar. Cada campo tiene nombre, tipo (`string`, `number`, `integer`, `boolean`, `date`, `datetime`, `email`, `phone`), descripción y una pista para la IA.
6. Headers HTTP (opcional), por ejemplo `Authorization`. Deja el nombre vacío para terminar.
7. Plantilla de body JSON (solo `POST`, `PUT` y `PATCH`): un objeto JSON donde `{{campo}}` se reemplaza con los campos requeridos, por ejemplo `{"orderId":"{{orderId}}"}`.
8. Mensaje de respuesta (opcional).

#### Tipos de acción

| Grupo | Tipo | Etiqueta en el CLI | Valor que pide |
|-------|------|--------------------|----------------|
| Contact | `action.asign` | Assign agent | ID de usuario o email del agente |
| Contact | `action.unassign` | Unassign agent | — |
| Contact | `action.stage` | Set stage | ID de la fase |
| Contact | `action.stage.remove` | Remove stage | — |
| Contact | `action.segmentation` | Set segmentation | ID de la segmentación |
| Contact | `action.segmentation.remove` | Remove segmentation | — |
| Contact | `action.tag` | Add tag | ID de la etiqueta |
| Contact | `action.tag.remove` | Remove tag | ID de la etiqueta |
| Contact | `action.solved` | Mark chat as resolved | — |
| Contact | `action.agentShutDown` | Hand off to human agent (turns the AI agent off) | — |
| Contact | `action.secuence` | Assign sequence | ID de la secuencia |
| Contact | `action.worker` | Run worker | ID del worker |
| Events | `action.event.add` | Schedule event | — |
| Events | `action.event.update` | Reschedule event | — |
| Events | `action.event.delete` | Delete event | — |
| Events | `action.event.list` | List events | — |
| Events | `action.event.confirm` | Confirm event | — |
| Events | `action.event.cancel` | Cancel event | — |
| Files | `action.send.image` | Send image | URL de la imagen |
| Files | `action.send.file` | Send file | URL del archivo |

Al agregar una acción se pide: nombre o intent (por ejemplo `talk_to_human`), cuándo usarla, tipo, valor (si el tipo lo requiere), campos requeridos opcionales y mensaje de respuesta.

### Resultado

```text
Tool Calling - Sales Plazbot
────────────────────────────────────────
Status: Enabled

Services - API calls (1)
────────────────────────────────────────
┌────────────────────┬────────┬────────────────────────────────────────────┬──────────┐
│ Intent             │ Method │ Endpoint                                   │ Status   │
├────────────────────┼────────┼────────────────────────────────────────────┼──────────┤
│ check_order_status │ GET    │ https://api.example.com/orders/{{orderId}} │ ● active │
└────────────────────┴────────┴────────────────────────────────────────────┴──────────┘

Actions (1)
────────────────────────────────────────
┌───────────────┬──────────────────────────────────────────────────┬──────────┐
│ Intent        │ Type                                             │ Status   │
├───────────────┼──────────────────────────────────────────────────┼──────────┤
│ talk_to_human │ Hand off to human agent (turns the AI agent off) │ ● active │
└───────────────┴──────────────────────────────────────────────────┴──────────┘
```

Si Tool Calling está desactivado y hay herramientas, se muestra `Tool Calling is disabled, so the agent will not use these tools.`

### Salida JSON

```json
{
"id": "age_AbcDef123",
"name": "Sales Plazbot",
"useToolCalling": true,
"services": [
  {
    "intent": "check_order_status",
    "reference": "Cuando el cliente pregunta por su pedido",
    "method": "GET",
    "endpoint": "https://api.example.com/orders/{{orderId}}",
    "enabled": true,
    "requiredFields": [{ "name": "orderId", "type": "string" }],
    "headers": { "Authorization": "Bear…x9Zq" }
  }
],
"actions": [
  {
    "intent": "talk_to_human",
    "reference": "Cuando el cliente pide hablar con una persona",
    "enabled": true,
    "actions": [
      { "type": "action.agentShutDown", "label": "Hand off to human agent (turns the AI agent off)", "value": "" }
    ]
  }
]
}
```

Los headers cuyo nombre contiene `auth`, `token`, `key`, `secret`, `password` o `cookie` se enmascaran.

> **Tip:** Para ediciones masivas, exporta el agente con [`plazbot agent export`](https://developers.plazbot.com/cli/agent/export), edita `services` y `actions` en el JSON y aplícalo con [`plazbot agent update`](https://developers.plazbot.com/cli/agent/update).

### Errores comunes

| Mensaje | Causa | Solución |
|---------|-------|----------|
| `The tools menu needs an interactive terminal.` | Sin `--list`/`--json` y sin terminal (CI, pipes). | Usa `plazbot agent tools age_AbcDef123 --list --json`. |
| `A service named "<intent>" already exists. Nothing was saved.` | Ya hay un servicio (o acción) con ese nombre. | Usa otro nombre o quita el existente. |
| `Agent "age_AbcDef123" was not found in workspace ...` | El ID no existe en el workspace activo. | Revisa con `plazbot agent list`. |
| `You are not signed in.` | No hay sesión activa. | Ejecuta [`plazbot login`](https://developers.plazbot.com/cli/login). |
