groundlens
OfficialGroundlens: un corrector para respuestas RAG

Cómo funciona · Instalación · Inicio rápido · Servidor MCP · Limitaciones · Reproducibilidad
Groundlens es un corrector de lo que escribe tu modelo. Marca las palabras que tus fuentes no respaldan — y te muestra qué debería haber dicho cada una. Comprueba la fundamentación y la fidelidad de las respuestas RAG frente a sus fuentes recuperadas, la tarea para la que la gente recurre a la detección de alucinaciones, la verificación de citas o la evaluación de RAG — y se diferencia en que devuelve marcas y evidencias para un revisor, no un veredicto o una puntuación a la que aplicar un umbral.
QUESTION What is the invoice total?
SOURCE ...the total amount due is 10,000 dollars, payable within 30 days...
ANSWER The invoice total is 1,000 dollars, due in 30 days.
GROUNDLENS 1,000 nothing supports this. Closest in invoice.pdf#p1: '10,000'Nunca te dice que la respuesta es incorrecta. Te dice qué palabra debes mirar y qué documento debes abrir. Treinta segundos de atención humana en lugar de cinco minutos.
Cómo funciona

Groundlens aborda la comparación de palabras y números de dos maneras diferentes:
Palabras | Números |
Las palabras se anclan por significado. El respaldo de una palabra es la similitud coseno más alta que alcanza contra cualquier palabra de las fuentes, usando un codificador prefabricado congelado — el mismo tipo que tu recuperación ya utiliza. | Los números se anclan por aritmética. El numeral se analiza a un valor con formato normalizado — |
Groundlens proporciona la puntuación más baja como resultado, no el promedio. Toda métrica de similitud por tokens agrega mediante la media, y la media es donde mueren los errores de un solo token.
Un ejemplo práctico: diez no es cien
Un documento recuperado dice que el total adeudado es de 10,000 dólares. La respuesta dice 1,000 dólares. Un humano lo detecta al instante, sin título en finanzas.
La similitud por incrustaciones no lo detecta. El coseno entre la respuesta correcta y la incorrecta es de aproximadamente 0.99 — el error se disuelve en el vector como una gota de tinta se disuelve en un estanque. Un juez LLM tampoco: lee buscando plausibilidad, y "el total es de 1,000 dólares" es una frase perfectamente plausible sobre una factura. Un detector de tramos entrenado tampoco, porque las sustituciones de un solo dígito son raras en sus etiquetas de entrenamiento.
Los codificadores de oraciones organizan el texto por vocabulario, tema y estructura. Nunca por verdad. Un número incorrecto dentro de una oración correcta es, para un codificador que colapsa paráfrasis, casi una paráfrasis.
En esa factura, el respaldo medio de la respuesta incorrecta es 0.79 — que parece correcto. El ancla más débil es 0.00 — que es una marca en el margen.
Umbral operativo
Esta biblioteca no tiene umbral predeterminado. Un umbral es una propiedad de un despliegue, no de un método. Depende del codificador, de tus datos y de lo que te cueste un falso positivo en comparación con un falso negativo. Nada de eso se conoce aquí.
Hay una medición detrás de la regla. En la cuadrícula de puntos operativos que ejecutamos, la mejor tasa de falsos positivos con un 95 por ciento de recuperación fue de 0.65, para cada detector de una sola pasada que probamos, incluido este. En la recuperación que una revisión regulada realmente necesita, ningún corte fijo en esa cuadrícula es utilizable. Publicar uno significaría publicar un número que ya sabemos que no se sostiene.

Lo que groundlens proporciona es:
Una puntuación de respaldo por palabra, donde un valor más bajo significa menos respaldo de las fuentes.
Marcas con recibos: la palabra, su tramo, su respaldo y la oración de evidencia más cercana, para que un revisor pueda verificar cualquier llamada en segundos.
Una función
calibrate(), que ajusta un corte con tus propios datos etiquetados. Se niega a ejecutarse con menos de 200 ejemplos etiquetados, porque por debajo de eso el corte es ruido.
Si necesitas un umbral en tu canalización, ejecuta calibrate() con tus datos etiquetados:
from groundlens import calibrate
point = calibrate(labelled, target_recall=0.95)
print(point.threshold, point.fpr, point.fpr_ci95) # read the fpr first
calibrate()necesita al menos 200 ejemplos etiquetados, porque por debajo de eso un umbral de 95% de recuperación se estima a partir de un puñado de puntos.
Related MCP server: Sentry MCP
Instalación
pip install groundlens # zero runtime dependencies. Not numpy, not torch
pip install "groundlens[encoder]" # + the reference sentence encoder
pip install "groundlens[encoder,mcp]" # + the MCP server, for Claude Desktop and friendsLa instalación principal no incorpora ningún paquete, y un trabajo de CI hace fallar la compilación si eso cambia alguna vez. La versión anterior instalaba aproximadamente dos gigabytes de pila de aprendizaje profundo antes de que hubieras hecho nada.
Inicio rápido
from groundlens import proofread, SentenceTransformerEncoder
answer = "The invoice total is 4.75% payable within 45 days."
sources = [("policy.pdf#p3", "The rate stated in the policy is 3.90% and the term is 30 days.")]
marks = proofread(answer, sources, encoder=SentenceTransformerEncoder(), k=2)
print(marks.report())
# 4.75% support 0.00 nearest in policy.pdf#p3: '3.90%'
# 45 support 0.00 nearest in policy.pdf#p3: '30'Cada marca lleva su recibo:
for anchor in marks.weakest:
anchor.text # '4.75%' the word in the answer
anchor.span # (21, 26) where it sits
anchor.kind # 'numeral' checked by arithmetic, not meaning
anchor.support # 0.0 absent from the sources
anchor.evidence_id # 'policy.pdf#p3' which document to open
anchor.evidence_text # '3.90%' what it should have matchedDesde la terminal:
groundlens read --answer answer.txt --context policy.pdf#p3=policy.txtServidor MCP
El mismo corrector, dentro de tu asistente. Groundlens incluye un servidor MCP, de modo que Claude Desktop, Claude Code, Cursor, VS Code o cualquier otro cliente MCP puede comprobar una respuesta frente a sus fuentes sin salir de la conversación. Se ejecuta localmente sobre stdio. Ningún texto sale a ningún sitio.
pip install "groundlens[encoder,mcp]"
python -m groundlens.mcpLuego apunta tu cliente hacia él. En claude_desktop_config.json — o el equivalente
mcp.json en Cursor y VS Code:
{
"mcpServers": {
"groundlens": {
"command": "python",
"args": ["-m", "groundlens.mcp"]
}
}
}Usa la ruta absoluta al Python que tiene Groundlens instalado si no es
el que está en tu PATH: /path/to/venv/bin/python.
La única herramienta
find_unsupported_words(answer, sources, k=4, locale="und")
| la salida del modelo a comprobar |
|
|
| cuántas de las anclas más débiles devolver |
| cómo escriben los números estos documentos. |
Devuelve las anclas más débiles con sus recibos, el mínimo, el id del codificador y
un sha256 del hallazgo:
{
"weakest_anchors": [
{
"word": "4.75%",
"support": 0.0,
"checked_by": "arithmetic",
"closest_in_sources": "3.90%",
"source_id": "policy.pdf#p3",
"notes": []
}
],
"floor": 0.0,
"n_marked": 12,
"encoder_id": "all-mpnet-base-v2@<revision-sha>",
"sha256": "..."
}Una sola herramienta, a propósito. El servidor anterior anunciaba tres, y así es como un producto se convierte en tres historias antes de que nadie lo haya instalado.
No hay veredicto ni umbral, aquí como en todas partes de esta biblioteca. Un
support de 0.00 en un número significa que ese valor está ausente de las fuentes. En una
palabra significa que no se encontró ningún ancla léxica, lo cual es normal en una
paráfrasis fiel. El servidor informa de las marcas; el lector decide.
El codificador se carga en la primera llamada, no al inicio, y el modelo se descarga una vez (aproximadamente 420 MB) la primera vez que se utiliza.
Limitaciones
No puede verificar valores calculados — "los ingresos se triplicaron" frente a una fuente que dice "los ingresos pasaron de 5M a 15M".
El canal de palabras comprueba si una palabra está respaldada por las fuentes. No comprueba que esté vinculada a lo correcto. Si una respuesta dice "pagadero en 30 días" sobre la factura A y los 30 días pertenecen a la factura B en otro lugar del mismo contexto, la palabra está respaldada y no aparece ninguna marca.
No puede comprobar el razonamiento. Eso corresponde a los modelos de implicación.
Hereda tu recuperación. Si el pasaje es incorrecto, también lo es la fundamentación de la respuesta.
La segmentación asume escrituras separadas por espacios, y advierte en lugar de fingir cuando el texto es mayoritariamente CJK o tailandés.
Reproducibilidad
El canal de numerales es exacto. Comparación decimal, contexto aritmético fijo, configuración regional desde un argumento y nunca desde
LC_ALL. Idéntico byte a byte en cualquier máquina — CI lo demuestra en diez combinaciones de SO × Python bajoPYTHONHASHSEED=randomy una configuración regional turca.El canal léxico es un coseno float32 de una revisión de codificador fijada — no un nombre de modelo, porque una re-subida silenciosa cambiaría cada número que hayas publicado. Se reproduce hasta 1e-6 entre plataformas y el orden de las anclas más débiles es estable. No es bit-idéntico entre x86 y Apple Silicon, y no afirmamos que lo sea.
marks.sha256cubre la estructura y los respaldos de numerales exactamente, y redondea los respaldos léxicos a seis decimales. Reproducir el hash reproduce el hallazgo, no los últimos bits de la aritmética.
groundlens.dev · PyPI · Retractions · Contributing · Apache-2.0
Available Tools
3 toolsverify_answerB
Verify an answer against its sources under a policy and return the sealed record.
sources: (id, text) pairs, {"id","text"} dicts, or bare strings.
policy: a built-in name (e.g. "eu_ai_act_high_risk_v1"), a path, or YAML.
Returns the decision (PASS/REVIEW/FAIL), the evidence, the regulatory
mapping and the record with its content hash.
| Name | Required | Description | Default |
|---|---|---|---|
| answer | Yes | ||
| locale | No | und | |
| policy | No | ||
| sources | Yes | ||
| question | No |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of disclosing behavior. It does describe the return value (decision, evidence, regulatory mapping, record with content hash), which is helpful. However, it does not state whether the operation is read-only, whether it stores or modifies any data, or what side effects might occur. For a verification tool, this is a notable gap, especially since the action of returning a 'sealed record' implies some immutability but not explicitly a non-destructive 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 concise and front-loaded, stating the core action in the first sentence. It then efficiently lists input format variants and the return contents. The multi-line formatting with indentation is slightly unconventional but does not harm readability. There is minimal redundancy, and 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 tool has 5 parameters (2 required) and an output schema exists, the description is moderately complete. It covers the key inputs (sources, policy) and mentions the return structure. However, it omits explanation of 'locale' and 'question', and does not provide usage context relative to sibling tools or error scenarios. The presence of an output schema lightens the need to detail return fields, but the missing parameter semantics and lack of sibling differentiation reduce 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 description coverage is 0%, so the description must compensate. It explains the semantics of 'sources' (formats) and 'policy' (built-in, path, YAML). The 'answer' parameter is implicitly clear from the first sentence. However, 'locale' and 'question' are not described at all. Thus, the description covers only a portion of the parameters, leaving two parameters with no guidance beyond their names.
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 begins with a clear, specific verb and resource: 'Verify an answer against its sources under a policy and return the sealed record.' This distinguishes it from siblings (verify_run, verify_records) by focusing on answer verification, which is a distinct operation.
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 provides usage details such as acceptable formats for sources (id/text pairs, dicts, strings) and policy (built-in name, path, YAML), which implicitly guides the caller. However, it does not explicitly state when to use this tool versus the sibling tools verify_run or verify_records, nor does it mention any exclusions or alternative conditions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
verify_recordsA
Verify a log of records offline: every hash, every link, every signature.
records: the JSON Lines text of an answer-record or run-record log.
Returns {"ok", "verified", "kind"}; fails if any record or link was altered.
| Name | Required | Description | Default |
|---|---|---|---|
| records | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full behavioral burden and does meaningful work: it discloses the return shape ('Returns {"ok", "verified", "kind"}'), the failure mode ('fails if any record or link was altered'), and that the operation happens offline. It stops short of explicitly stating verification is non-destructive, a minor gap given 'verify' implies it.
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 compact — purpose is front-loaded in the first sentence, followed by the parameter and then the return/failure behavior. Every clause carries information an agent needs; there is no filler or restatement of the tool name.
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 one-parameter verification tool with an output schema present, the description covers purpose, input format, return shape, and failure behavior — nearly everything needed to call it correctly. Minor gaps like the possible values of 'kind' are left to the output schema, which is acceptable per the rubric.
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 0%, so the description must compensate, and it does: it documents 'records' as 'the JSON Lines text of an answer-record or run-record log,' adding format and content meaning the schema lacks. It doesn't specify the exact structure of a valid record, but for a single string parameter the added semantics are substantial.
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 states a specific verb and resource ('Verify a log of records offline') with concrete scope ('every hash, every link, every signature'), so an agent can tell exactly what operation this performs. It also distinguishes this from the siblings verify_run and verify_answer by clarifying that it accepts both answer-record and run-record logs.
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 by noting the tool accepts 'an answer-record or run-record log,' which hints it covers the domains of both siblings. However, it never names verify_run or verify_answer or gives an explicit when-to-use vs. when-not-to-use rule, leaving the routing decision to inference.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
verify_runA
Verify an MCP execution trace under an execution policy and return the run record.
trace: the MCP session as JSON-RPC messages (JSON Lines).
policy: the execution policy, as YAML/JSON text or a path.
Returns the gate (ALLOW/REVIEW/DENY), any breaches, and the signed run record.
| Name | Required | Description | Default |
|---|---|---|---|
| trace | Yes | ||
| policy | Yes | ||
| run_id | Yes | ||
| system | Yes | ||
| started_at | No | ||
| system_version | No |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
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. It discloses the return values (gate, breaches, signed run record) but does not mention potential side effects (e.g., whether it writes or stores anything), permission requirements, or error behavior. This is some behavioral context but incomplete for a tool with no annotation safety net.
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 reasonably concise, with the purpose front-loaded and parameters broken into clear lines. It avoids redundant wording and communicates the key return values efficiently, though it could be tightened slightly.
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 an output schema, so return format details are not strictly required, and the description already provides a high-level return summary. However, given the six-parameter complexity and lack of annotations, the description should explain all parameters and ideally differentiate usage from siblings. It covers the core purpose but leaves several parameters and usage guidance gaps.
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 0%, so the description must compensate. It explains trace (format: JSON-RPC messages as JSON Lines) and policy (format: YAML/JSON text or path), which is useful. However, it does not explain run_id, system, started_at, or system_version, leaving 4 of 6 parameters undocumented in both schema and description. This is a significant gap.
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 verifies an MCP execution trace against an execution policy and returns the run record with gate, breaches, and signed record. This specific verb+resource distinguishes it from sibling tools verify_answer and verify_records, which target different resources.
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 by specifying it is for verifying execution traces, which gives clear context. However, it does not explicitly mention when not to use it or point to alternatives like verify_answer or verify_records, so it lacks explicit exclusions.
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.
4 tool updates
v3.0.6- Removed
find_unsupported_words - Added
verify_answer - Added
verify_records - Added
verify_run
1 tool update
v0.1.0- First observed
find_unsupported_words
TDQS
Scored across 3 tools
The three tools address clearly different verification targets: execution traces, answer-source pairs, and record logs. No two tools accept the same kind of input or produce the same kind of output, so an agent can select among them without ambiguity.
All tool names follow the same verify_<noun> pattern with snake_case, matching the verb-object convention. The naming makes the input type immediately predictable from the tool name.
At three tools, the surface is tightly scoped to the verification domain: run traces, answers, and record-chain integrity. Each tool covers a distinct workflow and none feels redundant.
The toolkit covers the full observed verification lifecycle: generating verified run records, generating answer records, and validating logs of those records. Policies are provided as parameters rather than requiring separate management tools, so there are no obvious dead ends.
Maintenance
Related MCP Connectors
Fact-checks generated content against your sources of truth showing what to trust, change, & verify.
- PortMemOAuthcom.portmem
Check AI-written drafts against your source documents, with the passage behind every verdict.
Real-time fact-check, citation verification, and source-freshness for AI agents.
DraftCheck: flags AI-writing patterns in prose with fix hints. Deterministic linter, not a detector.
Related MCP Servers
AlicenseBqualityFmaintenanceAn MCP server that provides a comprehensive interface to Semgrep, enabling users to scan code for security vulnerabilities, create custom rules, and analyze scan results through the Model Context Protocol.6701 PyPI687MIT
Sentry MCPofficial
AlicenseAqualityAmaintenanceA remote Model Context Protocol server acting as middleware to the Sentry API, allowing AI assistants like Claude to access Sentry data and functionality through natural language interfaces.738 npm917MIT
Vectara MCP serverofficial
AlicenseAqualityDmaintenanceOpen source MCP server for Vectara21,497 PyPI29Apache 2.0
Arkheia Hallucinationofficial
AlicenseNot gradedqualityDmaintenanceDetect fabrication and hallucination in any LLM output. Score responses from GPT-4o, Claude, Gemini, Llama and 30+ models. Free tier included.2MIT