# Herramienta de agentes

URL: https://swb.one/es/docs/setup/agent-tool

Una herramienta de agentes ejecuta uno o varios agentes. MCP permite a un agente usar herramientas externas. Una sesión local es una conversación abierta con un agente en un dispositivo emparejado.

## Copiar el prompt de configuración [#setup-prompt]

https://swb.one/prompts/agent-tool.md

````
Read the setup guide at https://swb.one/docs/setup/agent-tool.

Help me connect my agent tool to SwB.
SwB carries messages and stores shared memory.

Ask me which chat apps already reach my agent.
Tell me that my existing chat connections stay the same.
Keep the existing Telegram bot settings.
Keep the existing WeChat ClawBot settings and binding.
Use one active receiver per Telegram bot token.
Run one WeChat ClawBot instance per binding.
Pair my agent with SwB over MCP as a separate connection.
Use MCP Events or a local webhook for notices about new messages.
If I want a direct Telegram connection to SwB, use a separate bot with a new token.
Use the Telegram setup guide at https://swb.one/docs/setup/telegram.

Ask me to choose a name for the agent.
Use up to 40 lowercase letters, digits and dashes.
Start with a letter or digit.
Use my chosen name in place of `my-tool`.
Use a SwB client with owner access for setup.
Call `connect(what="agent-tool", choose={"agent":"my-tool"})`.
Alternatively, run this command in my SwB folder.

```sh
swb connect agent-tool --choose agent=my-tool
```

Keep the existing key if the client already has one.
If SwB returns a pairing code, redeem it in a private terminal within ten minutes.
Use `POST /connect`.
Send `{"code":"<pairing code>"}` in the request body.
Send a `User-Agent` header that names the app on each HTTP request to SwB.
Read the response in memory.
Add a server named `swb` in the client settings.
Use `mcp_url` as the Streamable HTTP address.
Streamable HTTP lets the app call SwB tools over the network.
Use the returned `key` in the `Authorization: Bearer <key>` header.
Store the key in the app's private settings.
Keep credentials private.

## Messages

Use MCP to read messages, send replies and share memory.
Use `wait` or `inbox` to read messages from an open conversation.

## Personal agents

MCP Events sends a notice when a message arrives.
Call `events/list` to see the events SwB offers.
Use `events/subscribe` for `switchboard.message.created` with `mailbox_id` set to my agent name.
Use webhook delivery with a public HTTPS callback address.
A callback is the address that receives notices.
Use a secret with the prefix `whsec_` and a base64 value that decodes to 24 to 64 bytes.
Use the same secret to verify Standard Webhooks signatures at the callback.
Read the message with `get_message`.
Answer with `reply` and the conversation handle.

For a local webhook, pair the companion with the webhook feature.
A webhook receives messages at a web address.
Save the webhook configuration in `~/.config/swb/webhook/my-tool.json`.
Use my chosen agent name in the file name and the `name` field.
Set the required `key_env` field to a `SWB_KEY_<NAME>` variable.
Save my agent's paired SwB key in that variable on the companion device.
The companion uses this key to register the delivery route with SwB.
Use a loopback address or an address on a private or shared network.
A loopback address reaches the same device.
A shared address is in the `100.64.0.0/10` range.
Use a separate receiver secret to sign messages or send a bearer token.
Give the receiver and the companion the same receiver secret.
On the companion device, save it in the variable named in `secret_env`.
For `standard-webhooks`, use the same secret format as for MCP Events.
For a receiver that expects a bearer token, set `auth` to `bearer`.
For bearer tokens, use an HTTP loopback address or an HTTPS address.

```sh
swb companion connect https://swb.example.com --cap webhook
```

```json
{"name":"my-tool","url":"http://127.0.0.1:8644/webhooks/swb","auth":"standard-webhooks","key_env":"SWB_KEY_MY_TOOL","secret_env":"SWB_WEBHOOK_MY_TOOL"}
```

Use the handle from the webhook to answer with `reply`.
Call `inbox` when the agent starts.
The mailbox keeps messages if webhook delivery fails.
Use one delivery method per mailbox.

## Status hooks

Use a status hook if the tool can run a command when a session changes.
Use the same agent name in the command and in MCP.
Pair the device with a companion if I want to use status hooks or a driver.
A companion is a SwB program that connects this device to my SwB server.
Install the `swb` command with `pipx install swb.one`.
Use `companion_code` from the owner client.
Enter the code at the companion's hidden prompt.
Replace the example address with my SwB address.
Add one option for each feature I use.

```sh
swb companion connect https://swb.example.com --cap hooks --cap ade
```

Send one JSON object to `swb hook <name>` on standard input.
Use the session ID from the tool.
Use the folder and label from the session.
Set `event` to `start`, `working`, `blocked`, `idle`, `done` or `ended`.
Include `text` for the answer on a `done` event.

```json
{"event":"done","session":"session-1","name":"My session","dir":"/path/to/project","text":"Test complete"}
```

If a plugin can deliver messages to the session, read wakes from `swb hook <name> --wakes <session>`.
A wake is a message for an open session.
Read one JSON object per line.
Use the tool's supported interface to deliver the `text` to the session.

## CLI session driver

Use a driver if the tool has commands to list and message open sessions.
A driver is a file that maps SwB operations to commands from the tool.
Use Linux or macOS for a custom driver.
Save the driver as a JSON file in `~/.config/swb/ade/`.
Use `$XDG_CONFIG_HOME/swb/ade/` if that environment variable is set.
The account that runs the companion must own the folder and file.
Set `name` to the same agent name.
Set `available`, `list` and `send` to the tool's commands.
Use `argv` to list each command and its arguments separately.
Use JSON output for the session list and reply.
Map the session ID, label, folder and state from the list response.
In `send`, use `{session}` as a separate argument for the session ID.
Use `"stdin": "text"` or put `{text}` immediately after a separate `--` argument.
Use `check` to confirm a session is idle before sending.
Use `wait` and `read` when the tool returns its reply from a separate command.
Use only the tool's documented commands.

Use this example for the structure.
Replace the example commands and JSON fields with those of my tool.

```json
{
  "name": "my-tool",
  "available": {"argv": ["my-tool", "status", "--json"]},
  "list": {
    "argv": ["my-tool", "sessions", "--json"],
    "sessions": "sessions",
    "id": "id",
    "name": "label",
    "dir": "folder",
    "state": "status",
    "states": {"ready": "idle", "running": "working", "approval": "blocked"}
  },
  "check": {
    "argv": ["my-tool", "sessions", "show", "{session}", "--json"],
    "expect": {"id": "{session}", "status": "ready"}
  },
  "send": {
    "argv": ["my-tool", "sessions", "send", "{session}", "--json", "--", "{text}"],
    "reply": "answer"
  }
}
```

Replace `my-tool` with my agent name in the file name.
Set these permissions for new and existing manifests before you call `targets`.
The folder needs mode `0700`. The file needs mode `0600`.

```sh
chmod 00700 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade"
chmod 0600 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade/my-tool.json"
```

Call `targets(block="local")` from the owner client.
Send a test message to the session address returned by `targets`.
Read the answer with `result` and the conversation from `send`.

## Check the connection

Call `inbox` from the paired client.
Call `swb_guide(trigger="setup")` from the same client.
From the owner client, use `send` to send a test message to `agent:my-tool`.
Replace `my-tool` with my chosen name.
Read it with `inbox` from the paired client.
Answer with `reply` and the item's handle.
Read the answer from the owner client with `result` and the conversation from `send`.

Call `memory_summary` from the paired client.
Read the tool's shared notes, such as `AGENTS.md`.
Select facts to share.
Keep credentials and private details on the device.
Use `memory_sync` with `source="agents-md"`.
Give each fact a stable `source_key`.
Use the project slug for project memory.
````

Pega el prompt en un agente de SwB con acceso de propietario. El agente llama a `connect(what="agent-tool", choose={"agent":"example-agent"})` para obtener los ajustes. Empieza el nombre con una letra minúscula o un dígito. Usa hasta 40 caracteres entre minúsculas, dígitos y guiones. SwB identifica al agente con ese nombre.

Usa el código de emparejamiento para [obtener la clave del agente](/es/docs/setup/mcp-client#obtener-la-clave). Esto permite a SwB entregar tareas locales a ese agente. Guarda la clave en los ajustes privados.

<Tabs items={['MCP', 'Sesión local']}>
<Tab value="MCP">
Añade SwB a tu herramienta con los ajustes que recibas y la clave del agente.

Envía un mensaje de prueba al agente por su nombre. Pídele que lo lea con `inbox` y que responda con `reply`. El agente puede usar la memoria que compartas.
</Tab>
<Tab value="Sesión local">
Usa un [archivo de controlador](#driver-manifest) si la herramienta ofrece comandos para listar sesiones y enviarles tareas. Usa [hooks de estado](#status-hooks) si la herramienta puede ejecutar un comando al cambiar de estado.

Introduce el código de un solo uso al emparejar el dispositivo. Pide al agente con acceso de propietario que llame a `targets(block="local")`. Envía un mensaje de prueba a una dirección de sesión completa del resultado. Lee la respuesta con `result`.
</Tab>
</Tabs>

## Agentes personales [#personal-agents]

MCP Events avisa cuando llega un mensaje. Una dirección de retorno recibe los avisos.

Consulta los eventos disponibles con `events/list`. Suscríbete a `switchboard.message.created` con `events/subscribe`. Pon el nombre del agente emparejado en `mailbox_id`.

Usa la entrega por webhook con una dirección HTTPS pública de retorno. Usa un secreto con el prefijo `whsec_` y un valor base64. El valor debe dar entre 24 y 64 bytes al decodificarlo. Usa el mismo secreto para verificar las firmas de Standard Webhooks en el receptor.

Lee el mensaje con `get_message` y el `message_id` del aviso. Responde con `reply` y el identificador de la conversación.

Usa el [webhook local](/es/docs/companion#local-webhook) si el receptor está en tu dispositivo o en tu red privada.

```sh
swb companion connect https://swb.example.com --cap webhook
```

Usa la clave de SwB del agente emparejado para autorizar la ruta de entrega. Pon su variable `SWB_KEY_<NAME>` en `key_env`. Usa un secreto independiente del receptor para firmar los mensajes o enviar un token Bearer.

Elige un modo de entrega por buzón.

### Conservar las conexiones de chat [#existing-channels]

Dile al agente de configuración qué aplicaciones de chat ya llegan a tu agente.

Conserva la configuración del bot de Telegram. Conserva la configuración y la vinculación de WeChat ClawBot. Usa un receptor activo por cada token de bot de Telegram. Ejecuta una instancia de WeChat ClawBot por cada vinculación.

Empareja tu agente con SwB por MCP en una conexión aparte. Usa MCP Events o el webhook local para avisos de mensajes nuevos. Para conectar Telegram directamente a SwB, [configura un bot aparte](/es/docs/setup/telegram) con un token nuevo.

## Archivo de controlador [#driver-manifest]

Un archivo de controlador indica al companion qué comandos debe ejecutar. Guárdalo en formato JSON en `~/.config/swb/ade/<name>.json`. Si defines `XDG_CONFIG_HOME`, usa la carpeta `swb/ade` dentro de esa ruta.

Usa Linux o macOS para un controlador propio. La cuenta que ejecuta el companion debe ser dueña de la carpeta y del archivo. Sustituye `example-agent` por el nombre de tu agente. Usa el modo `0700` para la carpeta. Usa el modo `0600` para el archivo. Aplica los mismos permisos a los archivos de controlador existentes.

```sh
chmod 00700 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade"
chmod 0600 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade/example-agent.json"
```

Pon el nombre del agente en `name`. En `available`, indica un comando que funcione cuando la herramienta esté lista. En `list`, indica un comando que devuelva las sesiones en JSON. Indica en `sessions` la ruta a la matriz de sesiones. Usa una cadena vacía si la matriz está en el nivel superior. Asocia `id`, `name`, `dir` y `state` con los campos de la sesión. Usa `states` para asociar los estados de la herramienta con los de SwB.

Cada comando usa una matriz `argv`. El primer elemento es el programa ejecutable. Cada elemento que sigue es un argumento. Usa `{session}` en `send` para seleccionar la sesión abierta. Pon `{text}` justo después del argumento literal `--` o envía el texto por la entrada estándar con `"stdin": "text"`.

Usa `check` para confirmar que la sesión puede recibir nuevas tareas. Usa `send.reply` para leer la respuesta del comando de envío. Para un comando de lectura aparte, usa `read` y define su campo `reply`. Usa `wait` si la herramienta ofrece un comando para esperar la respuesta. Consulta los [ejemplos incluidos](https://github.com/ZhehanZhang/SwB/tree/release/1.0/src/switchboard/companion/caps/ade_presets).

[Empareja el dispositivo](/es/docs/companion#emparejar-un-dispositivo) con la función de controlador.

```sh
swb companion connect https://swb.example.com --cap ade
```

## Hooks de estado [#status-hooks]

Un hook ejecuta un comando cuando la herramienta avisa de un cambio. [Empareja el dispositivo](/es/docs/companion#emparejar-un-dispositivo) con la función de hooks.

```sh
swb companion connect https://swb.example.com --cap hooks
```

Usa el nombre del agente emparejado en `swb hook <name>`. Pasa un objeto JSON por la entrada estándar. Usa el mismo ID de sesión en todos los eventos de esa sesión.

```json
{"event":"start","session":"example-session","name":"Example session","dir":"/path/to/workspace"}
```

Usa `start`, `working`, `blocked`, `idle`, `done` o `ended` como evento. Incluye la respuesta en `text` en el evento `done`.

Ejecuta `swb hook <name> --wakes <session>` para leer las tareas de esa sesión. Cada línea contiene un objeto JSON con `text` y `conversation`. Pasa el texto a la sesión abierta mediante la interfaz de la herramienta. SwB devuelve la respuesta al remitente.
