Skip to main content
Glama
hesreallyhim

MCP Observer Server

by hesreallyhim

servidor observador mcp

mcp-observer-server es un servidor MCP (Protocolo de Contexto de Modelo) que monitoriza los eventos del sistema de archivos y proporciona notificaciones en tiempo real a los clientes MCP. Actúa como un puente (más bidireccional) entre el sistema de archivos local y los asistentes de IA como Claude Inspector, lo que les permite responder automáticamente a los cambios de archivos.

NOTA: Esta es una demostración/prueba de concepto de un servidor MCP de monitoreo de archivos en el que estoy trabajando. He recibido muchas preguntas, comentarios, problemas y debates sobre este tema, así que quería publicar esta implementación mínima para compartir mi enfoque.

Contexto

El protocolo MCP define el concepto de suscripción de recursos, donde un cliente puede solicitar ser notificado de cualquier cambio en un recurso, y el servidor puede optar por enviar notificaciones. A continuación, se muestra el diagrama de flujo:

Diagrama de flujo de suscripción de recursos

El protocolo indica que el cliente debe enviar una solicitud de lectura al servidor para leer los cambios (todo esto es opcional, por cierto). Sin embargo, me parece un poco engorroso e implica un viaje adicional, y preferiría que mi notificación de actualización de recursos también describiera el cambio. Por suerte, el SDK ofrece un campo meta / _meta y se puede enviar prácticamente lo que se quiera. Así que podría querer enviar el número de líneas modificadas, una comparación de los cambios, quién sabe qué más. No lo he implementado en esta demo; ahora mismo solo envío la marca de tiempo. (Básicamente, extraje todo del servidor excepto la prueba de concepto mínima). Además, se ejecuta en el transporte stdio, nada sofisticado.

¡NOTA! Aún no he probado esto con ningún cliente MCP real. Entiendo que muchos clientes de vista admiten suscripciones de recursos, ya que son opcionales. Afortunadamente, Inspector es un cliente muy bueno y puedes usarlo para probar este servidor.

INSTRUCCIONES DE DEMOSTRACIÓN:

  1. Clonar el repositorio.

  2. Instale las dependencias usando uv (o de alguna otra manera, supongo).

  3. Ejecute el servidor usando make start (usa uv ) o ejecute npx @modelcontextprotocol/inspector uv run src/mcp_observer_server/server.py .

  4. Abra el cliente Inspector y conéctese usando stdio, no necesita configuración.

  5. Utilice la herramienta subscribe para supervisar un directorio o archivo (alternativamente, puede ejecutar "Listar recursos", hacer clic en un recurso y luego hacer clic en el botón "Suscribirse" para suscribirse a él).

  6. De forma predeterminada, el servidor expondrá un archivo llamado watched.txt en src/mcp_observer_server/watched.txt (el archivo es .gitignored, por lo que debe crearlo), pero también puede suscribirse a otros archivos. Puede suscribirse a este archivo con la herramienta subscribe_default .

  7. Modifique el archivo watched.txt (o el archivo al que se haya suscrito) y debería aparecer una notificación del servidor en el panel inferior derecho del Inspector. Este es el POC establecido.

Related MCP server: File MCP Server

VISUALIZACIÓN DE DEMOSTRACIÓN

  1. Inicie el servidor y conéctese con Inspector:Iniciar el servidor y conectarse

  2. Enumere los recursos predeterminados:Lista de recursos

  3. Enumere las herramientas:Herramientas de lista

  4. Suscríbete al archivo predeterminado: Suscribirse al archivo predeterminado

  5. Modificar el archivo:Modificar el archivo

  6. Ver aparecer la notificación:Ver Notificación

🎉

Descripción del servidor

El servidor MCP Observer rastrea los cambios en archivos y directorios de su sistema, lo que permite a los clientes MCP suscribirse a estos eventos y tomar medidas cuando se crean, modifican, eliminan o mueven archivos (la demostración actual gestiona eventos de modificación). Este servidor implementa la especificación completa del Protocolo de Contexto de Modelo, que proporciona:

  • Monitoreo de archivos en tiempo real : uso de la biblioteca Watchdog para una observación eficiente del sistema de archivos

  • Gestión de suscripciones : cree, enumere y cancele suscripciones de monitoreo para cualquier ruta

  • Historial de cambios : mantiene un registro de los cambios recientes para cada suscripción (omitido en la demostración)

  • Acceso a archivos y directorios : lea el contenido de los archivos y los listados de directorios a través de los recursos de MCP

  • Diseño sin estado : los clientes controlan lo que sucede en respuesta a los cambios de archivos

Características principales

  • Suscribirse a cambios en archivos específicos, directorios o repositorios completos

  • Filtrar eventos por patrones de archivos o tipos de eventos (omitido en la demostración)

  • Consultar cambios recientes para ver qué archivos se vieron afectados (omitido en la demostración)

  • Acceda al contenido de los archivos a través de los puntos finales de recursos

  • Implementación ligera y eficiente con dependencias mínimas

  • Integración sencilla con cualquier cliente compatible con MCP (...que admita suscripciones de recursos)

Aplicaciones prácticas

El principal problema que intento resolver es que, a menos que Claude Code, por ejemplo, toque un archivo y escriba el cambio, no tiene ni idea de lo que ocurre en tu repositorio/proyecto. (¿Conoces esas notificaciones de "Archivo modificado desde la última lectura"?). Tener un cliente o asistente de programación que supervise lo que haces en tu proyecto, sin tener que delegarle todas las tareas a Claude solo para que sepa que suceden, me parece tremendamente útil. Algunas aplicaciones prácticas incluyen:

  • Actualizaciones automatizadas de la documentación : mantenga la documentación sincronizada con los cambios de código: usted actualiza algún código, Claude recibe una notificación del cambio y verifica o actualiza de forma proactiva las cadenas de documentación, etc.

  • Revisiones de código en vivo : obtenga comentarios en tiempo real sobre los cambios de código mientras trabaja, detectando errores ortográficos, errores tipográficos, etc., brindando asesoramiento, verdadera programación en pares.

  • Automatización de pruebas : ejecute pruebas cuando se modifiquen los archivos relevantes.

  • Asistencia de IA : habilite las herramientas de IA para responder automáticamente a los cambios de archivos.

  • Automatización de commits en Git : ¿Olvidas realizar commits con suficiente frecuencia? Claude puede supervisar tus cambios y sugerir (o realizar) acciones de commit con mayor frecuencia.

Diseño de implementación actual

La implementación del servidor presenta una arquitectura optimizada que prioriza la simplicidad, la confiabilidad y la facilidad de mantenimiento.

Aspectos destacados de la arquitectura

  1. Estructura simplificada

    • Implementación enfocada (~170 líneas de código)

    • Funcionalidad consolidada en un pequeño conjunto de componentes principales

    • Diseño limpio basado en funciones que aprovecha directamente el SDK de MCP

    • Alta legibilidad y facilidad de mantenimiento

  2. Gestión eficiente del Estado

    • La estructura de diccionario simple asigna rutas a las sesiones del cliente

    • Utiliza un diccionario watched para el mapeo directo de ruta a sesión

    • Seguimiento de estado mínimo con flujo de datos claro

    • Evita estructuras de datos redundantes

  3. Integración del protocolo MCP

    • Uso directo de los decoradores de funciones del SDK de MCP

    • Manejo limpio de URI de recursos

    • Inicialización simplificada del servidor con configuración de capacidad adecuada

    • Sistema de entrega de notificaciones directas

  4. Procesamiento de eventos

    • Implementación optimizada del controlador de eventos Watchdog

    • Ruta directa de evento a notificación

    • Comunicación segura para subprocesos mediante call_soon_threadsafe

    • Filtrado eficiente de eventos

  5. Sistema de notificación

    • Uso directo de primitivas de notificación MCP

    • Entrega confiable con manejo adecuado de errores

    • Manejo preciso de marcas de tiempo UTC

    • Formato de URI limpio

Componentes principales

  1. Estructura de datos

    • Un único diccionario global watched asigna objetos de ruta a conjuntos de objetos ServerSession

    • Cada entrada de ruta contiene el conjunto de sesiones suscritas a esa ruta

  2. API de herramientas

    • Dos herramientas esenciales: subscribe y unsubscribe

    • Parámetro de ruta simple para una gestión de suscripciones sencilla

    • Manejo limpio de errores y validación de rutas

  3. Manejo de recursos

    • URI de archivos expuestos directamente a través del listado de recursos

    • Resolución y validación de rutas

    • Lectura de contenido de texto para archivos

  4. Procesamiento de eventos

    • La clase Watcher extiende FileSystemEventHandler

    • Procesa eventos modificados directamente

    • Envío de notificaciones seguro para subprocesos

    • Manejo de la relatividad de trayectorias para trayectorias anidadas

  5. Entrega de notificaciones

    • Creación y envío de ServerNotification

    • Metadatos de eventos con marcas de tiempo

    • Formato de URI limpio

La implementación logra un buen equilibrio entre funcionalidad y simplicidad, lo que da como resultado una base de código confiable y fácil de mantener.

Available Tools

4 tools
list_watchedA

List all currently monitored paths and their subscriber counts

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A3.6/5.0
Behavior2/5

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 indicates a read operation ('List') but doesn't specify whether this requires authentication, how data is returned (e.g., format, pagination), or any rate limits. The description is minimal and lacks essential behavioral context for a tool that likely interacts with subscription systems.

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, efficient sentence that front-loads the core purpose without any wasted words. It directly communicates the tool's function in a clear and structured manner, making it easy to understand at a glance.

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

Completeness2/5

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

Given the tool's complexity (likely low, but involves subscription monitoring), no annotations, and no output schema, the description is insufficient. It doesn't explain what the output looks like (e.g., list format, data structure), potential errors, or operational constraints, leaving significant gaps for an AI agent to use it effectively.

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?

The tool has 0 parameters with 100% schema description coverage, so the schema fully documents the absence of inputs. The description doesn't need to compensate for any parameter gaps, and it appropriately doesn't mention parameters, making it complete in this regard. A baseline of 4 is appropriate for zero-parameter tools.

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 specific action ('List all') and resource ('currently monitored paths and their subscriber counts'), distinguishing it from sibling tools like subscribe/unsubscribe which perform different operations. It precisely defines what the tool does without being vague or tautological.

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 context by specifying 'currently monitored paths,' suggesting this tool is for viewing existing subscriptions rather than modifying them. However, it doesn't explicitly state when to use this versus alternatives or provide any exclusion criteria, leaving some ambiguity about its specific application scenarios.

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

subscribeC

Subscribe to changes on a file or directory

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes

TDQS

C2.8/5.0
Behavior2/5

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. While 'Subscribe to changes' implies a monitoring/notification function, it doesn't describe what kind of changes trigger notifications, how notifications are delivered, whether this requires specific permissions, rate limits, or what happens when multiple subscriptions exist. This leaves significant behavioral gaps for a tool that likely establishes ongoing monitoring.

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, efficient sentence that states the core purpose without unnecessary words. It's appropriately sized for a tool with one parameter and gets straight to the point with zero wasted verbiage.

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

Completeness2/5

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

For a subscription tool with no annotations, no output schema, and minimal parameter documentation, the description is inadequate. It doesn't explain what 'subscribing' entails operationally, what format notifications take, how to manage subscriptions, or what the tool returns. Given the complexity of establishing monitoring and the complete lack of structured documentation, this description leaves too many questions unanswered.

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?

With 0% schema description coverage for the single 'path' parameter, the description provides no additional semantic information about what the path represents, its format, or constraints. The description mentions 'file or directory' which gives some context for the path parameter, but this is minimal compensation for the complete lack of schema documentation.

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

Purpose4/5

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

The description clearly states the action ('Subscribe to changes') and target resource ('on a file or directory'), providing a specific verb+resource combination. However, it doesn't distinguish this tool from its sibling 'subscribe_default', which appears to be a related subscription tool, so it doesn't fully differentiate from alternatives.

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 provides no guidance on when to use this tool versus alternatives like 'subscribe_default' or 'list_watched'. It doesn't mention prerequisites, exclusions, or contextual factors that would help an agent choose between subscription-related tools.

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

subscribe_defaultB

Subscribe to the default watched.txt file for development

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.1/5.0
Behavior2/5

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 states the action ('subscribe') but doesn't explain what subscription entails (e.g., real-time updates, notifications, persistence), permissions required, side effects, or error conditions. This leaves significant gaps for a mutation-like operation.

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, efficient sentence with no wasted words. It front-loads the core action and target, making it easy to parse quickly. Every element ('subscribe', 'default', 'watched.txt file', 'development') contributes meaning without redundancy.

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

Completeness2/5

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

Given the tool has no parameters (simplifying input) but no annotations or output schema, the description is incomplete. It lacks details on behavior, return values, error handling, and differentiation from siblings like 'subscribe'. For a subscription tool with mutation implications, this leaves too many unknowns for effective agent use.

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?

The tool has 0 parameters, and schema description coverage is 100% (empty schema). The description doesn't need to add parameter details, and it appropriately avoids discussing nonexistent inputs. A baseline of 4 is applied since no parameters exist to document.

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

Purpose4/5

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

The description clearly states the action ('subscribe') and target resource ('default watched.txt file for development'), making the purpose understandable. It doesn't explicitly distinguish from sibling tools like 'subscribe' (which likely allows custom targets) or 'list_watched'/'unsubscribe', but the specificity of 'default' provides some implicit differentiation.

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 explicit guidance is provided on when to use this tool versus alternatives like 'subscribe' (for non-default files) or 'list_watched' (for viewing subscriptions). The description implies it's for development purposes, but doesn't clarify prerequisites, exclusions, or specific use cases compared to siblings.

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

unsubscribeC

Unsubscribe from changes on a file or directory

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes

TDQS

C2.8/5.0
Behavior2/5

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 states the action ('Unsubscribe from changes') but doesn't explain what 'changes' refers to, whether this operation is reversible, what permissions are required, or what happens after unsubscribing (e.g., notifications stop). For a mutation tool with zero annotation coverage, this leaves significant behavioral gaps.

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, efficient sentence with zero waste—it directly states the tool's purpose without unnecessary words. It's appropriately sized and front-loaded, making it easy to parse quickly.

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

Completeness2/5

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

Given the tool's complexity (a mutation operation with no annotations, no output schema, and low schema coverage), the description is incomplete. It lacks details on behavioral traits, parameter usage, output expectations, and differentiation from siblings, making it inadequate for informed tool selection and invocation.

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?

The input schema has 1 parameter with 0% description coverage, so the schema provides no semantic information. The description mentions 'a file or directory' but doesn't clarify what the 'path' parameter represents (e.g., format, examples, or constraints). It adds minimal value beyond the schema's structural definition.

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

Purpose4/5

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

The description clearly states the action ('Unsubscribe from changes') and the target resource ('on a file or directory'), providing a specific verb+resource combination. However, it doesn't explicitly distinguish this tool from its sibling 'subscribe' or 'subscribe_default', which would require mentioning what makes 'unsubscribe' different from those subscription tools.

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 provides no guidance on when to use this tool versus alternatives like 'list_watched' or when not to use it. There's no mention of prerequisites (e.g., needing an existing subscription) or contextual cues for selection among sibling tools, leaving usage decisions ambiguous.

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 updates
    • First observedlist_watched
    • First observedsubscribe
    • First observedsubscribe_default
    • First observedunsubscribe

TDQS

A3.6/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a clearly distinct purpose with no overlap: list_watched for viewing current subscriptions, subscribe for adding new ones, subscribe_default for a specific default case, and unsubscribe for removal. The descriptions reinforce these distinct roles, making misselection unlikely.

Naming Consistency5/5

All tools follow a consistent verb_noun pattern (list_watched, subscribe, subscribe_default, unsubscribe) with clear, action-oriented names. The naming is uniform and predictable, enhancing usability.

Tool Count5/5

With 4 tools, this server is well-scoped for its purpose of monitoring file/directory changes. Each tool serves a necessary function in the subscription lifecycle, and the count is neither too sparse nor bloated.

Completeness5/5

The tool set provides complete coverage for the domain of file/directory monitoring: list (read), subscribe (create), unsubscribe (delete), and a specialized subscribe_default for convenience. There are no obvious gaps, supporting full agent workflows.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    A
    quality
    D
    maintenance
    A Model Context Protocol (MCP) server that enables AI assistants to perform comprehensive file operations including finding, reading, writing, editing, searching, moving, and copying files with security validations.
    7
    1
    -
  • A
    license
    Not graded
    quality
    C
    maintenance
    A secure file server for AI assistants that provides comprehensive file operations and text manipulation with configurable access levels and multiple connection modes.
    6
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A secure, sandboxed file system server that enables reading, writing, searching, and managing files through MCP-compatible AI clients with path traversal protection and size limits.
    -