Skip to main content
Glama
file-insight-mcp

file-insight-mcp

by jm333-B

File Analysis MCP (file-insight-mcp)

A personal local MCP server that reads unstructured documents in a specified folder, analyzes their structure, and writes per-document summaries and a folder-wide summary report.

All documents in this package's data/sample_docs/ are synthetic data created for demo purposes.

References

Related MCP server: file-analyzer

What this server does

  1. Scans the structure of a fixed target folder (data/sample_docs/).

  2. Reads only documents with allowed extensions (.txt .md .csv .log).

  3. Extracts table of contents (heading structure), dates, numbers, and key term candidates from documents using rule-based logic.

  4. Builds a combined summary prompt from all documents. The summary itself is written by the host LLM (Claude/Codex); this MCP does not call any LLM API.

  5. Validates the structure of the written summary report and cross-checks that mentioned filenames actually exist.

  6. Saves the report to a file only after the user explicitly approves.

Quick start

Required environment: Python 3.11 or later, uv

uv sync --extra dev

After installation, verify that all four commands in the Verification section below pass.

To visually inspect the tools with MCP Inspector:

uv run mcp dev src/file_insight_mcp/server.py

Project structure

Domain logic and tool conventions are separated so that changing validation rules does not require touching the tool layer.

Path

Role

src/file_insight_mcp/security.py

Path safety checks, extension allowlist, size and item count limits

src/file_insight_mcp/core.py

Folder scan, document reading, report structure validation, approval-based saving

src/file_insight_mcp/outline.py

Table of contents, date, number, and key term extraction (rule-based, deterministic)

src/file_insight_mcp/grounding.py

Cross-checking filenames mentioned in summaries (advisory check)

src/file_insight_mcp/harness.py

Common tool convention elements — NextAction, ToolFailure, truncation and line numbers

src/file_insight_mcp/server.py

MCP tool, resource, and prompt registration (harness layer)

src/file_insight_mcp/evalkit.py

Pure logic for path expressions, verdicts, and variable substitution in eval cases

evals/cases.jsonl

Deterministic regression cases (data, not code)

scripts/run_evals.py

Runner that executes cases over the actual MCP protocol

scripts/smoke_stdio.py

STDIO startup, schema, and harness convention smoke test

scripts/validate_package.py

Pre-release static checks (credentials, dangerous calls, tool annotations)

tests/

Domain function unit tests (run without starting the server)

SCAN → LIST → READ → EXTRACT → DRAFT → CHECK → PREVIEW → [사용자 승인] → SAVED

Step

Tool

Read/Write

Role

SCAN

scan_folder_structure

Read

Target folder structure, per-extension counts, allowed status

LIST

list_target_documents

Read

List of documents that can actually be read

READ

read_document_chunk

Read

View source text. Supports line range specification and L14 citation anchors

EXTRACT

extract_document_outline

Read

Extract table of contents (heading/numbering) structure

EXTRACT

extract_key_terms

Read

Extract key term candidates based on dates, numbers, and frequency

DRAFT

build_summary_prompt

Read

Generate a prompt combining all documents + the standard report format

CHECK

validate_report_draft

Read

Structure validation. Provides rule_id·severity·line·fix (save gate)

CHECK

check_summary_grounding

Read

Cross-check that filenames mentioned in the summary actually exist (advisory, does not block saving)

PREVIEW

diff_report_against_saved

Read

Check differences against the previously saved version

PREVIEW

preview_save_report

Read

Shows validation and diff together and issues an approval token

SAVED

save_approved_report

Write

Saves only when the approval token matches (the only write tool)

OBSERVE

list_saved_reports

Read

List of saved reports

OBSERVE

read_report_audit_log

Read

View the save audit log

Resources and prompts

Type

URI or name

Role

Resource

document://{relative_path}

Document source text

Resource

report://{report_id}

Saved summary report

Prompt

analyze_folder

Analysis workflow from scan to save approval

Harness design

This server treats not only functionality but also the way the model uses tools as a design target.

  • Every response includes stage and next_actions, so the model can choose the next tool from the response alone. blocking: true is a guidance hint meaning "do not skip this step." What actually blocks saving is structure validation and the approval token; the hint does not take over that role.

  • Errors are returned as ToolFailure with a cause code, recovery method, and selectable values. The goal is to let the model recover on its own without asking again.

  • Argument schemas are kept flat ({"relative_path": "..."}). Using Pydantic models as argument types would nest them as {"params": {...}} and change the call shape.

  • Return values are Pydantic models, so outputSchema is generated automatically.

  • Every tool has readOnlyHint / destructiveHint so the host can show a different approval UI for write tools.

  • Only certain checks (structure) block saving; heuristic checks (filename cross-check) are reported as warnings only.

Context budget

Following the principle that "the context window is not a dumping ground but a working-memory budget," every tool has an explicit cap on response size.

  • scan_folder_structure: If MAX_SCAN_ENTRIES (500) is exceeded, it reports truncated: true and truncates.

  • read_document: Files larger than MAX_FILE_BYTES (200KB) are not read in full; instead, an error guides the caller to read only part of the file via read_document_chunk.

  • extract_key_terms: Limits the number of items per category with max_terms.

  • preview_save_report: include_preview=False is the default, so a draft the model already has is not included in the response again. When it must be included, max_preview_chars limits the length.

  • harness.truncate() / harness.number_lines(): Always makes truncation status and citation anchors (line numbers) explicit so the model does not have to guess whether "this is the whole thing or part of it."

Safety boundaries

  • The server only handles security.TARGET_DIR (data/sample_docs/). It cannot access anything outside that directory via .., absolute paths, drive letters, or symbolic links (security.safe_relative_path).

  • Files outside the extension allowlist (.txt .md .csv .log) are not read. Executable/script extensions are always excluded from targets.

  • If a file exceeds MAX_FILE_BYTES (200KB), it is not read in full; an error guides the caller instead.

  • Hidden files and folders whose names start with . are excluded from scanning.

  • The only write tool is save_approved_report, which works only when the (report_id, body) hash token issued by preview_save_report matches.

  • This server only reads documents. If code or shell execution calls such as eval/exec/subprocess appear in the source, scripts/validate_package.py fails.

Verification

uv run pytest -q
uv run python scripts/smoke_stdio.py
uv run python scripts/run_evals.py
uv run python scripts/validate_package.py

The four commands each check different things, so all of them must pass.

Command

Scope of checks

Server startup

pytest -q

core·outline·grounding·security·evalkit domain functions

No

smoke_stdio.py

Tool registration, schema flatness, annotations, error message conventions

Yes

run_evals.py

Deterministic regression cases in evals/cases.jsonl

Yes

validate_package.py

Static checks for credential leaks, dangerous calls, tool annotations

No

run_evals.py includes the full save flow, covering whether saving succeeds or is rejected when the approval token is correct or incorrect. Whenever you fix a bug, add one line to evals/cases.jsonl with a case that reproduces that bug. See evals/README.md for the case syntax.

If you want to analyze a different folder

For safety, this project fixes the target folder to TARGET_DIR in src/file_insight_mcp/security.py (the data/sample_docs/ inside the package). To analyze a real work folder:

  1. Change TARGET_DIR to the desired absolute path, or modify it to be injected via an environment variable.

  2. Reflect the extensions that actually exist in that folder in ALLOWED_EXTENSIONS.

  3. First check that there are no sensitive subfolders (credentials, personal information, etc.).

Claude Desktop connection

Replace ABSOLUTE_PROJECT_PATH in config/claude_desktop_config.example.json with the absolute path of this folder, then apply it to the Claude Desktop configuration. You must fully quit the app and relaunch it.

Design principles

  • The MCP does not call any separate LLM API. Claude or Codex writes the summary sentences; this MCP handles the source text, structure, validation, and saving.

  • It never fabricates filenames, numbers, or dates not confirmed in the documents; the grounding checker mechanically cross-checks them.

  • Final saving requires both the approval token issued at preview and the user's explicit approval.

  • Domain logic (core, outline, grounding) is separated from tool conventions (server, harness, security).

Available Tools

13 tools
build_summary_promptA
Read-onlyIdempotent

대상 폴더의 모든 문서와 표준 보고서 형식을 결합한 요약 프롬프트를 반환합니다.

이 MCP는 LLM API를 호출하지 않습니다. 요약은 호스트(Claude/Codex)가 하고, 이 도구는 '무엇을 어떤 형식으로 쓸지'에 대한 지시문과 원문 전체를 조립합니다.

Args: with_line_numbers: 원문 줄 번호 부착 및 인용 규칙 추가 여부 (기본 True).

Returns: PromptResponse: prompt에 규칙 + 필수 섹션 + 문서 목록 + 원문이 담긴 지시문.

Inputs: with_line_numbers. Returns: stage, prompt, status, target_dir, +2 more

check_summary_groundingA
Read-onlyIdempotent

보고서에 언급된 파일명이 현재 폴더 스캔 결과에 실제로 있는지 대조합니다.

"문서에 없는 파일을 만들어 내지 않는다"는 규칙을 사람 눈 대신 기계가 확인합니다.

중요: 이 검사는 자문(advisory) 입니다. 휴리스틱이므로 오탐이 있을 수 있고, 저장을 막지 않습니다. 저장 게이트는 validate_report_draft(구조)와 사용자 승인입니다.

Args: report_markdown: 요약 보고서 초안 전문.

Returns: GroundingResponse: status(GROUNDED / MOSTLY_GROUNDED / NEEDS_EVIDENCE_REVIEW), score(0-100), findings[].

Inputs: report_markdown (required). Returns: score, stage, status, checked, +4 more

diff_report_against_savedA
Read-onlyIdempotent

이미 저장된 보고서와 초안의 차이를 보여 줍니다.

같은 report_id로 두 번째 저장을 하면 기존 파일을 덮어씁니다. 무엇이 사라지는지 먼저 확인해 사고를 막는 용도입니다.

Args: report_id: 보고서 id. report_markdown: 초안 전문. diff_preview_lines: unified diff 미리보기 줄 수 (기본 40).

Returns: DiffResponse: diff.write_mode가 CREATE / OVERWRITE / NO_CHANGE 중 하나.

Inputs: report_id (required), report_markdown (required), diff_preview_lines. Returns: diff, stage, status, target, +2 more

extract_document_outlineA
Read-onlyIdempotent

마크다운 헤딩, 번호 매김 항목, 전부 대문자 줄을 목차 후보로 추출합니다.

비정형 문서는 형식이 제각각이므로 규칙 기반 휴리스틱 세 가지를 함께 사용합니다. 결과에는 원문 줄 번호가 함께 담겨 근거로 쓸 수 있습니다.

Args: relative_path: 문서 상대 경로.

Returns: OutlineResponse: outline[]에 level, title, line이 담깁니다.

Inputs: relative_path (required). Returns: stage, status, outline, entry_count, +2 more

extract_key_termsA
Read-onlyIdempotent

문서에서 날짜, 단위가 붙은 수치, 빈도 기반 핵심 용어 후보를 뽑습니다.

통계적 NLP가 아니라 정규식과 빈도 계산만 쓰는 결정적(deterministic) 추출이므로, 같은 문서에는 항상 같은 결과가 나옵니다.

Args: relative_path: 문서 상대 경로. max_terms: 분류별 최대 항목 수 (기본 20).

Returns: KeyTermsResponse: dates, numbers에 줄 번호와 원문이, frequent_terms에 용어·빈도가 담깁니다.

Inputs: relative_path (required), max_terms. Returns: dates, stage, status, numbers, +3 more

list_saved_reportsA
Read-onlyIdempotent

이미 저장된 요약 보고서 목록을 조회합니다.

같은 report_id로 저장하면 덮어쓰기가 되므로, 저장 전에 무엇이 있는지 확인하는 용도입니다.

Returns: SavedListResponse: saved[]에 report_id, 경로, 줄 수, 수정 시각(UTC), 내용 해시 앞 16자.

Inputs: no named parameters. Returns: count, saved, stage, status, +1 more

list_target_documentsA
Read-onlyIdempotent

확장자·크기 제한을 통과한, 실제로 읽고 요약할 수 있는 문서 목록을 돌려줍니다.

여기서 얻은 relative_path를 다른 모든 도구에 그대로 넘깁니다.

Returns: DocumentListResponse: documents[]에 relative_path, 크기, 줄 수, 수정 시각이 담깁니다.

Inputs: no named parameters. Returns: count, stage, status, documents, +1 more

preview_save_reportA
Read-onlyIdempotent

저장 대상·변경 내용·검증 결과를 한 번에 보여 주고 승인 토큰을 발급합니다.

저장 직전의 단일 관문입니다. 구조 검증을 통과했을 때만 approval_token이 발급되며, 토큰은 (report_id, 본문) 해시라서 승인받은 내용과 저장되는 내용이 달라질 수 없습니다.

토큰은 사용자 승인을 대신하지 않습니다. 응답의 approval_request를 사용자에게 그대로 보여 주고, 사용자가 명시적으로 승인한 뒤에만 save_approved_report를 호출하세요.

Args: report_id: 보고서 id. report_markdown: 저장할 보고서 전문. include_preview: 전문을 응답에 다시 담을지 여부 (기본 False). max_preview_chars: preview 최대 길이 (기본 4000).

Returns: PreviewResponse: status(AWAITING_APPROVAL / NEEDS_REVISION), approval_token, validation, diff, approval_request.

Inputs: report_id (required), report_markdown (required), include_preview, max_preview_chars. Returns: diff, stage, status, target, +7 more

read_document_chunkA
Read-onlyIdempotent

relative_path에 해당하는 문서 원문을 읽습니다.

긴 문서를 통째로 읽어 컨텍스트를 낭비하지 않도록 줄 범위를 지정할 수 있습니다.

Args: relative_path: 문서 상대 경로. start_line: 시작 줄(1부터). 기본 1. end_line: 끝 줄. 생략하면 끝까지. with_line_numbers: 줄 번호 접두사 부착 여부. 기본 True.

Returns: DocumentChunkResponse: content에 본문, total_lines에 전체 줄 수, truncated에 일부만 읽었는지 여부.

Raises: ToolFailure: DOCUMENT_NOT_FOUND / INVALID_PATH. 오류 메시지에 사용 가능한 relative_path 목록이 함께 담깁니다.

Inputs: relative_path (required), end_line, start_line, with_line_numbers. Returns: stage, status, content, end_line, +5 more

read_report_audit_logA
Read-onlyIdempotent

보고서 저장 감사 로그를 최신순으로 조회합니다.

AWAITING_APPROVAL → SAVED 흐름의 실행 증거를 확인할 때 사용합니다.

Args: limit: 최대 건수 (기본 20). report_id: 특정 보고서로 필터링 (선택).

Returns: AuditResponse: events[] 최신순.

Inputs: limit, report_id. Returns: count, stage, events, status, +1 more

save_approved_reportA
DestructiveIdempotent

미리보기에서 발급된 승인 토큰이 일치할 때만 보고서를 파일로 저장합니다.

이 서버에서 유일한 쓰기 도구입니다. 호출 전 반드시 두 조건을 만족해야 합니다.

  1. preview_save_report가 AWAITING_APPROVAL을 돌려주고 토큰을 발급했다.

  2. 사용자가 그 내용을 보고 명시적으로 저장을 승인했다.

토큰은 기술적 무결성(승인한 내용 == 저장되는 내용)만 보장합니다. 사용자 승인을 대신하지 않습니다. 사용자가 "저장해"라고 말하지 않았다면 호출하지 마세요.

Args: report_id: 보고서 id. report_markdown: 저장할 보고서 전문. approval_token: 미리보기가 발급한 토큰. expected_write_mode: 선택. 지정하면 실제 write_mode와 다를 때 거부합니다.

Returns: SaveResponse: path(저장 경로), audit(감사 로그 경로), write_mode(CREATE / OVERWRITE / NO_CHANGE).

Raises: ToolFailure: TOKEN_MISMATCH, VALIDATION_FAILED, WRITE_MODE_CHANGED, INVALID_REPORT_ID. 모두 복구 방법이 메시지에 포함됩니다.

Inputs: report_id (required), approval_token (required), report_markdown (required), expected_write_mode. Returns: path, audit, stage, status, +3 more

scan_folder_structureA
Read-onlyIdempotent

서버에 고정된 대상 폴더를 재귀적으로 훑어 파일 구조를 돌려줍니다.

폴더 분석의 출발점입니다. 각 항목의 allowed가 false이면 확장자 또는 크기 제한 때문에 다른 도구로 읽을 수 없다는 뜻이며, reason에 이유가 담깁니다.

Returns: ScanResponse: entries[]에 상대 경로·확장자·크기·수정 시각·허용 여부가 담기고, extension_counts에 확장자별 개수, truncated에 항목 수 제한으로 일부만 담겼는지 여부가 담깁니다.

Examples: - 사용: "이 폴더에 어떤 파일들이 있나요?" - 사용하지 않음: 이미 대상 파일을 알고 있고 원문이 필요할 때 → read_document_chunk

Inputs: no named parameters. Returns: stage, status, entries, max_depth, +6 more

validate_report_draftA
Read-onlyIdempotent

요약 보고서 초안의 구조를 검사합니다. 저장 게이트입니다.

error가 하나라도 있으면 preview_save_report에서 승인 토큰이 발급되지 않습니다.

검사 항목: - error: H1 제목, 필수 섹션 5개(폴더 개요/파일 구조/문서별 요약/주요 키워드/확인 필요 사항) - warning: 섹션 순서, 자리표시자 잔존, 대상 폴더 표기 누락, 문서 경로 인용 누락

Args: report_markdown: 요약 보고서 초안 전문.

Returns: ValidationResponse: valid, error_count, warning_count, issues[](rule_id/severity/message/fix/line).

Inputs: report_markdown (required). Returns: stage, valid, issues, status, +3 more

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 13 tools

    Disambiguation5/5

    Each tool has a distinct role in the workflow: scanning, listing readable docs, reading chunks, extracting outlines/terms, building prompts, validating structure, checking grounding, diffing, previewing, saving, listing saved reports, and reading audit logs. The only potential overlap is scan_folder_structure vs list_target_documents, but their purposes are clearly differentiated (full scan vs. actionable document list). No ambiguity in selection.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern in snake_case (scan_folder_structure, read_document_chunk, extract_key_terms, validate_report_draft, list_saved_reports). Verbs are descriptive and parallel (scan/list/read/extract/build/validate/check/diff/preview/save). No mixed conventions or chaotic naming.

    Tool Count5/5

    13 tools is within the ideal 3-15 range. Each tool supports a specific stage of a coherent workflow (folder analysis → report generation → validation → approval → save → audit). No redundant or trivial tools; the count feels well-scoped for the server's purpose.

    Completeness4/5

    The workflow covers scanning, extraction, prompt building, structural validation, grounding checks, diff, preview, save, list, and audit. The only notable gap is the lack of a tool to read a previously saved report's full content directly (e.g., read_saved_report), though diff_report_against_saved provides partial visibility. This is a minor gap that agents can work around via diff or by reading original documents.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables real-time indexing and semantic search of local documents (PDF, Word, text, Markdown, RTF) using vector embeddings and local LLMs. Monitors folders for changes and provides natural language search capabilities through Claude Desktop integration.
      22
      MIT
    • F
      license
      A
      quality
      C
      maintenance
      Enables read-only analysis of local unstructured documents by scanning a folder, extracting text and structural metadata, and passing content with truncation and error-awareness to an LLM for summarization.
      9
      1
      -
    • A
      license
      A
      quality
      C
      maintenance
      Enables reading and extracting text from local documents (PDF, Word, Excel, PowerPoint, HWP, Markdown, CSV, etc.) without network access, and provides approval-gated summary saving and file organization.
      11
      MIT