Skip to main content
Glama
hesreallyhim

MCP Observer Server

by hesreallyhim

mcp-наблюдатель-сервер

mcp-observer-server — это сервер MCP (Model Context Protocol), который отслеживает события файловой системы и предоставляет уведомления в реальном времени клиентам MCP. Он действует как (более двунаправленный) мост между вашей локальной файловой системой и помощниками ИИ, такими как Клод Inspector, позволяющий автоматически реагировать на изменения файлов.

ПРИМЕЧАНИЕ: Это демонстрация/POC сервера MCP для мониторинга файлов, над которым я работаю. Я вижу много вопросов/комментариев/проблем/обсуждений по этому поводу, поэтому я хотел бы опубликовать эту минимальную реализацию, чтобы поделиться своим подходом.

Контекст

Протокол MCP определяет понятие подписки на ресурс, в котором клиент может запросить уведомление о любых изменениях в ресурсе, а сервер может выбрать отправку уведомлений. Вот схема потока:

Диаграмма потока подписки на ресурсы

Протокол говорит, что клиент должен затем отправить запрос на чтение обратно на сервер, чтобы прочитать изменения. (Все это, кстати, необязательно). Но я нахожу это немного громоздким и подразумевающим дополнительный запрос, и я бы предпочел, чтобы мое уведомление об обновлении ресурсов также описывало изменение. К счастью, SDK предлагает поле meta / _meta , и вы можете отправить практически все, что захотите. Так что я могу захотеть отправить количество измененных строк, разницу изменений, кто знает что. Я не реализовал это в этой демонстрации, сейчас я просто отправляю временную метку. (Я в основном вырвал все с сервера, кроме минимального POC.) Кроме того, он просто работает на транспорте stdio, ничего особенного.

ПРИМЕЧАНИЕ!!! Я пока не тестировал это ни с одним "реальным" клиентом MCP - насколько я понимаю, клиенты view на самом деле поддерживают подписку на ресурсы, поскольку это в любом случае необязательно. Однако, к счастью, Inspector - очень хороший клиент, и вы можете использовать его для тестирования этого сервера.

ДЕМО-ИНСТРУКЦИИ:

  1. Клонируйте репозиторий.

  2. Установите зависимости с помощью uv (или, я полагаю, каким-то другим способом).

  3. Запустите сервер с помощью make start (использует uv ) или выполните npx @modelcontextprotocol/inspector uv run src/mcp_observer_server/server.py .

  4. Откройте клиент Inspector и подключитесь с помощью stdio, настройка не требуется.

  5. Используйте инструмент subscribe для мониторинга каталога или файла (или запустите «Список ресурсов», щелкните ресурс, а затем нажмите кнопку «Подписаться», чтобы подписаться на него).

  6. По умолчанию сервер выставит файл с именем watched.txt в src/mcp_observer_server/watched.txt (файл .gitignored, поэтому его нужно создать), но вы можете подписаться и на другие файлы. Вы можете подписаться на этот файл с помощью инструмента subscribe_default .

  7. Измените файл watched.txt (или любой другой файл, на который вы подписались), и вы должны увидеть уведомление сервера в нижней правой панели Inspector. Это установленный POC.

Related MCP server: File MCP Server

ДЕМО-ВИЗУАЛИЗАЦИЯ

  1. Запустите сервер и подключитесь с помощью Inspector: Запустить сервер и подключиться

  2. Список ресурсов по умолчанию: Список ресурсов

  3. Перечислите инструменты:Список инструментов

  4. Подписаться на файл по умолчанию: Подписаться на файл по умолчанию

  5. Измените файл:Изменить файл

  6. Появляется уведомление: Смотреть уведомление

🎉

Описание сервера

MCP Observer Server отслеживает изменения файлов и каталогов в вашей системе, позволяя клиентам MCP подписываться на эти события и предпринимать действия при создании, изменении, удалении или перемещении файлов (текущая демонстрация обрабатывает событие изменения). Этот сервер реализует полную спецификацию Model Context Protocol, предоставляя:

  • Мониторинг файлов в реальном времени : использование библиотеки Watchdog для эффективного наблюдения за файловой системой

  • Управление подписками : создание, перечисление и отмена подписок на мониторинг для любого пути.

  • История изменений : ведет журнал последних изменений для каждой подписки (в демоверсии отсутствует)

  • Доступ к файлам и каталогам : чтение содержимого файлов и списков каталогов через ресурсы MCP.

  • Дизайн без сохранения состояния : клиенты контролируют, что происходит в ответ на изменения файлов

Основные характеристики

  • Подпишитесь на изменения в определенных файлах, каталогах или целых репозиториях

  • Фильтрация событий по шаблонам файлов или типам событий (в демоверсии отсутствует)

  • Запросить последние изменения, чтобы узнать, какие файлы были затронуты (в демоверсии пропущено)

  • Доступ к содержимому файла через конечные точки ресурсов

  • Легкая и эффективная реализация с минимальными зависимостями

  • Простая интеграция с любым MCP-совместимым клиентом (...поддерживающий подписку на ресурсы)

Практические применения

Основная проблема, которую я пытаюсь решить, заключается в том, что если Claude Code, например, не коснется файла и не запишет в него изменения, он не будет знать, что происходит в вашем репозитории/проекте. (Вы знаете эти уведомления — «Файл изменен с момента последнего чтения»?) Наличие клиента или помощника по кодированию, который фактически отслеживает то, что вы делаете в своем проекте, и вам не нужно делегировать каждую задачу Claude, просто чтобы он знал, что это происходит, кажется мне чрезвычайно полезным. Некоторые практические приложения включают:

  • Автоматизированные обновления документации : синхронизируйте документацию с изменениями кода — вы обновляете код, Клод уведомляется об изменении, и он заблаговременно проверяет или обновляет строки документации и т. д.

  • Обзоры кода в реальном времени : получайте обратную связь в режиме реального времени об изменениях кода по мере работы, выявляйте орфографические ошибки, ошибки ввода и т. д., давайте советы, настоящее парное программирование.

  • Автоматизация тестирования : запуск тестов при изменении соответствующих файлов.

  • Помощь ИИ : включите инструменты ИИ для автоматического реагирования на изменения файлов.

  • Автоматизация коммитов Git : Вы забываете делать коммиты достаточно часто? Клод может следить за вашими изменениями и предлагать (или выполнять) действия по коммиту чаще.

Текущая реализация проекта

Реализация сервера отличается оптимизированной архитектурой, в которой приоритет отдается простоте, надежности и удобству обслуживания.

Архитектурные особенности

  1. Упрощенная структура

    • Целенаправленная реализация (~170 строк кода)

    • Объединение функциональности в небольшой набор основных компонентов

    • Чистый функциональный дизайн, напрямую использующий MCP SDK

    • Высокая читаемость и удобство обслуживания

  2. Эффективное государственное управление

    • Простая структура словаря отображает пути к клиентским сеансам

    • Использует watched словарь для прямого сопоставления пути к сеансу

    • Минимальное отслеживание состояния с понятным потоком данных

    • Избегает избыточных структур данных

  3. Интеграция протокола MCP

    • Прямое использование декораторов функций MCP SDK

    • Чистая обработка URI ресурса

    • Упрощенная инициализация сервера с правильной настройкой возможностей

    • Система прямой доставки уведомлений

  4. Обработка событий

    • Оптимизированная реализация обработчика событий Watchdog

    • Прямой путь от события к уведомлению

    • Потокобезопасная связь через call_soon_threadsafe

    • Эффективная фильтрация событий

  5. Система оповещения

    • Прямое использование примитивов уведомлений MCP

    • Надежная доставка с правильной обработкой ошибок

    • Точная обработка временных меток UTC

    • Чистое форматирование URI

Основные компоненты

  1. Структура данных

    • Единый глобальный словарь watched сопоставление объектов Path с наборами объектов ServerSession

    • Каждая запись пути содержит набор сеансов, подписанных на этот путь.

  2. API-интерфейс инструмента

    • Два основных инструмента: subscribe и unsubscribe

    • Простой параметр пути для простого управления подпиской

    • Чистая обработка ошибок и проверка пути

  3. Обработка ресурсов

    • Файловые URI, напрямую отображаемые через список ресурсов

    • Разрешение и проверка пути

    • Чтение текстового содержимого файлов

  4. Обработка событий

    • Класс Watcher расширяет FileSystemEventHandler

    • Обрабатывает измененные события напрямую

    • Потокобезопасная отправка уведомлений

    • Обработка относительности пути для вложенных путей

  5. Доставка уведомлений

    • Создание и отправка ServerNotification

    • Метаданные событий с временными метками

    • Чистое форматирование URI

Реализация обеспечивает хороший баланс между функциональностью и простотой, что приводит к созданию надежной и удобной в обслуживании кодовой базы.

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. Dates show when Glama detected each change.

  1. 4 tool updates
    • First observedlist_watched
    • First observedsubscribe
    • First observedsubscribe_default
    • First observedunsubscribe

TDQS

A3.6/5.0
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
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

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.
    -

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/hesreallyhim/mcp-observer-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server