Skip to main content
Glama

reference-search-mcp

Herramienta de uso personal: búsqueda de imágenes de referencia de dibujo para ilustradores. Los agentes de IA de codificación deben leer primero AGENTS.md.

Un servidor MCP de búsqueda de imágenes de referencia pensado para IA: recibe una consulta en lenguaje natural → la convierte en palabras clave → busca en paralelo en varias fuentes de imágenes → elimina las miniaturas duplicadas → compone un mosaico numerado → el modelo multimodal los selecciona mediante llamadas a herramientas (en lugar de JSON en bruto) → el cliente impulsa la iteración (rondas a, b, c…, con deduplicación entre rondas) → al final descarga la imagen completa por su ID y devuelve la ruta del archivo.

调用方 AI (MCP 客户端)
   │  image_search_start("找适合播客封面的太空插画素材")
   ▼
[reference-search-mcp]                        ┌──────────────────────┐
  ├─ LLM 层 (pi)  NL → 关键词 (submit_keywords 工具)          │ 搜索适配器(并行)    │
  ├─ providers    DDG / Bing / Wikimedia / Openverse / Serper │  ddg ─┐             │
  ├─ 去重         pHash(跨轮 seen 集合)                      │  bing ─┤ 结果合并    │
  ├─ 拼图         sharp 编号拼图 round-a.png(a1..aN)         │  wikimedia ─┘       │
  ├─ 视觉筛选     pi vision 模型看拼图,调用 select_images /   └──────────────────────┘
  │               reject_images / refine_search 工具
  ▼
{ round:"a", gridPath, selectedIds:["a3","a17"], metadata:[...] }
   │  image_search_iterate("不要 a3,多找像 b7 的") → round b(重复图自动剔除)
   │  image_search_collect(session, ["b1","c12"]) → 本地文件路径 + manifest.json

¿Por qué los resultados se entregan con «llamadas a herramientas» y no con un JSON estructurado?

La selección que hace el modelo de filtrado sobre el mosaico se expresa con llamadas a funciones como select_images / reject_images / refine_search:

  • El esquema de parámetros lo valida el propio proveedor del modelo — por lo tanto es JSON válido de forma natural, sin cercos de markdown, ni prosa intercalada, ni claves irreverentes.

  • Expresa varias intenciones de una vez (elegir + rechazar + sugerir la siguiente palabra clave).

  • Si el ejecutor recibe un ID no válido (p. ej., a99), devuelve un error y el modelo lo corrige automáticamente en la siguiente ronda.

  • Es idéntico a la capa externa de MCP: en la capa externa, el modelo solicitante nos utiliza mediante herramientas, y en la capa interna nosotros utilizamos al modelo mediante herramientas.

La capa LLM se apoya en pi (@earendil-works/pi-ai, MIT): unifica varios proveedores de API (Anthropic / OpenAI / DeepSeek / Gemini / 通义 / Kimi / MiniMax…), resolución automática de credenciales, catálogo de modelos integrado, reintentos y utilidades de reparación de JSON. No introduce un framework pesado de agentes — el LLM del servidor es tan solo tres funciones acotadas (parsear palabras clave / interpretar el idioma / filtrar la imagen), y el bucle de iteración real lo impulsa la IA que hace la llamada.

Related MCP server: mcp-universal-crawler

Inicio rápido

Requisito: Node ≥ 22.19.

npm install --ignore-scripts
npm run build

1. Configurar el LLM (credenciales de pi, elige una de las dos)

# 方式 A:环境变量(任意 pi 支持的提供商)
export DEEPSEEK_API_KEY=sk-...          # 文本解析(便宜)
export ANTHROPIC_API_KEY=sk-ant-...     # 视觉筛选
# 或 OPENAI_API_KEY / GEMINI_API_KEY / OPENROUTER_API_KEY ...

# 方式 B:pi 的登录体系(支持订阅制)
npx @earendil-works/pi-coding-agent /login   # 或直接 pi /login

Selección de modelo (opcional):

export PI_TEXT_MODEL=deepseek/deepseek-chat
export PI_VISION_MODEL=anthropic/claude-sonnet-4-5
export PI_THINKING=off            # off|minimal|low|medium|high

Punto de puntosco personalizado compatible con OpenAI (Qwen-VL / GLM-4V / Ollama, etc.):

export PI_CUSTOM_PROVIDER_API=openai-completions
export PI_CUSTOM_PROVIDER_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
export PI_CUSTOM_PROVIDER_MODELS=qwen-vl-max,qwen-turbo
export PI_CUSTOM_PROVIDER_API_KEY=sk-...

Modelo de visión de DeepSeek (deepseek-v4-flash-vision-exp, no está en el catálogo integrado de pi, modelo con punto personalizado):

export DEEPSEEK_API_KEY=sk-...
export PI_TEXT_MODEL=deepseek/deepseek-v4-flash
export PI_VISION_MODEL=deepseek-vision/deepseek-v4-flash-vision-exp
export PI_CUSTOM_PROVIDER_ID=deepseek-vision
export PI_CUSTOM_PROVIDER_API=openai-completions
export PI_CUSTOM_PROVIDER_BASE_URL=https://api.deepseek.com
export PI_CUSTOM_PROVIDER_MODELS=deepseek-v4-flash-vision-exp
export PI_CUSTOM_PROVIDER_API_KEY_ENV=DEEPSEEK_API_KEY

Puede usarse sin credenciales de LLM (modo degradado): cuando llames a start/iterate pasas keywords explícitamente, se omite el análisis y el filtrado automáticos y se devuelven todos los candidatos.

2. Configurar las fuentes de imágenes

export PROVIDERS=ddg,bing,wikimedia          # 默认;并行查询
export OPENVERSE_TOKEN=...                   # 启用 openverse(CC 图库)
export SERPER_API_KEY=...                    # 启用 serper(Google 图搜)
export SAFE_SEARCH=true

3. Conectar el cliente MCP

Claude Code:

{
  "mcpServers": {
    "reference-search": {
      "command": "node",
      "args": ["D:/path/to/reference-search-mcp/dist/index.js"],
      "env": { "DEEPSEEK_API_KEY": "...", "ANTHROPIC_API_KEY": "..." }
    }
  }
}

Cliente stdio propio: node dist/index.js, protocolo MCP estándar; las herramientas devuelven bloques de texto JSON.

Doble modo: este MCP es «capacidad visual externalizada»

La esencia de este MCP es darle ojos a un modelo de solo texto: la búsqueda, el mosaico y la numeración son la parte mecánica; el filtrado visual (mirar el mosaico y elegir los números) es la «capacidad visual externalizada». Que el llamante sea multimodal o no decide si el servidor tiene que mirar por él:

Modo

Apto para el solicitante

Comportamiento del servidor

Interacción

server (FILTER_MODE=server)

modelo de texto plano

parsea keywords en texto + filtro visual

devuelve selectedIds + reasons (informe del modelo de visión)

client (FILTER_MODE=client o filter:false)

modelo multimodal

solo lo mecánico, no llama la API (filter:false)

devolverá ruta del mosaico + candidatos; el modelo mira el mosaico y elige los IDs

auto (por defecto)

cualquiera

si hay modelo visual configurado, filtra; si no, degrada

igual que server / client

collect admite de por sí cualquier ID válido — un llamante multimodal puede ignorar selectedIds y elegir libre por sí mismo. Cada llamada también se puede usar filter: false para anular la configuración global.

Contrato de herramientas

Herramienta

Entrada

Retorno clave

image_search_start

query, content?, criteria?, count?, safe_search?, filter?

session_id, round:"a", grid_path, filtered, selected_ids, metadata(número → título/dominio/licencia/tamaño/URL),keywords_used, warnings`

image_search_iterate

session_id, feedback (puede referirse en texto), keywords?, filter?

siguiente ronda round:"b"…; deduplicación por pHash entre ronda (dedupe_skipped); redefine refine_search` con la LLM

image_search_collect

session_id, ids:["b1","c12"]

files (paths / URL / licencias / dimensiones), manifest_path, failures (por ID)

image_search_status

session_id

elecciones/descacados de cada ronda, keywords actuales, coleccionado

Regla de IDs: letra de ronda + nº de casilla. a3 = ronda 1, casilla 3; b12 = ronda 2, casilla 12. Todas las referencias y colecciones se rigen por esto.

Referencia de configuración

Variable

Por defecto

Descripción

PROVIDERS

ddg ,bing, wikimedia`

Fuentes habilitadas, separadas por comas

OPENVERSE_TOKEN / SERPER_API_KEY

Credenciales opcionales para las fuentes

GRID_COLUMNS / GRID_ROWS

6 / 8

48 celdas por ronda; GRID_CELL_CELL por defecto 256px

SESSION_TTL_MINUTES

120

limpieza automática de sesiones y mosaicos temporales

DATA_DIR / OUT_DIR

temp/./out

directorio de datos y de copias

HTTP_TIMEOUT_MS

15000

tiempo de espera en la recogida

LLM_MAX_TURNS

3

número máximo de turnos bucle de herramientas internas

FILTER_MODE

auto

auto | server | client (ver « Doble modo »)

PI_TEXT_MODEL / PI_VISION_MODEL / PI_THINKING

auto-selección

selección del modelo LLM correspondiente

Sección GXP:

src/
  mcp/        # MCP server(stdio)与 4 个工具注册
  llm/        # pi-ai 之上的工具调用循环:parseKeywords / interpretFeedback / filterGrid
  providers/  # SearchProvider 接口 + ddg/bing/wikimedia/openverse/serper 适配器,并行容错
  grid/       # sharp 拼图构建(编号徽章/占位格)、pHash 去重
  session/    # 会话状态机(轮次 a/b/c、seen 哈希、TTL 清理)
  collect/    # 整图下载(UA/Referer/重试/校验)、manifest 生成
  service.ts  # 编排:search → dedupe → grid → filter → round state

Pruebas y scripts

npm test                              # 34 个测试:单测 + 真实 MCP stdio 集成测试
npm run smoke -- --query "space nebula" --keywords "nebula,art" --collect "a1,a2" [--iterate "更多星球"]
npm run handshake -- --query "cat" --keywords "cat"     # MCP stdio 握手冒烟(先 build)
npx tsx scripts/debug-pi.ts           # 诊断:pi 层工具调用(DeepSeek 文本)
npx tsx scripts/debug-vision.ts       # 诊断:视觉模型对最近一轮拼图的原始响应

Consideraciones

  • Copyright: metadata/manifest transmiten la licencia (incluida por Wikimedia / Openverse); para material comercial, verificación de la autorización de la fuente.

  • Protección anti enlaces directos: algunos sitios (como Etsy) rechazan las descargas de terceros; collect informará por ID; si da 403, puedes abrir la URL directamente en el navegador.

  • Antirrobot: los adaptadores tienen User-Agent, intervalos de petición y retroceso por reintentos; el fallo de una fuente no derrumba el conjunto.

  • Modo degradado: sin credenciales de LLM hay que se explicita keywords y no se filtra automáticamente (devuelve todos los candidatos).

Available Tools

4 tools
image_search_collectDownload the full images for chosen cell idsA

Download the full-resolution images for a list of round-qualified ids (e.g. ['a3', 'b12']) to the output directory. Returns local file paths plus a manifest with source URLs and licenses.

ParametersJSON Schema
NameRequiredDescriptionDefault
idsYes
session_idYes

TDQS

A3.9/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full behavioral burden. It discloses the action (downloads to output directory) and the return format (local paths and manifest with URLs/licenses). It does not mention file overwriting, network requirements, or session validity, but these are minor gaps for a download tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences that are tightly written: the first states the core action, the second states the return value. No filler, and the most important information is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the essential function but omits the purpose of session_id and its relation to the broader search workflow. Without annotations or an output schema, an agent may not know if session_id must come from a prior start/iterate call or whether the output directory is session-scoped. This is incomplete for a multi-step tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description explains 'ids' with an example and meaning (round-qualified ids), but 'session_id' is not explained at all. Since schema description coverage is 0%, the description should have delineated both parameters; it partially compensates but leaves a critical gap on how session_id is used.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb (download), resource (full-resolution images), and target (list of ids) with an example. It clearly distinguishes from siblings (start/iterate/status) which are about session management, not downloading.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by mentioning 'round-qualified ids' and downloading, but it never explicitly says when to use this tool versus siblings or that it should follow a prior step. The workflow relationship to image_search_start/iterate/status is left to inference, with no exclusions or explicit conditions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

image_search_iterateIterate on an existing search sessionA

Give feedback referencing round-qualified ids (e.g. 'keep a3, more like b7, no photos') plus optional explicit keywords. Produces the next round (b, c, ...) with dedup against all previously shown images. The LLM interprets the feedback into keyword additions/removals via refine_search.

ParametersJSON Schema
NameRequiredDescriptionDefault
countNo
filterNofalse = skip the server-side vision filter for this round
criteriaNo
feedbackYesNatural-language feedback; may reference cell ids like a3 / b12
keywordsNoExplicit keyword replacement; skips LLM feedback interpretation
session_idYes
safe_searchNo

TDQS

A3.8/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden. It discloses dedup against previously shown images and that the LLM interprets feedback into keyword changes via refine_search. However, it doesn't mention side effects like session mutation, reversibility, or any potential rate limits. It covers some key behaviors but not all.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences with zero waste. The primary usage is front-loaded, and the key behaviors (dedup, LLM interpretation) are clearly stated. Very efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 7 parameters, no output schema, and no annotations, the description is relatively brief. It covers core mechanics but omits details on several parameters and doesn't describe the return value or any side effects. It's adequate but not fully complete for complex usage.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is only 43%, so the description must compensate for undocumented parameters like count, criteria, safe_search, and session_id. It adds meaning for feedback (referencing cell ids) and keywords (explicit replacement) but does not explain the remaining parameters. The description fails to bridge the coverage gap for those.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: it iterates on an existing search session by taking feedback referencing round-qualified ids, producing the next round with dedup. It distinguishes from siblings by implying it's not for starting a new session (image_search_start) but for refinement, and the title reinforces 'existing'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It gives clear usage instructions: provide feedback with round-qualified ids and optionally explicit keywords. It implies when to use (with an existing session) but does not explicitly mention when not to use or name alternatives. Context from siblings suggests this is for continuation, but the description alone doesn't state exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

image_search_startStart an image search sessionA

Parse a natural-language query into keywords (unless keywords are given), search all configured image providers in parallel, dedupe, render a numbered composite grid (round 'a', cell ids a1..aN), and run a multimodal filter that returns the selected cell ids. Returns the grid file path, the selected ids, the metadata table, and the keywords actually used.

ParametersJSON Schema
NameRequiredDescriptionDefault
countNoMax candidates in this round (default: grid capacity)
queryYesNatural-language image request, e.g. 'space nebula illustrations for a podcast cover'
filterNofalse = skip the server-side vision filter and return all candidates (use when the calling model is multimodal and will look at the grid itself); default follows FILTER_MODE
criteriaNoStyle / quality criteria for filtering, e.g. 'flat vector, no text, dark background'
keywordsNoExplicit search keywords; skips LLM parsing when given
safe_searchNo

TDQS

A4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden of behavioral disclosure. It details the process steps, the return values (grid file path, selected ids, metadata table, keywords used), and explains special behaviors like the 'filter' parameter (false skips filter) and 'keywords' parameter (skips LLM parsing). It also notes the default for filter follows FILTER_MODE. This is transparent, though it does not mention session state persistence or file system side effects beyond returning a path.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two concise sentences. The first enumerates the pipeline steps without redundancy, and the second lists the return values. It is front-loaded with the core action and contains no filler or repetitive language.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the tool's behavior, parameters, and return values. It does not explain the overall session workflow (e.g., that image_search_iterate follows), but that is arguably outside the scope of a single tool description. The return list compensates for the absent output schema. Completeness is high for the tool's complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 83%, so most parameters are described in the schema. The description adds meaningful context beyond the schema by explaining that 'count' defaults to grid capacity, 'filter=false' skips the vision filter, and 'keywords' skips LLM parsing. It also clarifies the filter default via FILTER_MODE. This enriches the parameter understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a clear verb and resource: 'start an image search session.' It then describes the full pipeline (parse query, search parallel, dedupe, render grid, filter, return results). The action is specific and distinct from siblings like iterate, collect, and status, making it obvious this tool initiates the session.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description does not explicitly state when to use this tool versus its siblings. It does not mention 'use this to begin a session' or direct the agent to image_search_iterate for refinement. While the name implies it is the starting point, there is no explicit guidance on choosing it over alternatives or any exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

image_search_statusShow session stateB

Rounds so far, per-round selections/rejections, current keywords, and collected ids.

ParametersJSON Schema
NameRequiredDescriptionDefault
session_idYes

TDQS

B3.2/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description bears full responsibility for disclosing side effects. It lists what data is returned but does not explicitly state that the operation is read-only or free of side effects. The verb 'show' implies a non-mutating action, but this is not made explicit, leaving some ambiguity.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence that front-loads the core purpose ('show session state') and then lists all contents in a compact list. There is no superfluous information, and every item contributes to understanding the returned data.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple status tool with one parameter and no output schema, the description lists the key fields returned, which is helpful. However, it lacks an explicit read-only statement and does not mention error conditions (e.g., invalid session_id), which are important given the absence of annotations. It is adequate but not fully complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description completely ignores the only parameter, session_id, and the schema provides no description for it either. The agent gets no additional context about the format, origin, or purpose of session_id beyond its name, which is insufficient given the 0% schema description coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'show' and the resource 'session state', and then enumerates the specific contents ('rounds so far, per-round selections/rejections, current keywords, and collected ids'). This distinguishes it from sibling tools that start, iterate, or collect, as it is the only one that reports on state.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is given on when to use this tool versus its siblings. It does not mention that it should be used between iterations, nor does it reference alternatives or conditions that would select it. The only hint is the name 'status', which implies a read operation, but there is no explicit context.

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.

  1. 4 tool updatesv0.1.0
    • First observedimage_search_collect
    • First observedimage_search_iterate
    • First observedimage_search_start
    • First observedimage_search_status

TDQS

A4/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a unique and clearly defined role: start initializes a search, iterate refines it with feedback, collect downloads selected results, and status reports the current state. No two tools overlap in purpose.

Naming Consistency5/5

All tools follow the exact same `image_search_<verb>` pattern, with verbs that accurately describe the action (start, iterate, collect, status). The naming is uniformly styled and predictable.

Tool Count5/5

Four tools is perfectly scoped for an iterative image search workflow. Each tool covers a necessary step without redundancy, making the set concise and well-balanced.

Completeness5/5

The tools cover the full lifecycle: initiating a search, refining it through feedback, collecting final results, and monitoring progress. No obvious gaps exist for the intended use case, as the start tool integrates search and multimodal filtering.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers