File Context MCP

Integrations

  • Uses Express.js to implement a REST API server with endpoints for file operations and LLM queries.

  • Implemented as a Node.js application for server-side functionality.

  • Integrates with Ollama as a local LLM provider for context-aware querying. Allows users to send prompts to Ollama models with context from local files.

파일 컨텍스트 MCP(모델 컨텍스트 프로세서)

개요

파일 컨텍스트 MCP는 로컬 파일의 컨텍스트를 사용하여 대용량 언어 모델(LLM)을 쿼리하는 API를 제공하는 TypeScript 기반 애플리케이션입니다. 여러 LLM 공급자(Ollama 및 Together.ai)를 지원하며, 다양한 파일 유형을 처리하여 컨텍스트 인식 응답을 생성할 수 있습니다.

핵심 기능

1. 파일 시스템 탐색

  • 동적 파일 및 디렉토리 탐색
  • 다양한 파일 형식 지원( .txt , .md , .ts , .json 등)
  • 살균을 통한 안전한 경로 처리

지엑스피1

2. 컨텍스트 처리

  • LLM 쿼리에 대한 지능형 컨텍스트 포맷팅
  • 대용량 파일을 처리하기 위한 컨텍스트 잘림
  • 디렉토리 쿼리를 위한 파일 콘텐츠 집계
export const promptUtils = { formatContextPrompt(context: string, query: string): string { return ` You are an AI assistant analyzing the following content: ---BEGIN CONTEXT--- ${context} ---END CONTEXT--- Please respond to the following query: ${query} Base your response only on the information provided in the context above. `; }, truncateContext(context: string, maxLength: number = 4000): string { if (context.length <= maxLength) return context; // Try to truncate at a natural break point const truncated = context.slice(0, maxLength); const lastNewline = truncated.lastIndexOf('\n'); if (lastNewline > maxLength * 0.8) { return truncated.slice(0, lastNewline) + '\n... (truncated)'; } return truncated + '... (truncated)'; } };

3. 다중 모델 지원

  • 올라마(지역) 통합
  • Together.ai(클라우드) 통합
  • 확장 가능한 모델 인터페이스 디자인
export interface LLMResponse { text: string; model: string; error?: string; } export class ModelInterface { async queryOllama(prompt: string, context: string): Promise<LLMResponse> { try { const response = await axios.post(`${config.ollamaBaseUrl}/api/generate`, { model: config.modelName, prompt: this.formatPrompt(prompt, context), stream: false }); return { if (!response.data || !response.data.response) { throw new Error('Invalid response from Ollama'); } } catch (error) { return { text: response.data.response, model: 'ollama' }; } catch (error) { console.error('Ollama error:', error); return { text: '', model: 'ollama', error: error instanceof Error ? error.message : 'Unknown error' }; } } model: config.modelName, async queryTogether(prompt: string, context: string): Promise<LLMResponse> { try { const response = await axios.post( 'https://api.together.xyz/inference', { model: config.modelName, prompt: this.formatPrompt(prompt, context), max_tokens: 512, }, { headers: { Authorization: `Bearer ${config.togetherApiKey}` } } ); return { return { text: response.data.output.text, model: 'together' }; } catch (error) { return { text: '', model: 'together', error: error instanceof Error ? error.message : 'Unknown error' }; } } private formatPrompt(prompt: string, context: string): string { return `Context: ${context}\n\nQuestion: ${prompt}`; } }

건축학

핵심 구성 요소

  1. 서버(server.ts)
    • Express.js REST API 구현
    • Multer를 사용한 파일 업로드/삭제 처리
    • 요청 검증 및 라우팅
    • OpenAPI/Swagger 통합
  2. 파일 시스템 도구(core/fileSystem.ts)
    • 파일 및 디렉토리 작업
    • 콘텐츠 읽기 및 구문 분석
    • 디렉토리 탐색
    • 안전한 파일 삭제
    • 파일 작업에 대한 오류 처리
  3. 모델인터페이스(core/modelInterface.ts)
    • 여러 LLM 공급자 지원(Ollama, Together.ai)
    • 응답 형식 및 오류 처리
    • 구성 가능한 모델 매개변수
    • 통합 쿼리 인터페이스
  4. 유틸리티 모듈
    • fileUtils : 파일 유형 감지, 경로 정리, 크기 포맷팅
    • promptUtils : 컨텍스트 포맷팅, 지능형 잘라내기
    • validators : 경로, 쿼리 및 모델 검증
    • logger : 레벨이 있는 구조화된 로깅
  5. 구성(config/config.ts)
    • 환경 변수 관리
    • API 키 및 엔드포인트
    • 모델 구성
    • 서버 설정
  6. API 사양(resources/file-context-api.yml)
    • OpenAPI 3.0 문서
    • 요청/응답 스키마
    • 엔드포인트 문서
    • 오류 응답 정의

API 엔드포인트

1. 파일 목록

GET /api/files Query params: - path: string (optional, defaults to './') Response: - Array of FileInfo objects with file/directory details

2. 파일 업로드

POST /api/files/upload Content-Type: multipart/form-data Body: - file: File (must be a text file, max 5MB) Response: { "message": "File uploaded successfully", "file": { "name": string, "size": string, "path": string } }

3. 파일 삭제

DELETE /api/files/{filename} Params: - filename: string (name of file to delete) Response: { "message": "File deleted successfully" }

4. 컨텍스트를 사용한 쿼리

POST /api/query Body: { "path": string, "query": string, "model": "ollama" | "together" } Response: { "text": string, "model": string, "error?: string }

설정 및 구성

  1. 환경 변수
TOGETHER_API_KEY=your_api_key_here OLLAMA_BASE_URL=http://localhost:11434 MODEL_NAME=llama2 PORT=3001
  1. 설치
npm install

Smithery를 통해 설치

Smithery를 통해 Claude Desktop용 File Context MCP를 자동으로 설치하려면:

npx @smithery/cli@latest install @compiledwithproblems/file-context-mcp --client claude
  1. 애플리케이션 실행
# Development npm run dev # Production npm run build npm start

작동 원리

  1. 파일 처리 흐름
    • 요청 수신 → 경로 검증 → 파일 읽기 → 콘텐츠 추출
    • 디렉토리 처리에는 재귀적 파일 읽기가 포함됩니다.
    • 파일 유형에 따른 콘텐츠 필터링
    • 파일 업로드는 유형 및 크기에 대해 검증됩니다.
    • 경로 검증을 통한 안전한 파일 삭제
  2. 컨텍스트 처리
    • 파일 내용이 집계됩니다
    • 컨텍스트는 명확한 경계로 포맷됩니다.
    • 대규모 컨텍스트는 지능적으로 잘립니다.
    • 신속한 서식은 LLM 이해에 구조를 추가합니다.
  3. 모델 통합
    • 다양한 LLM 공급자를 위한 통합 인터페이스
    • 오류 처리 및 응답 정규화
    • 구성 가능한 모델 매개변수

보안 기능

  1. 경로 살균
    • 디렉토리 트래버설 공격 방지
    • 경로 검증 및 정규화
    • 안전한 파일 유형 검사
  2. 파일 업로드 보안
    • 파일 유형 검증
    • 파일 크기 제한(최대 5MB)
    • 안전한 파일 저장
    • 안전한 파일 삭제
  3. 입력 검증
    • 쿼리 콘텐츠 검증
    • 모델 유형 검증
    • 경로 구조 검증
    • 파일 내용 검증

지원되는 파일 유형

이 애플리케이션은 다음과 같은 텍스트 기반 파일 형식을 지원합니다.

  • 문서: .txt , .md
  • 코드 파일: .js , .ts , .jsx , .tsx , .py , .java , .cpp , .c , .h
  • 구성: .json , .yaml , .yml , .env
  • 웹 파일: .html , .css
  • 데이터 파일: .csv , .xml , .log

파일 유형 유효성 검사는 다음 경우에 적용됩니다.

  • 파일 업로드
  • 컨텍스트 처리
  • 파일 읽기 작업

최대 파일 크기: 파일당 5MB

오류 처리

이 애플리케이션은 포괄적인 오류 처리를 구현합니다.

  • 파일 시스템 오류
  • API 응답 오류
  • 잘못된 입력 오류
  • 모델별 오류
  • 파일 업로드/삭제 오류

개발

프로젝트 구조

file-context-mcp/ ├── src/ │ ├── server.ts # Main application server │ ├── core/ # Core functionality │ │ ├── fileSystem.ts # File operations handling │ │ └── modelInterface.ts # LLM provider integrations │ ├── utils/ # Utility functions │ │ ├── fileUtils.ts # File type & path utilities │ │ ├── promptUtils.ts # Prompt formatting │ │ ├── validators.ts # Input validation │ │ └── logger.ts # Application logging │ ├── config/ # Configuration │ │ └── config.ts # Environment & app config │ └── resources/ # API specifications │ └── file-context-api.yml # OpenAPI spec ├── storage/ # File storage directory │ ├── code-samples/ # Example code files │ └── notes/ # Documentation & notes ├── postman/ # API testing │ └── File-Context-MCP.postman_collection.json # Postman collection ├── dist/ # Compiled output └── node_modules/ # Dependencies

새로운 기능 추가

  1. 새로운 파일 유형
    • fileUtils.isTextFile() 에 확장자를 추가합니다.
    • 필요한 경우 특정 핸들러를 구현합니다.
  2. 새로운 모델 제공업체
    • ModelInterface 클래스 확장
    • validators.isValidModel() 에 공급자를 추가합니다.
    • 공급자별 오류 처리 구현

테스트

우편 배달부 컬렉션

이 프로젝트에는 모든 API 엔드포인트를 테스트하기 위한 Postman 컬렉션( postman/File-Context-MCP.postman_collection.json )이 포함되어 있습니다. 사용 방법은 다음과 같습니다.

  1. 컬렉션 가져오기
    • 오픈 포스트맨
    • "가져오기" 버튼을 클릭하세요
    • File-Context-MCP.postman_collection.json 파일을 선택하거나 드래그합니다.
  2. 사용 가능한 요청
    File-Context-MCP ├── List files │ └── GET http://localhost:3001/api/files?path=./storage ├── Query │ └── POST http://localhost:3001/api/query (single file analysis) ├── Analyze multiple files │ └── POST http://localhost:3001/api/query (directory analysis) └── File Upload └── POST http://localhost:3001/api/files/upload
  3. 파일 작업 테스트
    • 파일 목록 : 저장 디렉토리의 내용을 봅니다.
    • 파일 업로드 : "file" 키를 사용하여 form-data를 사용하고 텍스트 파일을 선택하세요.
    • 쿼리 파일 : LLM을 사용하여 단일 파일 콘텐츠 분석
    • 디렉토리 분석 : LLM을 사용하여 여러 파일 처리
  4. 예제 쿼리
    // Single file analysis { "path": "./storage/code-samples/example.ts", "query": "Explain what this TypeScript code does", "model": "ollama" } // Directory analysis { "path": "./storage", "query": "What types of files are in this directory and summarize their contents?", "model": "ollama" }
  5. 파일 업로드 가이드
    • "파일 업로드" 요청을 사용하세요
    • 본문 탭에서 "form-data"를 선택하세요
    • "파일" 유형으로 "파일" 키를 추가합니다.
    • 지원되는 텍스트 파일을 선택하세요(지원되는 파일 유형 참조)
    • 최대 파일 크기: 5MB

수동 테스트

  • /storage 에 제공된 테스트 파일을 사용하세요.
  • 다양한 파일 유형 및 쿼리 테스트
  • 모델 응답 및 오류 처리 확인
  • 테스트 파일 크기 제한 및 유형 제한

환경 설정

다음 사항을 확인하세요.

  • 서버를 실행하세요( npm run dev )
  • 환경 변수 구성
  • Ollama를 로컬로 실행하세요(Ollama 모델의 경우)
  • Together.ai API 키 설정(Together 모델용)

향후 고려 사항

  1. 대용량 파일을 효율적으로 처리하는 방법
  2. 지원되는 파일 유형 확장
  3. 컨텍스트 처리 최적화
  4. 응답에 대한 스트리밍 지원 추가
  5. 속도 제한 및 캐싱 구현

이 프로젝트는 파일 기반 컨텍스트에서 LLM 상호 작용을 위한 유연한 인터페이스를 제공하는 동시에 모듈성, 유형 안전성 및 오류 처리에 중점을 둔 최신 TypeScript/Node.js 방식을 보여줍니다.

-
security - not tested
F
license - not found
-
quality - not tested

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

이 서버는 로컬 파일의 컨텍스트를 사용하여 대규모 언어 모델을 쿼리하는 API를 제공하며, 컨텍스트 인식 응답을 위한 다양한 모델과 파일 유형을 지원합니다.

  1. Overview
    1. Core Features
      1. 1. File System Navigation
      2. 2. Context Processing
      3. 3. Multi-Model Support
    2. Architecture
      1. Core Components
    3. API Endpoints
      1. 1. List Files
      2. 2. Upload File
      3. 3. Delete File
      4. 4. Query with Context
    4. Setup and Configuration
      1. Installing via Smithery
    5. How It Works
      1. Security Features
        1. Supported File Types
          1. Error Handling
            1. Development
              1. Project Structure
              2. Adding New Features
            2. Testing
              1. Postman Collection
              2. Manual Testing
              3. Environment Setup
            3. Future Considerations

              Related MCP Servers

              • -
                security
                F
                license
                -
                quality
                A server that enables Large Language Models to discover and interact with REST APIs defined by OpenAPI specifications through the Model Context Protocol.
                Last updated -
                74
                32
                JavaScript
                • Apple
              • -
                security
                A
                license
                -
                quality
                A Model Context Protocol server that enables Large Language Models to seamlessly interact with ClickHouse databases, supporting resource listing, schema retrieval, and query execution.
                Last updated -
                1
                Python
                MIT License
                • Linux
                • Apple
              • -
                security
                A
                license
                -
                quality
                A Model Context Protocol server that enables Large Language Models to interact with ClickUp workspace tasks and data, allowing creation and retrieval of tasks through natural language.
                Last updated -
                59
                TypeScript
                MIT License
                • Apple
              • A
                security
                F
                license
                A
                quality
                A Model Context Protocol server that enables large language models to interact with Apache Superset databases through REST API, supporting database queries, table lookups, field information retrieval, and SQL execution.
                Last updated -
                4
                3
                TypeScript

              View all related MCP servers

              ID: cllpbhp6yy