Skip to main content
Back to Guides
Integration12 min read

Integrando Herramientas Externas en TOOLS.md

Guía completa para añadir APIs, CLIs y scripts a tu agente, desde configuración hasta ejemplos prácticos.

## ¿Qué es TOOLS.md? TOOLS.md es el archivo donde documentas todas las herramientas, APIs, CLIs y scripts disponibles para tu agente. Es como el "manual de herramientas" que consulta antes de realizar cualquier tarea técnica. Un agente sin herramientas es como un programador sin IDE: técnicamente puede trabajar, pero será mucho menos eficiente. ## Tipos de Integraciones ### 1. APIs REST/GraphQL #### Configuración Base ```markdown ## GitHub API - **URL Base**: https://api.github.com - **Auth**: Token en Keychain `github_token` - **Rate Limit**: 5000 req/hora (autenticado) - **Docs**: https://docs.github.com/en/rest ### Endpoints Principales - Repos: `GET /user/repos` - Issues: `GET /repos/{owner}/{repo}/issues` - Crear Issue: `POST /repos/{owner}/{repo}/issues` ``` #### Ejemplo de Uso ```bash # Listar repos TOKEN=$(security find-generic-password -a clawdbot -s github_token -w) curl -H "Authorization: Bearer $TOKEN" \ https://api.github.com/user/repos # Crear issue curl -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"title":"Bug found","body":"Description..."}' \ https://api.github.com/repos/user/repo/issues ``` ### 2. CLIs y Comandos #### Docker ```markdown ## Docker - **Check Status**: `docker ps` - **Logs**: `docker logs ` - **Cleanup**: `docker system prune -f` - **Compose**: `docker-compose up -d` ### Comandos Comunes - Build image: `docker build -t name:tag .` - Run container: `docker run -d --name name -p 8080:80 image` - Execute bash: `docker exec -it container_name bash` ``` #### Git ```markdown ## Git Workflow - **Status**: `git status --porcelain` (machine readable) - **Commit**: `git add . && git commit -m "message"` - **Push**: `git push origin main` - **Branches**: `git branch -a` (all branches) ### Automation Scripts - Auto commit: `~/scripts/git-auto-commit.sh` - Release: `~/scripts/create-release.sh v1.0.0` ``` ### 3. Scripts Personalizados #### Estructura Recomendada ``` ~/scripts/ ├── deployment/ │ ├── deploy-app.sh │ └── rollback.sh ├── monitoring/ │ ├── check-health.sh │ └── get-metrics.sh └── utilities/ ├── backup-db.sh └── clean-temp.sh ``` #### Template de Script ```bash #!/bin/bash # Script: deploy-app.sh # Purpose: Deploy application to server # Usage: ./deploy-app.sh set -e # Exit on error set -u # Exit on undefined variable ENV=${1:-staging} VERSION=${2:-latest} echo "Deploying app v$VERSION to $ENV..." # Validation if [[ ! "$ENV" =~ ^(staging|production)$ ]]; then echo "Error: Environment must be staging or production" exit 1 fi # Main deployment logic ssh deploy@server "docker pull app:$VERSION && docker-compose up -d" echo "Deployment completed successfully" ``` ## Ejemplos por Categoría ### Email (Slack, Discord, etc.) ```markdown ## Slack API - **Bot Token**: Keychain `slack_bot_token` - **Send Message**: ```bash curl -X POST https://slack.com/api/chat.postMessage \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"channel":"#general","text":"Hello World"}' ``` - **Upload File**: ```bash curl -F file=@/path/to/file.txt \ -F "initial_comment=File upload" \ -F channels=general \ -H "Authorization: Bearer $TOKEN" \ https://slack.com/api/files.upload ``` ``` ### Cloud Providers ```markdown ## Hetzner Cloud API - **Token**: Keychain `hetzner_token` - **Base URL**: https://api.hetzner.cloud/v1 - **List Servers**: `GET /servers` - **Create Server**: `POST /servers` ### Firewall Management ```bash # Aplicar firewall a servidor SERVER_ID=12345 FIREWALL_ID=10500120 curl -X POST "https://api.hetzner.cloud/v1/firewalls/$FIREWALL_ID/actions/apply_to_resources" \ -H "Authorization: Bearer $TOKEN" \ -d '{"apply_to":[{"type":"server","server":{"id":'$SERVER_ID'}}]}' ``` ### Monitoring y Logs ```markdown ## Monitoring Stack - **Uptime**: `curl -s https://api.uptimerobot.com/v2/getMonitors` - **Logs**: `journalctl -u service-name --since "1 hour ago"` - **Disk**: `df -h` (human readable) - **Memory**: `free -h` - **Processes**: `ps aux --sort=-%cpu | head -10` ### Health Check Script ```bash #!/bin/bash # Quick health check for server echo "=== System Health ===" echo "CPU: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | awk '{print $1}')" echo "Memory: $(free | grep Mem | awk '{printf("%.1f%%", $3/$2 * 100.0)}')" echo "Disk: $(df / | tail -1 | awk '{print $5}')" echo "Load: $(uptime | awk -F'load average:' '{ print $2 }')" ``` ``` ### Database ```markdown ## PostgreSQL - **Connect**: `psql -h localhost -U user -d database` - **Backup**: `pg_dump -h host -U user database > backup.sql` - **Restore**: `psql -h host -U user database < backup.sql` - **Query**: `psql -c "SELECT version();" database` ### Common Queries - Table sizes: `SELECT schemaname,tablename,pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size FROM pg_tables ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;` - Active connections: `SELECT count(*) FROM pg_stat_activity;` ``` ## Gestión de Secretos ### Almacenamiento Seguro ```bash # Añadir secreto security add-generic-password -a clawdbot -s service_name -w "secret_value" -U # Leer secreto TOKEN=$(security find-generic-password -a clawdbot -s service_name -w) # Listar secretos security dump-keychain | grep clawdbot ``` ### Registry de Secretos Mantén un archivo `secrets-registry.json` con metadata (sin valores): ```json { "github_token": { "description": "GitHub personal access token", "scopes": ["repo", "read:user"], "expires": "2025-12-31", "last_used": "2025-02-08" }, "slack_bot_token": { "description": "Slack bot token for #general", "scopes": ["chat:write", "files:write"], "workspace": "company-workspace" } } ``` NUNCA commitees tokens o passwords en TOOLS.md. Solo documenta cómo accederlos desde Keychain. ## Testing de Integraciones ### Script de Validación ```bash #!/bin/bash # test-integrations.sh # Test all external tools and APIs echo "Testing integrations..." # GitHub API echo -n "GitHub API: " if curl -s -H "Authorization: Bearer $(security find-generic-password -a clawdbot -s github_token -w)" \ https://api.github.com/user >/dev/null; then echo "✅ OK" else echo "❌ FAIL" fi # Docker echo -n "Docker: " if docker ps >/dev/null 2>&1; then echo "✅ OK" else echo "❌ FAIL - Docker not running" fi # Database echo -n "Database: " if psql -c "SELECT 1;" database >/dev/null 2>&1; then echo "✅ OK" else echo "❌ FAIL - Cannot connect to DB" fi ``` ## Patterns y Best Practices ### 1. Error Handling ```bash # Siempre verificar códigos de salida if ! command; then echo "Error: Command failed" exit 1 fi # O usar set -e para fallar automáticamente set -e ``` ### 2. Rate Limiting ```bash # Para APIs con rate limiting make_request() { local url=$1 curl -s "$url" sleep 0.1 # 10 requests/second max } ``` ### 3. Retry Logic ```bash retry() { local max_attempts=$1 local attempt=1 shift while [ $attempt -le $max_attempts ]; do if "$@"; then return 0 fi echo "Attempt $attempt failed, retrying..." ((attempt++)) sleep 2 done echo "All attempts failed" return 1 } # Uso: retry 3 curl https://api.example.com ``` ### 4. Logging ```bash # Template de logging log() { local level=$1 shift echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a /tmp/script.log } log INFO "Starting deployment" log ERROR "Deployment failed" ``` ## Checklist de Nueva Integración Antes de añadir una nueva herramienta a TOOLS.md: - [ ] ¿Los secretos están en Keychain, no hardcodeados? - [ ] ¿Hay documentación de la API/comando? - [ ] ¿Incluye ejemplos de uso común? - [ ] ¿Maneja errores gracefully? - [ ] ¿Respeta rate limits si los hay? - [ ] ¿Está incluida en el script de testing? - [ ] ¿Los scripts tienen permisos de ejecución? - [ ] ¿Hay logging para debugging? ## Mantenimiento ### Rotación de Tokens ```bash # Script de rotación (ejemplo GitHub) OLD_TOKEN=$(security find-generic-password -a clawdbot -s github_token -w) echo "Old token: ${OLD_TOKEN:0:8}..." # Generate new token via GitHub API or UI read -p "Enter new token: " NEW_TOKEN # Update keychain security delete-generic-password -a clawdbot -s github_token security add-generic-password -a clawdbot -s github_token -w "$NEW_TOKEN" -U echo "Token updated successfully" ``` ### Health Monitoring Crea un cron job que valide las integraciones regularmente: ```bash # /etc/cron.d/integration-health 0 */6 * * * user /path/to/test-integrations.sh | mail -s "Integration Status" [email protected] ```