MCP Knowledge Assistant
Asistente de Conocimiento MCP
Un servidor de Model Context Protocol (MCP) de solo lectura que permite a un cliente de IA buscar en una base de conocimiento y recuperar documentos fuente completos. El proyecto comienza con un pequeño prototipo local y luego aplica el mismo contrato de herramientas a la recuperación semántica desde un almacén de vectores de OpenAI.
Qué demuestra esto
Diseño de herramientas MCP con responsabilidades reducidas de
searchyfetchEntradas y salidas estructuradas mediante FastMCP y Pydantic
Recuperación semántica sobre documentos subidos a un almacén de vectores de OpenAI
Deduplicación a nivel de documento cuando la búsqueda vectorial devuelve varios fragmentos coincidentes
Transportes MCP HTTP transmisible y
stdioUso integral de herramientas a través de la API de Respuestas de OpenAI y un túnel MCP seguro
Configuración mediante variables de entorno, sin credenciales en el código fuente
Pruebas unitarias y a nivel de protocolo que no realizan llamadas de pago a la API
Related MCP server: File AI
Arquitectura
OpenAI Responses API
|
| MCP tool calls through an outbound secure tunnel
v
Local FastMCP server (Streamable HTTP)
|
| vector-store search and file retrieval
v
OpenAI vector store -> uploaded documentsEl repositorio también incluye una ruta de aprendizaje totalmente local:
Local demo client -> FastMCP server (stdio) -> data/documents.jsonAmbos servidores exponen el mismo contrato público de herramientas:
Herramienta | Entrada | Propósito |
|
| Devuelve referencias de documentos compactas y relevantes. |
|
| Recupera un documento completo seleccionado de la búsqueda. |
Mantener la detección separada de la recuperación evita enviar documentos completos antes de que sean necesarios y proporciona al modelo identificadores de documento estables para usar en llamadas posteriores.
Estructura del proyecto
.
├── data/documents.json # Sample local knowledge base
├── sample_data/cats.pdf # Public-domain vector-store sample
├── src/mcp_knowledge_assistant/
│ ├── knowledge_base.py # Local keyword retrieval
│ ├── models.py # Shared response schemas
│ ├── server.py # Local stdio MCP server
│ └── vector_store_server.py # OpenAI vector-store MCP server
├── tests/ # Offline unit and MCP tests
├── demo_client.py # Local stdio demonstration
├── vector_store_demo_client.py # Direct HTTP MCP demonstration
└── api_client.py # Responses API + secure tunnel demonstrationRequisitos
Python 3.11 o superior
Un proyecto de API de OpenAI con facturación habilitada para la ruta del almacén de vectores
El PDF de muestra incluido, o su propio documento, subido a un almacén de vectores de OpenAI
El cliente de túnel de OpenAI solo para la demostración del túnel seguro
El servidor JSON local y el conjunto completo de pruebas no requieren clave de API.
Atribución del documento de muestra
La demostración del almacén de vectores utiliza Cats: Their Points and Characteristics de W. Gordon Stables, eBook #43429 del Proyecto Gutenberg. El PDF de muestra está alojado por OpenAI y se produjo a partir de la edición del Proyecto Gutenberg. Consulte el PDF para conocer la licencia del Proyecto Gutenberg y los términos de reutilización aplicables.
Configuración
Clone el repositorio, cree un entorno virtual e instale el proyecto:
python -m venv .venv
source .venv/bin/activate
python -m pip install -e ".[dev]"Para los ejemplos respaldados por OpenAI, copie la plantilla de entorno:
cp .env.example .env.localLuego agregue sus propios valores a .env.local:
OPENAI_API_KEY=your_project_api_key
VECTOR_STORE_ID=vs_your_vector_store_id.env.local, la configuración de PyCharm, los entornos virtuales y los perfiles de túnel locales
están excluidos de Git.
1. Ejecutar el prototipo local
El primer servidor usa stdio, por lo que el cliente MCP lo inicia como un proceso hijo
y se comunica a través de la entrada y salida estándar:
python demo_client.pyLa demostración detecta ambas herramientas, busca en la base de conocimiento JSON de muestra y recupera el documento seleccionado.
También puede iniciar el servidor mediante su comando instalado:
mcp-knowledge-assistantUn proceso silencioso en espera es normal para un servidor stdio que no tiene ningún
cliente conectado.
2. Ejecutar el servidor del almacén de vectores
Suba sample_data/cats.pdf a un almacén de vectores de OpenAI y luego establezca
OPENAI_API_KEY y VECTOR_STORE_ID en .env.local. Puede sustituir su
propio documento y consulta si lo prefiere. Inicie el servidor HTTP transmisible:
mcp-vector-store-assistantPor defecto, su punto final MCP es:
http://127.0.0.1:8000/mcpEn una segunda terminal, pruebe el punto final directamente:
python vector_store_demo_client.pyLa búsqueda vectorial opera sobre fragmentos, por lo que un documento largo puede producir varias
coincidencias con el mismo ID de archivo. La herramienta MCP search colapsa deliberadamente
esas coincidencias en un único resultado de documento. La herramienta fetch recupera y
combina el contenido analizado de ese documento para el modelo.
3. Llamarlo a través de la API de Respuestas
Siga la guía de túneles MCP seguros de OpenAI
para crear un túnel, configure su perfil local ignorado para que apunte a
http://127.0.0.1:8000/mcp e inicie el cliente de túnel. Agregue el ID resultante a
.env.local:
MCP_TUNNEL_ID=tunnel_your_tunnel_idEl cliente de túnel lee su propia credencial de tiempo de ejecución de
CONTROL_PLANE_API_KEY. Mantenga ese valor también local. Con el servidor de vectores
y el cliente de túnel ambos en ejecución, ejecute:
python api_client.pyLa solicitud a la API de Respuestas declara únicamente las herramientas MCP de solo lectura
search y fetch. El modelo puede buscar, recuperar una fuente seleccionada y componer una respuesta a partir
del contenido recuperado.
Pruebas
Ejecute todas las pruebas con:
pytestLas pruebas cubren la clasificación y recuperación local, la detección de herramientas MCP, la deduplicación de resultados vectoriales, el ensamblaje de contenido y la validación de entradas. Las llamadas a OpenAI están simuladas, por lo que el conjunto es repetible y no consume créditos de API.
Decisiones de diseño y alcance
Solo lectura primero: ninguna herramienta MCP modifica archivos o estado externo.
Contrato de compatibilidad estable:
search(query)devuelve referencias de documentos;fetch(id)devuelve contenido completo y metadatos.Resultados de documentos, no resultados de fragmentos: los fragmentos son evidencia de recuperación dentro del almacén de vectores, mientras que el cliente MCP recibe IDs de archivo estables.
MCP es una capa de abstracción: para un único almacén de vectores alojado en OpenAI, la herramienta File Search integrada de la API de Respuestas es más simple. MCP resulta útil cuando la misma interfaz de recuperación debe atender a múltiples clientes, ocultar detalles del backend, o agregar posteriormente autorización y lógica de dominio.
Límite de integración verificado: los servidores locales, los clientes MCP directos y la ruta de la API de Respuestas a través del túnel seguro se probaron durante el desarrollo. Este repositorio no afirma tener un servidor público implementado ni una aplicación ChatGPT publicada.
Notas de seguridad
Nunca confirme
.env.local, claves de API, claves de tiempo de ejecución del túnel o IDs de organización.Use credenciales con alcance de proyecto y otorgue únicamente los permisos necesarios.
Mantenga el servidor MCP local vinculado detrás del túnel saliente seguro en lugar de abrir un puerto de firewall entrante.
Revise los permisos de las herramientas antes de agregar cualquier acción de escritura o de consecuencias.
Referencias
Available Tools
2 toolsfetchA
Retrieve one complete document using an ID returned by search.
| Name | Required | Description | Default |
|---|---|---|---|
| id | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| id | Yes | |
| url | Yes | |
| text | Yes | |
| title | Yes | |
| metadata | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full behavioral disclosure burden. It reveals that this returns a complete document (not a summary) and that it depends on search-generated IDs, but doesn't mention error handling, permissions, or potential side effects. For a simple read operation this is adequate but has 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?
One sentence, no redundant details, and the key information (retrieve by ID) is front-loaded. Perfect conciseness.
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 that an output schema is present and there is only one parameter, the description sufficiently covers the essential context and its relationship to the sibling search tool. It could be improved by mentioning error cases or what happens if the ID is invalid, but for this simplicity it is complete enough.
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 single parameter 'id' has no schema description, so the description's phrase 'returned by search' provides crucial semantic context, explaining where the ID comes from and how it should be used to retrieve the document.
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 uses the specific verb 'Retrieve' with the resource 'one complete document' and the qualifier 'using an ID returned by search', which clearly defines the tool's scope and distinguishes it from the sibling tool 'search'.
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?
It explicitly states that the ID must come from search, establishing a clear workflow (search first, then fetch). It doesn't explicitly mention alternatives, but the context is clear enough for an agent to know when to use this tool versus search.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
searchC
Find documents relevant to a natural-language query.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| results | Yes |
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 behavioral disclosure. It reveals that the tool does semantic matching over a natural-language query, but says nothing about how results are ranked, paginated, limited, scoped, or whether interactions are read-only or have side effects. It is not misleading, but it adds very little beyond what the name and schema already imply.
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 front-loaded sentence with zero wasted words. It is appropriately brief for a minimal tool definition, though one could argue it is slightly under-specified—but the economy of expression is commendable.
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 tool with 1 parameter, no annotations, 0% schema coverage, and an unaddressed sibling 'fetch', one sentence is insufficient context. The description would be more complete by mentioning result limits, sort order, or any behavioral differences from fetch. The presence of an output schema helps explain return values, but the in/out behavior is still too thin for an agent to fully understand the tool's scope.
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 add value by clarifying that 'query' accepts natural-language text rather than structured filters or keywords. However, it provides no examples, formatting hints, length limits, or syntax conventions—the description does the bare minimum to make the parameter actionable.
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?
'Find documents relevant to a natural-language query' uses a clear verb ('find'), a resource ('documents'), and a scope qualifier ('natural-language query'). It is clear and specific, but it does not explicitly distinguish itself from its sibling 'fetch', so it earns a 4 rather than a 5.
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?
There is no guidance on when to use search versus its sibling 'fetch', no exclusions, and no when-to-use context. The description implies usage through the term 'search', but a sibling tool with zero differentiator guidance means the agent is left without decision support. This is 'no guidance' and scores a 2.
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.
2 tool updates
v0.1.0- First observed
fetch - First observed
search
TDQS
Scored across 2 tools
search and fetch have clearly distinct purposes: one finds documents by query, the other retrieves a specific document by ID. There is no overlap or ambiguity.
Both tools use simple, consistent single-verb names ('search' and 'fetch') that clearly indicate their actions. The pattern is uniform.
With only 2 tools, the server is minimal but functionally complete for a simple search-and-retrieve pattern. It feels thin but is reasonable for a narrow purpose.
The two tools cover the core workflow of searching and retrieving documents. Minor gaps could include listing all documents or getting metadata, but the essential lifecycle is covered.
Maintenance
Related MCP Connectors
Read-only MCP server exposing a user ORANO library to their own AI agent.
Knowledge base MCP for AI agents on iknow.dev. Search, read, and maintain via OAuth.
Knowledge base for AI agents: search, read, tasks; write, correct, report outcomes via /mcp/write.
Related MCP Servers
- AlicenseNot gradedqualityAmaintenanceAn MCP server that provides tools for retrieving and processing documentation through vector search, enabling AI assistants to augment their responses with relevant documentation context.24 npmMIT
- AlicenseBqualityDmaintenanceA read-only MCP server that provides document awareness for agents by parsing local files into structured profiles, blocks, chunks, and search results, enabling agents to understand and cite document content without dealing with raw file formats.543 npm3Apache 2.0
- FlicenseNot gradedqualityBmaintenanceAn MCP server that connects the Casio Plus knowledge base (playbooks, architecture, learning resources) to AI clients, offering read-only search and validation tools along with controlled feedback intake and review workflows.-
- AlicenseNot gradedqualityAmaintenanceMCP server that enables AI agents to search, fetch, and analyze a self-maintaining markdown knowledge base with provenance, drift detection, and canonical definitions.1MIT