File Context MCP

hybrid server

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

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(モデルコンテキストプロセッサ)

概要

File Context MCPは、TypeScriptベースのアプリケーションで、ローカルファイルのコンテキストを用いて大規模言語モデル(LLM)をクエリするためのAPIを提供します。複数のLLMプロバイダー(OllamaとTogether.ai)をサポートし、様々なファイルタイプを処理してコンテキストに応じたレスポンスを生成できます。

コア機能

1. ファイルシステムナビゲーション

  • 動的なファイルとディレクトリのトラバーサル
  • 複数のファイル タイプ ( .txt.md.ts.jsonなど) のサポート
  • 衛生管理による安全な通路の確保
import path from 'path'; export const fileUtils = { isTextFile(filePath: string): boolean { const textExtensions = [ '.txt', '.md', '.js', '.ts', '.json', '.yaml', '.yml', '.html', '.css', '.csv', '.xml', '.log', '.env', '.jsx', '.tsx', '.py', '.java', '.cpp', '.c', '.h' ]; return textExtensions.includes(path.extname(filePath).toLowerCase()); },

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. マルチモデルサポート

  • Ollama(ローカル)統合
  • 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
  • Web ファイル: .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」を持つフォームデータを使用し、テキストファイルを選択します。
    • クエリファイル: 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」を選択します
    • タイプ「File」のキー「file」を追加します。
    • サポートされているテキストファイルを選択します(サポートされているファイルの種類を参照)
    • 最大ファイルサイズ: 5MB

手動テスト

  • /storageに用意されているテストファイルを使用する
  • さまざまなファイルタイプとクエリをテストする
  • モデルの応答とエラー処理を検証する
  • テストファイルのサイズ制限と種類の制限

環境設定

必ず次の点に注意してください:

  • サーバーを実行しておきます( npm run dev
  • 環境変数を設定する
  • Ollamaをローカルで実行する(Ollamaモデルの場合)
  • Together.ai APIキーを設定する(Togetherモデル用)

今後の検討事項

  1. 大きなファイルを効率的に処理する方法
  2. サポートされるファイルタイプの拡張
  3. コンテキスト処理の最適化
  4. レスポンスのストリーミングサポートの追加
  5. レート制限とキャッシュの実装

このプロジェクトは、モジュール性、型の安全性、エラー処理に重点を置いた最新の TypeScript/Node.js プラクティスを示し、ファイルベースのコンテキストとの LLM 対話のための柔軟なインターフェースを提供します。

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

このサーバーは、ローカル ファイルのコンテキストを使用して大規模言語モデルをクエリするための 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
              ID: cllpbhp6yy