Compra Ágil MCP Server
The Compra Ágil MCP Server provides AI agents with comprehensive tools to search, analyze, monitor, audit, and interact with Chilean government procurement processes via Mercado Público.
Search & Monitoring
Search procurement processes by keywords, codes, status, region (1–16), and date ranges, with smart local filters to include/exclude specific terms
Track newly created or modified processes in real time (up to 24 hours)
Rank active opportunities using a weighted "Hot Score" based on competition, available budget, and time remaining (
radar_oportunidades_calientes)
Detail & Order Management
Retrieve full details of a procurement process: items, quotes, budget, delivery terms, and sustainability flags
Verify Purchase Order (OC) issuance and retrieve full order breakdowns (amounts, taxes, buyer, awarded supplier, product list)
Document Handling
Generate public download links for attached documents (specs, bases, annexes)
Download and extract text from PDF attachments, with optional keyword search
Search and read local guides, manuals, and regulations stored in the
docs/folder
Intelligence & Analytics
Recommend competitive winning prices by analyzing historical closed/awarded processes (adjusted to the 40th percentile)
Audit "deserted" (no-bid) processes to identify failure reasons by comparing with successful similar ones
Auto-generate structured JSON quotation drafts with Chilean VAT (19%) calculations and a formal cover letter
System & Resources
Monitor API rate limiting stats and daily quota consumption
Access regional catalogs, API status definitions, and a ChileCompra domain glossary
Use guided prompt templates to find competitor-free opportunities or analyze price competition across bidders
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Compra Ágil MCP Servershow high-value bids with no bidders"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP Server: Compra Ágil v2 — Mercado Público de Chile 🇨🇱
Servidor MCP (Model Context Protocol) desarrollado en TypeScript que envuelve e integra de forma avanzada la API REST de Compra Ágil v2 y la API de Órdenes de Compra (OC) de Mercado Público. Permite a cualquier IA, agente autónomo o cliente compatible interrogar, filtrar, auditar y prospectar procesos de compra estatal del gobierno de Chile.
El proyecto está diseñado bajo una arquitectura modular y cuenta con tres modos de operación:
Servidor Interactivo MCP: Comunicación bidireccional vía Stdio para integrarse directamente con el chat y herramientas de tu IDE o cliente (Cursor, Claude Desktop, Windsurf, etc.).
Daemon de Alertas en Segundo Plano: Servicio de consulta incremental autónomo que rastrea procesos de alto valor con 0 oferentes y guarda alertas automatizadas en un registro local.
Generador de Informes: Produce documentos imprimibles autocontenidos en formatos Carta, Oficio y A4.
📌 Antes de usarlo en decisiones de negocio, lee Limitaciones conocidas de la API. La documentación oficial de ChileCompra difiere del comportamiento real en puntos importantes — este servidor implementa lo que la API hace, no lo que promete.
📋 Tabla de Contenidos
Related MCP server: MCP Mercado Público
🔍 ¿Qué es Compra Ágil?
Compra Ágil es el mecanismo de adquisición simplificado y directo del Estado de Chile para montos inferiores a 100 UTM. Permite a los organismos públicos convocar de forma abierta a cotizaciones rápidas a través de Mercado Público, promoviendo la participación de Empresas de Menor Tamaño (EMT).
🎯 ¿A quién está dirigido?
Este servidor MCP maneja datos públicos de la API de Compra Ágil de Mercado Público, siendo de alto valor tanto para compradores del Estado como para proveedores privados:
🏛️ Para Compradores Públicos (Organismos del Estado)
Estudios de Mercado: Analiza los precios que el mercado cotizó en procesos similares antes de publicar una nueva adquisición.
Auditoría de Procesos Desiertos: Entiende por qué una convocatoria no recibió ofertas válidas, cruzando presupuesto y plazo contra el comportamiento del mercado.
Informes Imprimibles: Genera reportes profesionales en formato Carta, Oficio o A4 listos para presentar.
💼 Para Proveedores (Empresas y Pymes)
Inteligencia de Precios: Analiza a cuánto está cotizando la competencia en procesos del mismo rubro para posicionar tu oferta.
Prospectar Oportunidades: Monitorea llamados activos sin oferentes con un ranking ponderado (Hot Score) y filtros locales.
Alertas Automatizadas: El Daemon en segundo plano notifica oportunidades que coincidan con tu presupuesto mínimo y rubro.
⚠️ Importante: la API de Mercado Público no publica qué oferta ganó. Todo el análisis de precios se basa en cotizaciones presentadas, no en adjudicaciones. Lee Limitaciones conocidas antes de usarlo en decisiones de negocio.
⚡ Características Clave
Modernizado para SDK v1.12+: Carga declarativa y robusta de herramientas, recursos y prompts bajo los nuevos estándares del protocolo.
Carga de Entorno Autónoma: El servidor detecta y carga de forma automática y manual el archivo
.envdel directorio de trabajo al iniciarse, facilitando la conexión en clientes MCP de escritorio sin necesidad de configurar variables de sistema globales.Lector de Documentación Integrado (Recursos): Exposición nativa de guías, normativas y manuales en PDF (dentro de la carpeta
docs/) como recursos del protocolo MCP (compra-agil://documentacion/{filename}). El servidor extrae el texto del PDF de manera local y lo inyecta en el LLM bajo demanda. ⚠ Solo si clonas este repositorio — ver nota sobre la instalación por npm.Filtrado Inteligente Anti-Ruido: Filtros locales en la herramienta
buscar_compras_agiles(palabras_clave_requeridasypalabras_clave_excluidas) para afinar búsquedas amplias de la API y remover ofertas irrelevantes.Paginación Inteligente y Monitoreo Completo: La herramienta de cambios recientes admite navegación de páginas (
numero_pagina), y el demonio de monitoreo periódico procesa de forma recursiva todas las páginas de resultados (client.buscarTodo()) para evitar pérdidas de alertas.Integración del Detalle de OC: Resuelve de forma dinámica el código alfanumérico o ID numérico de las Órdenes de Compra utilizando la API legada de Mercado Público.
Validado contra la API real: El comportamiento documentado por ChileCompra difiere del real en varios puntos. Este servidor implementa lo que la API hace, no lo que promete, y lo documenta en Limitaciones conocidas. Hay tests de regresión que blindan cada hallazgo.
Redacción de credenciales: Todo texto que sale del proceso (logs, errores, respuestas) pasa por un punto único de redacción que borra el ticket. Es relevante porque
sendLoggingMessageenvía los logs al cliente MCP — es decir, al contexto del modelo y a la transcripción.Rate Limiting Local: Throttle proactivo que espacia las solicitudes bajo un máximo por minuto antes de enviarlas, además de reaccionar al error 429 para evitar la inhabilitación temporal del ticket. El estado de cuota persiste entre reinicios, y ante un 429 se honra el header
Retry-Aftercon espera creciente en vez de bloquear hasta el día siguiente: la cuota es un token bucket que se recarga solo (verificado: la API respondió con normalidad 13 min después de un 429).Caché de respuestas: Las consultas repetidas se sirven desde disco sin gastar cuota (15 min para detalles, 5 min para búsquedas). Es lo que hace viable el flujo completo de análisis: repetir
generar_borrador_cotizacionpasó de 6 consultas y 11 s a 0 consultas y 41 ms. El ticket nunca entra en la caché.Informes imprimibles: Genera documentos HTML autocontenidos con diseño de impresión real (
@page, saltos controlados, cabeceras de tabla repetidas) en formatos Carta, Oficio y A4.Logs Nativos en el Protocolo: El servidor declara la capacidad
loggingy emitenotifications/message, así que la actividad se puede seguir y depurar desde la propia interfaz del cliente. El cliente puede ajustar el detalle conlogging/setLevel. Como esos logs llegan al contexto del modelo, todo lo enviado pasa antes por la redacción de credenciales — incluido el endpoint legado de Órdenes de Compra, que lleva el ticket en la URL y se emite comoticket=[REDACTED].Manejo Seguro de Documentos (UUID): Evita errores de tipo
Authentication parameters missingal tratar con archivos adjuntos protegidos de Compra Ágil (UUIDs) redirigiendo al usuario a la ficha pública del buscador (https://buscador.mercadopublico.cl/ficha?code={codigo}) en lugar de entregar enlaces de descarga directa inaccesibles.
📌 Requisitos y Obtención de Credenciales
Para utilizar este servidor MCP necesitas:
Node.js v22+ (se utiliza la API nativa de
fetchy soporte nativo para módulos ESM).Ticket de acceso a la API de Mercado Público de ChileCompra.
🔑 Paso a Paso para obtener tu Ticket de Acceso
El ticket es una credencial de acceso gratuita que identifica tus peticiones ante los servidores de Mercado Público y controla tu cuota diaria de consultas. Sigue este procedimiento oficial para obtenerlo en 2 minutos:
Acceder al portal de la API: Abre tu navegador e ingresa a chilecompra.cl/api/.
Solicitar ticket: Haz clic en el botón destacado «Pide tu ticket».
Autenticación con Clave Única: Acepta los términos y condiciones de uso e inicia sesión con tu Clave Única del Estado de Chile.
Formulario de solicitud: Completa los datos requeridos en el formulario y presiona el botón «Solicitar ticket».
Recepción por correo: Recibirás tu ticket alfanumérico (ej:
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) de forma inmediata en tu casilla de correo electrónico.Consejo: Si no lo visualizas en tu bandeja de entrada en unos minutos, revisa la carpeta de Correo no deseado o Spam.
Una vez que tengas tu ticket alfanumérico copiado, puedes proceder a la instalación.
🚀 Instalación
Opción A: 🤖 Instalación Automatizada mediante tu Agente/Asistente de IA (Recomendado)
Si estás utilizando un asistente o agente de IA en tu editor de código con permisos para ejecutar comandos (como Cursor Composer, Roo Code, Cline, Windsurf Agent o Claude Code), puedes delegar la configuración por completo. Simplemente copia y pega el siguiente prompt en el chat de tu IA:
"Por favor, inicializa y configura este servidor MCP en mi entorno local. Entra a la carpeta
mcp-compra-agil, ejecutanpm installpara instalar dependencias y compila el proyecto connpm run build. Una vez compilado con éxito, registra el servidor MCP en mis ajustes (Cursor, Roo Code, Cline, Continue o Claude Desktop según corresponda) configurando la herramienta para que se ejecute connodeapuntando al archivodist/index.jsy vinculando el tokenCOMPRA_AGIL_TICKET(búscalo en mi archivo.envo pídemelo)."
Opción B: 💻 Instalación Manual clásica
Si prefieres realizar la instalación tú mismo desde la terminal:
# Entrar al proyecto
cd mcp-compra-agil
# Instalar dependencias de desarrollo y producción
npm install
# Compilar el código fuente TypeScript (.ts -> .js en dist/)
npm run buildOpción C: 📦 Ejecución directa vía NPX (Publicación en NPM)
El servidor está configurado para empaquetarse de manera compacta. Si decides publicarlo en el registro de paquetes de NPM (ej: con npm publish), cualquier otra persona podrá ejecutarlo e integrarlo de forma instantánea sin necesidad de descargar el código fuente ni compilarlo manualmente:
Configuración directa en el cliente MCP: Se puede configurar el comando de inicio usando
npx:npx @ssolis-ti/mcp-compra-agilInstalación global en el sistema:
npm install -g @ssolis-ti/mcp-compra-agil # Ejecución directa del binario registrado mcp-compra-agil(Asegúrate de que el usuario defina la variable de entorno
COMPRA_AGIL_TICKETen su cliente o entorno).
⚙️ Configuración de Variables de Entorno
Copia la plantilla y complétala con tus credenciales:
cp .env.example .env # en Windows: copy .env.example .env# Ticket oficial de acceso a la API (Obligatorio)
COMPRA_AGIL_TICKET=tu_ticket_aqui
# URL Base para las llamadas a la API v2 (por defecto api2.mercadopublico.cl)
COMPRA_AGIL_BASE_URL=https://api2.mercadopublico.cl
# Nivel de log: debug | info | warn | error
LOG_LEVEL=info
# --- Parámetros del Daemon de Monitoreo ---
# Intervalo entre búsquedas en minutos (por defecto 1 hora)
MONITOR_INTERVAL_MINUTES=60
# Presupuesto mínimo en CLP para emitir alerta (ej: 5.000.000)
MONITOR_MIN_BUDGET_CLP=5000000
# Palabras clave a buscar separadas por coma
MONITOR_KEYWORDS=software, desarrollo, licencias, plataforma, sistema, soporte, cloud🔐 Manejo seguro del ticket
El ticket es una credencial personal. Aunque el servidor redacta el ticket de todo log, error y respuesta (src/utils/redact.ts), esa es la última línea de defensa, no un permiso para exponerlo:
Guárdalo solo en el
.env— ya está en.gitignore.No lo pegues en chats, issues ni capturas de pantalla.
No lo pases inline en la terminal (
COMPRA_AGIL_TICKET=xxx node ...): queda en el historial del shell y visible en la lista de procesos.Para comprobar que funciona usa la herramienta
verificar_ticket: valida contra la API y solo muestra••••1234.Si trabajas con un agente de IA con acceso a tu disco, considera añadir reglas que le impidan leer el
.env.
🛠️ Uso y Modos de Ejecución
Desarrollo
Para levantar el servidor en caliente observando cambios en el código:
npm run devProducción
Para iniciar el servidor compilado:
npm run build
npm startMonitoreo Autónomo
Para ejecutar el Daemon de alertas en segundo plano (vigila oportunidades sin oferentes y escribe los reportes en alerts.log):
npm run monitorTesting con MCP Inspector
Para probar las herramientas, recursos y prompts en una interfaz gráfica local:
npm run inspect🔌 Integración con Clientes MCP y Agentes
Este servidor se comunica de manera estándar mediante Stdio. A continuación se detallan las instrucciones para integrarlo con los clientes y agentes más comunes del ecosistema:
1. Claude Desktop
Añade el servidor a tu archivo de configuración global editando %APPDATA%\Claude\claude_desktop_config.json (en Windows) o ~/Library/Application Support/Claude/claude_desktop_config.json (en macOS):
{
"mcpServers": {
"compra-agil": {
"command": "node",
"args": ["C:\\ruta\\completa\\mcp-compra-agil\\dist\\index.js"],
"env": {
"COMPRA_AGIL_TICKET": "tu_ticket_de_chilecompra_aqui"
}
}
}
}2. Claude Code (claudecode)
Para registrar el servidor de forma global en Claude Code (el agente CLI de Anthropic), ejecuta el siguiente comando en tu terminal antes de iniciar tu sesión de claude:
claude mcp add compra-agil --env COMPRA_AGIL_TICKET=tu_ticket_de_chilecompra_aqui -- node C:\ruta\completa\mcp-compra-agil\dist\index.jsNota: Si estás en un proyecto local, puedes usar rutas relativas o el comando local.
Para comprobar que se cargó con éxito, inicia una sesión de claude y escribe el comando /mcp o ejecuta claude mcp list en tu terminal.
3. OpenClaw
Para registrar el servidor en OpenClaw (el cliente de terminal y automatización open source), puedes hacerlo de dos formas:
A. Vía CLI (Recomendado)
Ejecuta en tu consola:
openclaw mcp add compra-agil node "C:\\ruta\\completa\\mcp-compra-agil\\dist\\index.js"
openclaw mcp set compra-agil env.COMPRA_AGIL_TICKET "tu_ticket_de_chilecompra_aqui"B. Edición de Archivo de Configuración
Abre tu archivo de configuración de OpenClaw (típicamente localizado en ~/.openclaw/openclaw.json o ~/.openclaw/openclaw.json5) e integra el servidor dentro de la sección "mcpServers":
"mcpServers": {
"compra-agil": {
"command": "node",
"args": ["C:/ruta/completa/mcp-compra-agil/dist/index.js"],
"env": {
"COMPRA_AGIL_TICKET": "tu_ticket_de_chilecompra_aqui"
}
}
}Asegúrate de ajustar los permisos de sandbox de herramientas (tools.sandbox.tools o tools.sandbox.allowlist) en tu config de OpenClaw para permitir la ejecución del comando node.
4. Open-Code / VSCodium / VS Code (Extensiones de Agentes)
Con la extensión Roo Code (Roo Cline / Cline):
Abre los Ajustes de la extensión Roo Code/Cline (
Settings).En la sección MCP Servers Configuration, haz clic en
Edit MCP Settings(esto abrirá el archivocline_mcp_settings.jsonoroo_mcp_settings.json).Añade el siguiente bloque:
{ "mcpServers": { "compra-agil": { "command": "node", "args": ["C:/ruta/completa/mcp-compra-agil/dist/index.js"], "env": { "COMPRA_AGIL_TICKET": "tu_ticket_de_chilecompra_aqui" }, "disabled": false } } }Guarda el archivo y la extensión refrescará automáticamente registrando las nuevas herramientas.
Con la extensión Continue:
Abre tu archivo ~/.continue/config.json y añade la configuración en el bloque "mcpServers":
"mcpServers": [
{
"name": "compra-agil",
"command": "node",
"args": ["C:/ruta/completa/mcp-compra-agil/dist/index.js"],
"env": {
"COMPRA_AGIL_TICKET": "tu_ticket_de_chilecompra_aqui"
}
}
]5. Cursor / Windsurf
Cursor: Dirígete a
Settings>Features>MCP. Haz clic en+ Add New MCP Server. Escribe el nombrecompra-agil, selecciona el tipoStdio, escribe en commandnodey en argsC:/ruta/completa/mcp-compra-agil/dist/index.js. Añade la variableCOMPRA_AGIL_TICKET.Windsurf: Dirígete a la pestaña de MCP en Ajustes e ingresa la misma configuración Stdio.
6. Agentes Personalizados (Node.js/Python SDK)
Si estás construyendo tu propio agente o pipeline automatizado con el SDK oficial de MCP:
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const transport = new StdioClientTransport({
command: "node",
args: ["C:/ruta/completa/mcp-compra-agil/dist/index.js"],
env: {
COMPRA_AGIL_TICKET: "tu_ticket_de_chilecompra_aqui"
}
});
const client = new Client({ name: "mi-agente-cliente", version: "1.0.0" });
await client.connect(transport);
// Listar herramientas y recursos disponibles
const tools = await client.listTools();
const resources = await client.listResources();📖 Catálogo del Servidor
Herramientas Disponibles (Tools)
Nombre de la Herramienta | Descripción de Entrada / Salida |
| Busca procesos utilizando palabras clave (con filtros inteligentes locales), región (1-16), estado y ventana temporal. Parámetros |
| Detalle exhaustivo de una cotización: descripción, ítems y cotizaciones recibidas (confidenciales hasta el estado Cerrada). |
| Sincronización reactiva e incremental por ventana de cambios, con soporte para paginación. Dos modos excluyentes: relativo ( |
| Informa si un proceso tiene OC emitida. No consulta la API por su cuenta (gastaba cuota para responder siempre "no puedo saberlo"): reutiliza el detalle si ya está en caché e indica cómo confirmarlo en la ficha pública — ver Limitaciones. |
| Desglose de productos y facturación de una OC. ⚠ El código debe venir de otra fuente (la OC que te emitieron, un correo, la ficha pública): consulta la API legada de Órdenes de Compra, y la de Compra Ágil no entrega códigos de OC. |
| Cuántas consultas lleva esta instalación en el día UTC y si ya recibió un 429. ⚠ Es un conteo local, no el saldo del ticket: la API no publica cuánta cuota queda. Persiste entre reinicios. |
| Comprueba que el ticket configurado funcione contra la API real sin revelar su valor (solo muestra |
| Contrasta el reloj de esta máquina con la hora oficial de Chile ( |
| Entrega el enlace a la ficha pública del proceso, que es donde el adjunto sí es accesible (en un navegador). El enlace heredado de descarga directa se ofrece advirtiendo que hoy responde 404. |
| ⚠ Hoy no puede descargar los adjuntos de Compra Ágil: el portal dejó de servirlos por enlace directo (404 verificado) y en la ficha el archivo lo genera JavaScript, sin URL que pedir. Para IDs numéricos responde de inmediato con el enlace a la ficha, sin gastar el intento. Los UUID sí se intentan. |
| Busca dentro de los PDF/TXT/MD de |
| Analiza la distribución de precios cotizados por la competencia en procesos similares (mín/p25/mediana/promedio/máx) y sugiere un precio competitivo. Advierte cuando la muestra es demasiado dispersa. ⚠ Analiza precios cotizados, no adjudicados — ver Limitaciones. |
| Analiza por qué una convocatoria quedó desierta, cruzando su presupuesto y plazo contra los precios que el mercado cotizó en procesos del mismo rubro. Reporta el motivo oficial de deserción. |
| Auto-completa propuestas JSON de cotización bajo el esquema oficial, calculando impuestos (19% IVA) y redactando la carta de presentación. Marca explícitamente los campos placeholder. |
| Califica y ordena convocatorias publicadas con un score ponderado (Hot Score, máx 115) de competencia, urgencia de cierre, presupuesto, simplicidad y segundo llamado. Cada resultado trae el desglose de factores y el campo |
| Genera un informe profesional imprimible (HTML autocontenido, diseño A4/Carta/Oficio) y devuelve la ruta del archivo. Ver Informes. |
Recursos Disponibles (Resources)
URI del Recurso | Tipo de Mime | Descripción de Contenido |
|
| Catálogo maestro de mapeo de las 16 regiones administrativas de Chile y sus identificadores numéricos. |
|
| Estados de la API con su comportamiento real verificado: marca cuáles funcionan ( |
|
| Glosario de acrónimos del dominio de ChileCompra para contextualización semántica de la IA. |
|
| Recurso dinámico que resuelve el objeto JSON puro devuelto por la API v2 de una Compra Ágil usando su código único. |
|
| Recurso dinámico que lee y extrae todo el contenido de texto de un PDF/TXT/MD local en la carpeta |
⚠️ La documentación no viaja en el paquete de npm
El paquete publicado incluye únicamente dist/ (declarado en files de package.json), porque las guías en PDF de ChileCompra pesan 12 MB frente a los ~110 KB del servidor. En consecuencia, si lo instalas con npx o npm install en lugar de clonar el repositorio:
Verás 3 recursos en vez de 13:
regiones,estadosyglosario, que están definidos en código. Los diez decompra-agil://documentacion/…no existirán.consultar_documentos_localesinformará que la carpetadocs/está vacía, apuntando a tu directorio de trabajo.
Ninguna de las 15 herramientas que consultan la API se ve afectada: la limitación alcanza solo a la documentación local.
Si quieres esa documentación, tienes dos caminos:
Clonar el repositorio en lugar de instalar desde npm — la carpeta
docs/viene incluida.Poner tus propios documentos: crea una carpeta
docs/en el directorio donde corres el servidor y guarda ahí los PDF, TXT o MD que te interesen. Se expondrán igual como recursos yconsultar_documentos_localeslos buscará. Sirve para tus propias bases técnicas, normativa interna o cualquier material de referencia.
Prompts Disponibles
buscar_oportunidades_proveedor: Plantilla estructurada para guiar a la IA a consultar la región del proveedor, buscar compras publicadas afines y filtrar las 5 mejores ofertas libres de competidores.analizar_competencia: Plantilla de comandos para comparar precios unitarios y totales de los participantes de un proceso finalizado, identificando la brecha económica (spread) entre ofertas. Nota: el motivo de selección no está disponible — la API no publica adjudicaciones.
⚠️ Limitaciones conocidas de la API
Estos hallazgos fueron verificados empíricamente contra el servicio real de Mercado Público (julio 2026, 45 procesos y 52 cotizaciones inspeccionados; re-confirmados en septiembre de 2026 junto a una auditoría de las 15 herramientas). La Guía oficial API Compra Ágil v2 documenta un comportamiento distinto en cada uno de estos puntos.
🔴 La API no publica adjudicaciones
La documentación dice | La API real hace |
| Se acepta, pero devuelve siempre 0 resultados |
| HTTP 400 — no es un filtro válido |
| El sub-objeto no existe; solo |
| No existen; hay |
| Es un número ( |
En la muestra, proveedor_seleccionado valió 0 en el 100 % de las cotizaciones y ningún proceso traía id_orden_compra.
Consecuencia práctica: no es posible saber qué oferta ganó ni obtener precios adjudicados. analizar_precios_mercado se apoya en precios cotizados, que sí son señal de mercado real. verificar_orden_compra ya no consulta la API por su cuenta: gastaba cuota para responder siempre "no puedo saberlo". Reutiliza el detalle si ya está en caché y, en cualquier caso, indica cómo confirmarlo en la ficha pública. Un "sin OC" no prueba que la OC no exista, solo que la API no la publica.
📊 Dónde viven los precios
Solo los procesos desierta publican sus cotizaciones (medido: desierta 5/8 procesos con precios; cerrada 0/8). Por eso el análisis de precios se basa en ellos.
Casi todas esas cotizaciones están declaradas inadmisibles — es justamente lo que dejó desierto al proceso. Se incluyen igualmente en las estadísticas: un precio ofertado es señal de mercado aunque le hayan rechazado el papeleo, y los motivos reales observados son mayoritariamente formales ("no cumple con garantía", "no cuenta con giro acorde"), no de precio. La herramienta reporta los motivos para que puedas ponderarlos.
📎 Los adjuntos no se pueden descargar por programa
La documentación dice | La realidad medida (septiembre 2026) |
| La API devuelve enteros (observados |
Los adjuntos se descargan por su ID | El endpoint heredado responde 404 para todos los adjuntos de Compra Ágil |
— | En la ficha pública el enlace es un |
Las cotizaciones nunca expusieron adjuntos: el array documentos[] existe solo a nivel del proceso, no dentro de proveedores_cotizando[].
Consecuencia práctica: si un llamado dice "ver características en adjunto", esas especificaciones solo se pueden leer abriendo la ficha en un navegador. Las herramientas de documentos llevan ahí directamente en vez de fallar.
⏱️ El 429 no es una cuota diaria: es un balde que se recarga
La guía se contradice a sí misma. Su §4 dice esperar "hasta el inicio del siguiente día calendario", pero su §7 manda esperar el header Retry-After y el glosario define la cuota como un token bucket que "se recarga automáticamente". La medición respalda lo segundo: tras un 429, la API volvió a responder con normalidad 13 minutos después.
Por eso este servidor no bloquea hasta el día siguiente: honra Retry-After y, si no viene, aplica una espera creciente (15 → 30 → 60 → 120 min) que la primera consulta exitosa reinicia. Si recibes un 429, reintenta en unos minutos antes de suponer que agotaste el día.
🐌 Otras restricciones medidas
Las consultas sin filtros devuelven HTTP 500. Hay que enviar al menos un filtro.
tamano_paginamínimo es 10 (valores1y5devuelven HTTP 400).La API es lenta, y empeoró. Medido el 8 de septiembre de 2026 sobre nueve consultas: búsqueda simple 10-12 s, búsqueda con texto 13-17 s, y detalle de un proceso 21-25 s, con HTTP 504 intermitentes en el detalle (1 de cada 3 en esa muestra). La pasarela corta a los ~30 s, así que las consultas grandes fallan enteras. Las herramientas de análisis piden sus detalles en paralelo y la caché evita repetirlos, pero conviene mantener
limite_analisisbajo: cada unidad es una llamada de detalle más, y cada una puede caerse.El segundo llamado es poco frecuente: 6% de los procesos cerrados/desiertos y 0,5% de los activos.
🖨️ Informes imprimibles
generar_informe produce un HTML autocontenido (sin scripts ni recursos externos) con diseño de impresión real, y devuelve la ruta del archivo, no su contenido — un informe pesa decenas de KB y retornarlo al modelo consumiría miles de tokens de contexto.
Formato | Medidas | Uso |
| 216 × 279 mm | Estándar de oficina en Chile |
| 216 × 330 mm | Folio chileno, documentos oficiales |
| 210 × 297 mm | Estándar ISO |
El oficio chileno no equivale al
legalde CSS (216 × 356 mm, US Legal): usarlo agregaría 26 mm de alto. Va declarado con dimensiones explícitas.
Abre el archivo en tu navegador y usa Ctrl+P para exportarlo a PDF, seleccionando el papel correspondiente en el diálogo de impresión.
Para iterar el diseño sin consumir cuota de la API ni requerir ticket:
npx tsx scripts/preview-informe.ts # genera los tres formatos con datos de muestra💡 Ejemplos Prácticos de Interacción
Búsqueda Multi-Filtro:
Usuario: "¿Qué compras ágiles de materiales eléctricos están publicadas en Valparaíso?"
Acción del LLM: Traduce "Valparaíso" al código de región
5usandocompra-agil://regionesy llama abuscar_compras_agilesconq="materiales electricos",estado="publicada",region="5".
Análisis de precios para cotizar:
Usuario: "Quiero cotizar resmas de papel, ¿a qué precio está el mercado?"
Acción del LLM: Llama a
analizar_precios_mercadoconq="resmas papel". Recibe la distribución de precios cotizados y el percentil 25 como referencia competitiva.
Informe de oportunidades:
Usuario: "Genérame un informe en oficio del radar de oportunidades de la RM."
Acción del LLM: Llama a
generar_informecontipo="radar",region="13",formato_papel="oficio". Recibe la ruta del HTML listo para imprimir.
Auditoría de un proceso desierto:
Usuario: "¿Por qué quedó desierta la compra
758-329-COT26?"Acción del LLM: Llama a
auditar_compras_desiertasconcodigo_compra="758-329-COT26". Recibe el motivo oficial, las brechas de presupuesto/plazo frente al mercado y recomendaciones.
📄 Licencia
Este proyecto está bajo la Licencia MIT. Consulta el archivo LICENSE para obtener más información.
Available Tools
13 toolsauditar_compras_desiertasA
Audita un proceso de Compra Ágil que haya quedado "desierto" (sin ofertas) para identificar los motivos (plazo ajustado, presupuesto bajo, requisitos restrictivos) comparándolo con procesos exitosos similares en el mercado. Admite ingresar el código de la compra o un término de búsqueda para encontrar un proceso desierto reciente.
| Name | Required | Description | Default |
|---|---|---|---|
| codigo_compra | No | Código de la Compra Ágil desierta para auditar (ej: "1057539-228-COT26"). Opcional si se especifica "q". | |
| q | No | Término de búsqueda de producto/servicio para encontrar y auditar un proceso desierto reciente (ej: "resmas papel"). Opcional. | |
| limite_analisis | No | Cantidad de procesos históricos exitosos con los que comparar (1-8, default 5) para no agotar la cuota de la API. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must fully convey behavioral traits. It implies a read-only analysis by mentioning comparisons and API quota limits, but it does not explicitly state that no data is modified or require authentication. The parameter 'limite_analisis' hints at API usage, but more direct transparency would improve safety.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise with two sentences, but the second sentence repeats input options already in the schema. It is well-structured and front-loaded with the primary purpose.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description explains the action and inputs but lacks details on the output format (e.g., what kind of report is generated). Without an output schema, the AI agent may not know what to expect, reducing completeness for a tool that likely returns structured analysis.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, so the schema already documents all parameters. The description adds value by explaining that 'codigo_compra' and 'q' are alternative inputs, and that 'limite_analisis' controls API quota usage. This contextual information goes beyond the schema's basic descriptions.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool audits a 'Compra Ágil' that ended with no offers, identifying reasons like tight deadlines, low budget, or restrictive requirements, and compares with successful similar processes. It distinguishes itself from siblings like 'buscar_compras_agiles' and 'obtener_detalle_compra' by focusing on post-hoc analysis.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description indicates when to use the tool (for deserted processes) and how to input data (code or search term). However, it does not explicitly mention when not to use it or provide comparisons with alternative tools, but the context is clear enough for selection.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
buscar_compras_agilesA
Busca procesos de Compra Ágil en Mercado Público de Chile. Permite filtrar por palabras clave, estado del proceso, región geográfica y rango de fechas de publicación. Retorna un listado resumido con código, nombre, estado, presupuesto e institución compradora. Nota: los parámetros 'q' (búsqueda por texto) e 'id' (código exacto) son mutuamente excluyentes. Estados válidos: publicada, cerrada, desierta, cancelada, proveedor_seleccionado. Regiones: códigos del 1 al 16 (ej: 13 = Metropolitana, 5 = Valparaíso).
| Name | Required | Description | Default |
|---|---|---|---|
| q | No | Palabras clave para buscar en el nombre/descripción del proceso. Ej: "materiales electricos". No usar junto con "id". | |
| id | No | Código exacto de una Compra Ágil. Ej: "1057539-228-COT26". No usar junto con "q". | |
| estado | No | Estado(s) del proceso, separados por coma. Valores: publicada, cerrada, desierta, cancelada, proveedor_seleccionado. Ej: "publicada,proveedor_seleccionado". | |
| region | No | Código(s) de región del organismo comprador, separados por coma (1-16). Ej: "13" para Metropolitana, "13,5" para Metropolitana y Valparaíso. | |
| publicado_desde | No | Fecha mínima de publicación en formato ISO-8601. Ej: "2026-01-01T00:00:00Z". | |
| publicado_hasta | No | Fecha máxima de publicación en formato ISO-8601. Ej: "2026-01-31T23:59:59Z". | |
| palabras_clave_requeridas | No | Lista de palabras clave separadas por comas que DEBEN estar presentes en el nombre de la compra (filtro local. Ej: "software,desarrollo"). | |
| palabras_clave_excluidas | No | Lista de palabras clave separadas por comas que NO DEBEN estar en el nombre de la compra (filtro local. Ej: "soporte,licencias"). | |
| ordenar_por | No | Criterio de ordenamiento. "FechaPublicacion" para las más recientes primero, "FechaUltimaModificacion" (default) para las últimas modificadas. | |
| tamano_pagina | No | Resultados por página (10-50, default 15). | |
| numero_pagina | No | Número de página a consultar (comienza en 1). |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description must carry the burden. It states the return format (summary list with code, name, status, budget, institution) but does not disclose whether the tool is read-only, requires authentication, or has rate limits. It adequately describes what it returns, but lacks deeper behavioral context.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is five sentences with no filler. First sentence states purpose, second lists filters, third describes return, fourth is a key note, fifth lists valid values. Front-loaded with purpose and efficient.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given 11 parameters and no output schema, the description covers purpose, filters, return fields, mutual exclusivity, and valid values. It doesn't explain pagination details (covered by schema), but is otherwise complete for a search tool. Could mention ordering default but not critical.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, so baseline is 3. The description adds value beyond schema by noting mutual exclusivity of 'q' and 'id', providing region code examples (e.g., 13 for Metropolitana), and listing valid statuses. This enriches the agent's understanding of parameter relationships.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description starts with 'Busca procesos de Compra Ágil en Mercado Público de Chile.' which clearly states the action (search) and resource (agile purchase processes). It distinguishes from sibling tools by focusing on searching/filtering, while siblings like 'obtener_detalle_compra' retrieve specific details.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Provides clear filters (keywords, status, region, date range) and explicitly notes mutual exclusivity of 'q' and 'id'. Lists valid statuses and region codes. However, it does not explicitly state when to use this tool over alternatives, though it is implied by its search nature.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
consultar_documentos_localesA
Busca y lee información dentro de los manuales, normativas o guías de Compra Ágil almacenados localmente en la carpeta docs/ (soporta formatos .pdf, .txt, .md).
| Name | Required | Description | Default |
|---|---|---|---|
| query | No | Término de búsqueda para filtrar fragmentos del documento (ej: "monto", "criterios"). Si se omite, lista los documentos disponibles. | |
| max_caracteres | No | Cantidad máxima de texto a retornar de cada coincidencia. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must carry the burden. It discloses it searches and reads documents (read-only behavior), but does not mention authentication needs, rate limits, or limitations on file size/encoding. Adequate but minimal.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single, front-loaded sentence that conveys the main purpose, supported formats, and scope. No wasted words.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description lacks details on the return structure (e.g., whether it returns snippets or full paragraphs, how matches are presented). With no output schema, this is a gap. Also, no error handling info. But given the tool's simplicity, it is minimally acceptable.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, baseline 3. The description adds value by clarifying that omitting 'query' lists available documents. For 'max_caracteres', it restates the schema description but adds 'de cada coincidencia' for context.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states it searches and reads information from local manuals, regulations, and guides in the docs/ folder, supporting .pdf, .txt, .md formats. It distinguishes from sibling tools like 'descargar_y_leer_documento' which likely handles external documents.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No explicit guidance on when to use this tool versus alternatives is provided. The description implies local document search, but does not exclude cases where another tool might be better.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
descargar_y_leer_documentoA
Descarga un documento adjunto de Mercado Público (bases técnicas/administrativas) en formato PDF usando su ID, extrae su texto y lo retorna al LLM. Útil para auditar requisitos técnicos de una oferta.
| Name | Required | Description | Default |
|---|---|---|---|
| id_documento | Yes | ID único del documento. Ej: "123456". | |
| query | No | Si se proporciona, busca y retorna solo fragmentos que contengan este término (case-insensitive). | |
| max_caracteres | No | Límite de caracteres a retornar (default 5000) para evitar saturar el contexto de la IA. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so description must cover behavioral traits. It describes download and extraction but omits details on error handling, return format, or caching. The max_caracteres parameter context is a plus.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences that front-load the action and context. Every sentence adds value with no redundant information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given no output schema or annotations, the description is adequate but incomplete. It doesn't specify return format, failure scenarios, or what happens with non-PDF documents. More detail would improve completeness.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema covers 100% of parameters with good descriptions. The tool description adds minimal new semantic beyond the schema, such as the purpose of max_caracteres to avoid context saturation. Baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool downloads, extracts text, and returns it to the LLM for auditing Mercado Público documents. It specifies the source and format, and distinguishes from siblings like 'obtener_enlace_documento' which only gets a link.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description mentions a use case ('auditar requisitos técnicos de una oferta') but provides no explicit guidance on when not to use or mention alternatives. Usage is implied but not fully delineated.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
generar_borrador_cotizacionA
Genera un borrador estructurado en formato JSON para presentar una cotización formal a un llamado de Compra Ágil activa. Calcula automáticamente los valores netos, impuestos (19% IVA de Chile) y montos brutos, sugiriendo un precio unitario de mercado si no se ingresa uno personalizado.
| Name | Required | Description | Default |
|---|---|---|---|
| codigo_compra | Yes | Código de la Compra Ágil activa a cotizar (ej: "1057539-228-COT26"). | |
| rut_proveedor | No | RUT del proveedor que realiza la cotización (ej: "76.123.456-7"). | |
| razon_social | No | Razón social/Nombre de fantasía de la empresa (ej: "Mi Pyme SpA"). | |
| precio_unitario_personalizado | No | Precio unitario neto personalizado para aplicar a los ítems. Si se omite, se buscará un precio estimado de mercado. | |
| plazo_entrega_dias | No | Plazo de entrega en días corridos/hábiles. Si se omite, se adopta el sugerido por el comprador o 5 días. | |
| descripcion_propuesta | No | Mensaje comercial o aclaraciones técnicas del proveedor para adjuntar a la propuesta. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. It explains the tool calculates net, tax (19% IVA), gross amounts, and suggests market prices, which is helpful. However, it does not clarify whether the draft is saved temporarily or permanently, if it modifies any state, or what authentication or authorization is required. This leaves notable gaps.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two sentences: first sentence defines purpose, second explains key behaviors. It is front-loaded with the core action and avoids redundancy. However, the second sentence is somewhat dense, packing three clauses. Minor improvement could split it, but overall it is efficient and well-structured.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool has 6 parameters, no output schema, and no annotations, the description covers the essential aspects: what it does, automatic calculations, and fallback behavior. It lacks details on the output structure (JSON format but no shape) and side effects, but these are partially compensated by the schema parameter descriptions. Overall, it is sufficiently complete for an agent to understand the tool's role.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so baseline is 3. The description adds overall context (e.g., automatic calculation, market price fallback) but does not provide additional semantics for individual parameters beyond what the schema already offers. For instance, 'precio_unitario_personalizado' is well-described in the schema, and the description only reiterates its effect. Thus no extra value.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool generates a structured JSON draft for a formal quotation on an active 'Compra Ágil' call. It uses a specific verb ('genera') and resource ('borrador ... para presentar una cotización formal'), and distinguishes itself from siblings like 'buscar_compras_agiles' and 'obtener_detalle_compra' by focusing on quotation creation.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage for quoting on a Compra Ágil by explaining automatic calculations and market price suggestion, but it does not explicitly state when to use this tool versus alternatives, nor does it provide exclusion criteria or prerequisites. The context is clear but guidance on when-not-to-use is missing.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
monitorear_cambios_recientesA
Busca Compras Ágiles que hayan sido creadas o modificadas en los últimos N minutos. Ideal para monitoreo de nuevas oportunidades de negocio y alertas en tiempo real. Internamente convierte los minutos a milisegundos para el parámetro ttl_cambio_ms de la API. Puede combinarse con filtros de estado y región para acotar los resultados.
| Name | Required | Description | Default |
|---|---|---|---|
| minutos | No | Buscar cambios en los últimos N minutos. Ej: 60 = última hora, 1440 = últimas 24 horas. Máximo 1440 (24h). | |
| estado | No | Filtrar por estado(s), separados por coma. Ej: "publicada" para solo oportunidades abiertas. | |
| region | No | Código(s) de región, separados por coma. Ej: "13" para Metropolitana. | |
| tamano_pagina | No | Resultados por página (10-50, default 50). | |
| numero_pagina | No | Número de página a consultar (comienza en 1). |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries full burden. It discloses internal conversion of minutes to milliseconds and hints at pagination via parameters. However, it does not mention rate limits or output format, but overall it adds useful behavioral context.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is three sentences with no wasted words. It is front-loaded with the core functionality, followed by ideal use and an internal detail. Highly concise and well-structured.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool has 5 optional parameters and no output schema. The description explains the purpose and filter combinations but does not describe the output structure (fields returned, pagination behavior). It is adequate but leaves gaps for an agent to fully understand the response.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, giving a baseline of 3. The description adds value by explaining the conversion of 'minutos' to milliseconds and providing usage examples (e.g., '60 = última hora'), beyond the schema's documentation.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the verb 'Busca' (searches) and the resource 'Compras Ágiles' with a specific time filter (creadas o modificadas en los últimos N minutos). It distinguishes itself from siblings like 'buscar_compras_agiles' which likely lacks the time filter.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description says 'Ideal para monitoreo de nuevas oportunidades de negocio y alertas en tiempo real', providing clear use cases. It also mentions combinability with state and region filters, but does not explicitly state when not to use or contrast with alternatives.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
obtener_detalle_compraA
Obtiene el detalle completo de una Compra Ágil específica por su código único. Incluye: descripción del proceso, productos solicitados con cantidades, proveedores que cotizaron con sus montos, presupuesto disponible, dirección y plazo de entrega, estado de la Orden de Compra (si fue emitida), y flags de sostenibilidad (requisitos medioambientales y de impacto social). NOTA: Las cotizaciones detalladas de los proveedores solo se muestran desde el estado "Cerrada" en segundo llamado en adelante.
| Name | Required | Description | Default |
|---|---|---|---|
| codigo | Yes | Código único de la Compra Ágil. Formato: XXXXXX-YYY-COTXX. Ej: "1057539-228-COT26". |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description bears full burden. It discloses a critical behavioral trait: detailed quotes are only shown from the 'Cerrada' state on the second call onward. This adds significant value beyond a simple read operation.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is front-loaded with the core purpose in the first sentence, then lists included details concisely. The behavioral note is appropriately placed. A minor improvement would be bullet formatting for the list.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a detail-retrieval tool with one parameter and no output schema, the description covers all major aspects: process, products, suppliers, budget, delivery, order status, sustainability flags, and a behavioral note. It is comprehensive enough for an agent to understand what the tool returns.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema already describes the 'codigo' parameter with format and example. The description adds 'por su código único' but no additional semantics beyond the schema, consistent with high schema coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the verb 'Obtiene' (gets) and resource 'detalle completo de una Compra Ágil específica', identifying the unique code as identifier. It distinguishes from sibling tools like 'buscar_compras_agiles' (search) and 'obtener_detalle_orden_compra' (purchase order detail).
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage when a specific purchase detail is needed by its code, but provides no explicit guidance on when to use vs. alternatives (e.g., searching vs. detail retrieval) or when not to use the tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
obtener_detalle_orden_compraA
Obtiene el detalle completo de una Orden de Compra (OC) emitida en Mercado Público de Chile. Admite tanto el ID numérico (id_orden_compra) como el código alfanumérico externo. Retorna información sobre montos (neto, impuestos, total), comprador, proveedor adjudicado y el listado de productos/servicios adquiridos.
| Name | Required | Description | Default |
|---|---|---|---|
| codigo_oc | Yes | Código alfanumérico (ej: "1057532-156-AG26") o ID numérico (ej: "54909627") de la Orden de Compra. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so the description carries the full burden. It discloses that the tool returns information about amounts, buyer, supplier, and product list, implying a read-only retrieval. However, it does not explicitly state side effects, permissions, or other behavioral traits.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two sentences, thoroughly informative without unnecessary words. It efficiently conveys the tool's purpose, input, and output, earning its place.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given a simple tool with one parameter, no annotations, and no output schema, the description adequately explains what it returns (amounts, buyer, supplier, line items). It is complete for its complexity level.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has 100% coverage for the single parameter, and the description adds value by explaining that it accepts both numeric ID and alphanumeric code, with an example format (e.g., '1057532-156-AG26'). This goes beyond the schema's description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool retrieves full detail of a purchase order from Chile's Mercado Público, specifying accepted inputs (numeric ID or alphanumeric code) and output fields (amounts, buyer, supplier, line items). This specificity distinguishes it from sibling tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage when you have an order code and need complete details. It does not explicitly state when not to use or provide alternatives, but the context is clear and the input description guides appropriate use.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
obtener_enlace_documentoA
Genera el enlace oficial de descarga pública en Mercado Público para un adjunto (bases, especificaciones o anexos) usando su ID de documento.
| Name | Required | Description | Default |
|---|---|---|---|
| id_documento | Yes | ID único del documento. Ej: "123456" de la lista de documentos de una compra. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so the description carries full burden. It describes the action but does not disclose error handling (e.g., invalid ID), permissions needed, or that it is a read-only operation. For a simple tool, this is adequate but not comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence that front-loads the main action and includes necessary details (Mercado Público, attachment types, document ID). No wasted words, and it earns its place.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the simplicity (1 param, no output schema), the description explains what the tool does but does not clarify the return format (e.g., returns a URL string) or error behavior. It is adequate but missing explicit output details.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, so baseline is 3. The description does not add additional meaning to the parameter beyond what is already in the schema's description. No extra context like validation or format is provided.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the verb (generates), the resource (official public download link), and the context (for attachments in Mercado Público using document ID). It distinguishes itself from siblings like 'descargar_y_leer_documento' which downloads content, not just generating a link.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage when needing a public download link, but does not explicitly state when to use this tool over alternatives like 'descargar_y_leer_documento' or 'consultar_documentos_locales'. No exclusions or prerequisites are mentioned.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
obtener_estadisticas_usoA
Obtiene las estadísticas de uso de la API y el estado actual de la cuota diaria (Rate Limiting). Útil para que el agente supervise cuántos requests quedan disponibles.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must cover behavioral traits. It implies a read-only operation (statistics and quota) but does not explicitly state it is safe or describe side effects. The description is adequate but lacks depth (e.g., authentication needs, exact output structure).
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences: first states core function, second adds practical use case. No unnecessary words, front-loaded, and perfectly concise.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool has no output schema, so the description should clarify what the returned statistics include. It only mentions 'usage statistics' and 'daily quota' vaguely. More detail (e.g., fields like requests limit, used, reset time) would improve completeness. Given no sophistication in schema/annotations, this is a gap.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has no parameters (0 params), so schema description coverage is 100%. Per guidelines, baseline is 4. The description adds no parameter info, which is fine as there are none.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool obtains API usage statistics and daily quota status. The verb 'obtiene' and specific resources 'estadísticas de uso' and 'cuota diaria' exactly match the tool name. It is distinct from siblings, which focus on procurement tasks.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly states it is useful for monitoring remaining requests, providing clear context. However, it does not mention when not to use it or alternative tools, but since no sibling overlaps, this is acceptable.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
radar_oportunidades_calientesA
Escanea, califica y clasifica de forma priorizada los procesos de Compra Ágil activos (publicados). Utiliza una fórmula ponderada (Hot Score) basada en la falta de oferentes, el presupuesto disponible y las horas restantes de cierre para destacar los llamados más convenientes y fáciles de ganar.
| Name | Required | Description | Default |
|---|---|---|---|
| region | No | Código de la región para filtrar (1-16). Ej: "13" para Metropolitana. | |
| q | No | Término de búsqueda opcional para acotar a un rubro o producto específico (ej: "licencias"). | |
| presupuesto_minimo | No | Filtrar solo procesos con presupuesto disponible mayor o igual a este monto en CLP. | |
| limite_resultados | No | Cantidad máxima de oportunidades destacadas a retornar (1-20, default 10). |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries full burden and explains the scoring algorithm (lack of bidders, budget, hours). It discloses it only works on active published processes. It does not mention rate limits, authentication, or error behaviors, but the core behavior is well covered.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two sentences, front-loading the action and then explaining the formula. Every word earns its place with no superfluous content.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given no output schema, the description lacks details on the return format (fields like ID, score, etc.) and ordering. It mentions prioritization but not pagination or error handling. Adequate but incomplete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, so each parameter is documented. The description adds no extra semantics beyond the schema. The baseline is 3, and the description does not enhance parameter understanding.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool scans, scores, and classifies active 'Compra Ágil' processes using a 'Hot Score' formula. It distinguishes itself from siblings like 'buscar_compras_agiles' by emphasizing prioritization and ease of winning.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage for finding convenient and easy-to-win opportunities but does not explicitly state when to use this tool versus alternatives like 'buscar_compras_agiles'. No exclusions or when-not-to-use guidance is provided.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
recomendar_precio_ganadorA
Analiza procesos históricos similares de Compra Ágil que ya fueron cerrados y adjudicados para estimar y sugerir un precio unitario o total óptimo y competitivo para postular. Admite ingresar el código de una compra activa para extraer automáticamente las palabras clave o un término de búsqueda genérico. Nota: Realiza consultas en paralelo acotadas por el rate limiter.
| Name | Required | Description | Default |
|---|---|---|---|
| codigo_compra | No | Código de la Compra Ágil activa para analizar (ej: "1057539-228-COT26"). Opcional si se especifica "q". | |
| q | No | Término de búsqueda de producto/servicio a cotizar (ej: "resmas papel", "soporte computadores"). Opcional si se especifica "codigo_compra". | |
| region | No | Código de la región para acotar el análisis histórico (1-16). Ej: "13" para Metropolitana. | |
| limite_analisis | No | Cantidad máxima de procesos históricos a auditar (1-8, default 5) para no agotar la cuota de la API. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so description must disclose behavior. It mentions parallel queries limited by rate limiter, which is helpful. But it does not state whether the tool is read-only (likely safe), what side effects exist, or any authentication requirements. More details on behavior are missing.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Description is concise, with two short paragraphs. Main purpose is front-loaded. Could be slightly more compact, but no unnecessary sentences. The note about rate limiter is relevant.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description does not explain what the tool returns (output format) and there is no output schema. For a tool with 4 parameters and no required fields, the lack of return value information is a gap. However, the context about using historical data and the rate limiter is complete enough for basic usage.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema covers all 4 parameters with descriptions. The description adds minimal extra meaning beyond the schema: it explains the purpose of the tool but doesn't elaborate on how parameters are used in the analysis. With 100% schema coverage, a baseline of 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Description clearly states the function: analyzing historical closed Compra Ágil processes to recommend an optimal unit or total price for bidding. The verb 'analiza' and resource 'procesos históricos' are specific. It distinguishes from sibling tools like 'auditar_compras_desiertas' (which audits deserted processes) and 'buscar_compras_agiles' (which searches for active processes).
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Description explains when to use: for estimating a competitive price before bidding. It provides input alternatives (codigo_compra or q) and notes the parameter 'limite_analisis' to control API quota. However, it does not explicitly state when not to use or contrast with sibling tools.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
verificar_orden_compraA
Verifica si una Compra Ágil específica ya tiene una Orden de Compra (OC) emitida. IMPORTANTE: El estado "oc_emitida" de la API NO funciona en la práctica. Esta herramienta resuelve esa limitación consultando el detalle del proceso y cruzando con la API de Órdenes de Compra de Mercado Público si existe un id_orden_compra.
| Name | Required | Description | Default |
|---|---|---|---|
| codigo | Yes | Código único de la Compra Ágil a verificar. Formato: XXXXXX-YYY-COTXX. Ej: "1057539-228-COT26". |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Since no annotations are provided, the description carries the full burden. It explains the tool's workaround behavior: consulting process details and cross-referencing with the Órdenes de Compra API. It does not mention permissions or side effects, but the behavior is clearly described for a verification tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences with no redundant information. The key limitation is highlighted using 'IMPORTANTE', making it easy to scan. Every sentence adds value.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the single parameter and no output schema, the description adequately covers the tool's purpose and behavior. It could be improved by specifying the output format (e.g., boolean or OC id), but it is still complete for the tool's complexity.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The only parameter (codigo) is fully described in the schema, but the description adds value by providing the required format with an example (XXXXXX-YYY-COTXX), which helps agents construct correct inputs.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: verifying whether a specific 'Compra Ágil' has an issued purchase order. It includes a specific verb (verifica), resource (Compra Ágil), and output (OC emitida). This distinguishes it from sibling tools like 'obtener_detalle_compra' and 'obtener_detalle_orden_compra'.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly warns that the API's 'oc_emitida' status does not work in practice, advising agents to use this tool instead. While it does not list all alternatives, it provides clear context for when to use this tool over other methods.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
13 tool updates
v1.0.2- First observed
auditar_compras_desiertas - First observed
buscar_compras_agiles - First observed
consultar_documentos_locales - First observed
descargar_y_leer_documento - First observed
generar_borrador_cotizacion - First observed
monitorear_cambios_recientes - First observed
obtener_detalle_compra - First observed
obtener_detalle_orden_compra - First observed
obtener_enlace_documento - First observed
obtener_estadisticas_uso - First observed
radar_oportunidades_calientes - First observed
recomendar_precio_ganador - First observed
verificar_orden_compra
TDQS
Scored across 13 tools
Each tool targets a distinct function: auditing desiertas, searching, document handling, quotation generation, monitoring, details, order verification, and opportunity scoring. No two tools have overlapping purposes, and descriptions clearly differentiate them.
All tool names follow a consistent verb_noun pattern in Spanish (e.g., 'auditar_compras_desiertas', 'buscar_compras_agiles', 'generar_borrador_cotizacion'). The naming is predictable and aids an agent in understanding tool roles.
With 13 tools, the set is well-scoped for the domain of Chilean public procurement (Compra Ágil). Each tool addresses a specific need without redundancy, covering search, detail, document handling, analytics, and recommendations.
The tool surface covers the core lifecycle: searching, obtaining details, auditing, generating quotations, monitoring changes, and verifying orders. Minor gaps exist, such as lack of tools to directly list all orders for a buyer or manage user profiles, but these are not essential for the primary use case.
Maintenance
Related MCP Connectors
Agent-native security, trust, reliability, data and procurement tools for AI workflows.
Chile Government Procurement MCP — Mercado Público / ChileCompra (keyless-ish).
Government tender search for AI agents. UK, EU and US procurement opportunities.
UK public procurement data for AI agents: tenders, contracts, buyer and supplier profiles.
Related MCP Servers
- AlicenseAqualityBmaintenanceExposes French and EU public procurement data (BOAMP + TED) as MCP tools for AI agents, enabling search for tenders, awards, and winner intelligence via typed filters.4141 PyPIMIT
- AlicenseAqualityDmaintenanceAllows AI assistants to query public procurement opportunities, purchase orders, and government entities from Chile's Mercado Público (ChileCompra) API in real time.1210 npm1MIT
- AlicenseNot gradedqualityCmaintenanceEnables access to Chile's government procurement data (Mercado Público / ChileCompra) via MCP, allowing AI agents to query public procurement information.4 npmMIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to query Colombian government procurement data via MCP tools or natural language questions.5 npmMIT