Skip to main content
Glama

Local Worker MCP

MCP local, agnóstico de cliente. Frontier planifica, delega y revisa. Local ejecuta el trabajo pesado, mecánico y verificable.

El objetivo es reducir el consumo de tokens de las IAs de pago sin enviar el contenido bruto a su contexto.

Codex / Claude / Gemini / Grok
              │
              ▼
       Local Worker MCP
              │
       ┌──────┴───────────────┐
       ▼                      ▼
 Gemma 4 12B QAT          arquivos / PDF
 via Ollama               extração + evidências
       │
       ▼
 resultado compacto e verificável
       │
       ▼
 Frontier revisa

Esto no sustituye a la IA principal y no es un model router. Es delegación real de trabajo.

LOCAL DISPONÍVEL?          NÃO
      │                     │
      ▼                     ▼
   DELEGA                NÃO INSISTE
      │                     │
      ▼                     ▼
   COMPRIME            FRONTIER ASSUME
      │
      ▼
 FRONTIER REVISA

Gemma es una optimización. Jamás puede convertirse en un punto único de fallo.

Principio

Delegar cuando la tarea sea mecánica, repetitiva, verificable o intensiva en contexto: PDF, logs, CSV, código, extracción, clasificación, resumen.

Mantener en frontier: decisiones arquitecturales, seguridad, cambios críticos, juicio subjetivo, requisitos ambiguos.

Si el worker local está offline, la frontier continúa. El MCP devuelve unavailable rápido y recomienda fallback. El cliente puede registrar:

Worker local indisponível; executei diretamente.

No exige intervención del usuario.

Related MCP server: ollama-handoff

Requisitos

  • Python 3.10+

  • Ollama en el mismo PC o en otro de la LAN

  • Un modelo local (recomendado: Gemma 4 12B QAT)

Instalación

git clone https://github.com/CaioAllgayer/Local-Worker-MCP.git
cd Local-Worker-MCP
python -m pip install -e ".[dev]"
copy .env.example .env

Ollama + Gemma

  1. Instale e inicie Ollama.

  2. Descargue el modelo. El nombre no es hardcoded — use el nombre real en su ollama list:

ollama list
ollama pull <nome-real-do-gemma>
  1. Si LOCAL_LLM_MODEL queda vacío, el worker intenta detectar un modelo cuyo nombre contiene gemma. Si no, usa el primer modelo listado.

  2. Pruebe el endpoint:

curl http://127.0.0.1:11434/api/tags
local-worker status
  1. Suba el MCP:

local-worker-mcp

Mismo PC

LOCAL_LLM_PROVIDER=ollama
LOCAL_LLM_BASE_URL=http://127.0.0.1:11434
LOCAL_LLM_MODEL=

local vs lan es detectado por el hostname. 127.0.0.1, localhost y ::1 son locales.

Notebook usando el desktop

El worker no asume localhost. El backend puede estar en otro PC de la LAN.

En el notebook:

LOCAL_LLM_PROVIDER=ollama
LOCAL_LLM_BASE_URL=http://192.168.x.x:11434

Cambie 192.168.x.x por la IP actual del desktop (ipconfig en Windows, ip a en Linux). No hay IP fija en el proyecto.

El comportamiento es el mismo: fail-fast, circuit breaker, cache, compresión.

En el desktop, Ollama necesita aceptar conexiones de la LAN (variable OLLAMA_HOST=0.0.0.0 y firewall liberando el puerto 11434).

OpenAI-compatible

LM Studio, llama.cpp server, vLLM y similares:

LOCAL_LLM_PROVIDER=openai_compatible
LOCAL_LLM_BASE_URL=http://127.0.0.1:1234/v1
LOCAL_LLM_MODEL=...
LOCAL_LLM_API_KEY=

Fail-fast y circuit breaker

Valores predeterminados:

LOCAL_LLM_CONNECT_TIMEOUT_SECONDS=2
LOCAL_LLM_REQUEST_TIMEOUT_SECONDS=45
LOCAL_LLM_MAX_RETRIES=0
LOCAL_LLM_CIRCUIT_BREAKER_FAILURES=2
LOCAL_LLM_CIRCUIT_BREAKER_COOLDOWN_SECONDS=60

Conexión rechazada no entra en retry. Después de N fallos el circuito se abre y las próximas llamadas devuelven unavailable inmediatamente. Tras el cooldown, se permite un intento.

{
  "status": "unavailable",
  "fallback_recommended": true,
  "reason": "Local LLM endpoint unreachable"
}

Herramientas MCP

Herramienta

Función

local_status

provider, endpoint, local/LAN, latencia, modelo, circuit breaker, cache

delegate_task

tarea genérica → JSON compacto

delegate_batch

tareas independientes en paralelo (MAX_PARALLEL_WORKERS=4)

delegate_file

TXT, Markdown, CSV, JSON, código, logs

delegate_pdf

extracción por página, chunking, síntesis jerárquica, evidencias

cache_stats

tamaño, entradas, hits, misses, hit rate, expirados

cache_cleanup

GC ahora (TTL → no reutilizados → LRU)

cache_clear

borra entradas descartables

El contenido bruto del archivo no necesita entrar en el contexto de la IA de pago. El worker lee, comprime y devuelve evidencias verificables (página, línea, fragmento).

Seguridad

Por defecto: SECURITY_MODE=READ_ONLY, ENABLE_SHELL=false.

SECURITY_MODE=READ_ONLY
ALLOWED_PATHS=C:\Projects,D:\Research
ENABLE_SHELL=false
  • READ_ONLY — solo lectura en los paths autorizados; escritura y shell bloqueados

  • WORKSPACE_WRITE — lectura/escritura en los paths autorizados; shell solo si ENABLE_SHELL=true

  • FULL_LOCAL — más permisivo; aún bloquea comandos destructivos

Path traversal está bloqueado. rm, del, format etc. son rechazados.

Cache y logs

Cache persistente en ~/.local-worker-mcp/cache, autolimpiante:

CACHE_TTL_DAYS=30
CACHE_MAX_SIZE_GB=10
CACHE_CLEANUP_THRESHOLD_PERCENT=90
CACHE_TARGET_USAGE_PERCENT=80
CACHE_CLEANUP_INTERVAL_HOURS=6

Las entradas son descartables por defecto. persistent=true preserva artefactos importantes.

Los logs rotan y expiran:

LOG_RETENTION_DAYS=14
LOG_MAX_SIZE_MB=250

El log no guarda el contenido completo de los archivos.

Benchmark

local-worker benchmark arquivo.pdf

Salida:

Arquivo: arquivo.pdf
Worker: gemma4:12b-qat
Backend: ollama
Endpoint: LAN/local
Tamanho: ...
Tokens originais estimados: ...
Tokens processados localmente: ...
Resultado para frontier: ...
Compressão: ...
Tempo: ...
Cache: HIT/MISS

Codex

~/.codex/config.toml o el JSON del cliente:

{
  "mcpServers": {
    "local-worker": {
      "command": "local-worker-mcp",
      "env": {
        "LOCAL_LLM_PROVIDER": "ollama",
        "LOCAL_LLM_BASE_URL": "http://127.0.0.1:11434",
        "ALLOWED_PATHS": "C:\\Projects"
      }
    }
  }
}

Ver examples/codex.json.

Claude Code

claude mcp add local-worker --scope user -- local-worker-mcp

O pegue examples/claude_code.json en ~/.claude.json.

En el CLAUDE.md / AGENTS.md del proyecto, enseñe la política:

Tareas mecánicas y lectura de archivos grandes van a delegate_pdf / delegate_file / delegate_task. Si local_status o la herramienta devuelve unavailable, ejecute directamente y siga adelante.

Otros clientes MCP

Cualquier cliente stdio funciona. Ejemplo genérico en examples/generic.json:

{
  "mcpServers": {
    "local-worker": {
      "command": "local-worker-mcp",
      "env": {
        "LOCAL_LLM_PROVIDER": "ollama",
        "LOCAL_LLM_BASE_URL": "http://127.0.0.1:11434"
      }
    }
  }
}

Ejemplos

  • examples/pdf.md — paper / PDF largo

  • examples/code.md — lectura inicial de repositorio

  • examples/logs.md — extracción de errores

Tests

python -m pip install -e ".[dev]"
pytest
ruff check src tests

La suite no depende de Ollama/Gemma reales. Todo está mockeado.

Lo que no entra en este MVP

Automatización de GUI Windows, Playwright, multiagente complejo, RAG vectorial, dashboard, Kubernetes, enrutador ML.

La arquitectura deja espacio para delegate_repo, delegate_git, delegate_browser etc. en la próxima fase.

Licencia

MIT.

Available Tools

8 tools
cache_cleanupA

Run cache garbage collection now (TTL, unused, then LRU).

Inputs: no named parameters.

cache_clearA

Delete disposable cache entries. Persistent artifacts stay unless include_persistent=true.

Inputs: include_persistent.

cache_statsB

Cache size, entry count, hits, misses, hit rate, and expired entries.

Inputs: no named parameters.

delegate_batchB

Run independent local tasks in parallel. One failure does not cancel the batch.

Inputs: tasks (required).

delegate_fileC

Have the local worker read a file (txt/md/csv/json/code/log) without loading it into frontier context.

Inputs: path (required), objective (required), persistent, output_mode, +1 more.

delegate_pdfC

Extract, chunk, and analyze a PDF locally. Returns compact findings with page evidence.

Inputs: path (required), objective (required), persistent, output_mode, +1 more.

delegate_taskC

Delegate a mechanical task to the local worker. Returns compact structured output.

Inputs: objective (required), context, persistent, force_refresh, +2 more.

local_statusA

Check local worker health: provider, endpoint, model, circuit breaker, cache.

Inputs: no named parameters.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 8 tools

    Disambiguation5/5

    Each tool has a clear, distinct purpose: health check, task delegation, batch processing, file reading, PDF analysis, cache statistics, cleanup, and clearing. There is no overlap in functionality, making it easy for an agent to select the appropriate tool.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern (e.g., local_status, delegate_task, cache_stats). The naming is predictable and clear, with verbs like 'delegate' and 'cache' used consistently to indicate the action and domain.

    Tool Count4/5

    With 8 tools, the count is appropriate for the server's purpose of managing a local worker and its cache. The scope is well-defined without being too thin or overly broad.

    Completeness4/5

    The tool surface covers the key operations: health checks, task delegation (including batch and file processing), and cache management (stats, cleanup, clear). A minor gap is the lack of a tool to update or cancel a delegated task, but the core workflows are well supported.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers