### Run setup script Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Prints a platform-specific setup guide for the local environment. ```bash ./setup-llm.sh ``` -------------------------------- ### Launch llama-server Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Start the server with specific performance and model parameters. ```powershell cd C:\llama.cpp # or the nested subfolder from Step 2 .\llama-server.exe ` -m ~/models/Qwen3.6-35B-A3B-UD-IQ4_XS.gguf ` --alias llm-model ` -c 98304 ` -n 32768 ` -ngl 99 ` --n-cpu-moe 14 ` -fa on ` --no-mmap ` --mlock ` -b 2048 -ub 512 ` --cache-type-k q8_0 --cache-type-v q8_0 ` --swa-full ` --no-context-shift ` --ctx-checkpoints 128 ` --checkpoint-every-n-tokens 4096 ` --cache-ram 4096 ` --jinja ` --reasoning-format deepseek ` --reasoning-budget 4096 ` --chat-template-kwargs '{"preserve_thinking":true}' ` --temp 0.6 ` --top-p 0.95 ` --top-k 20 ` --min-p 0.0 ` --presence-penalty 0.0 ` --repeat-penalty 1.0 ` --host 0.0.0.0 --port 8880 ` --metrics ` -np 1 ``` -------------------------------- ### Build and Start Nexus Dashboard Source: https://github.com/admica/filescopemcp/blob/main/README.md Commands to build the Nexus API and UI, then launch the dashboard server. ```bash npm run build:nexus # one-time build (API + UI) npm run nexus # starts at http://localhost:1234 ``` -------------------------------- ### Install LLM Monitoring Source: https://github.com/admica/filescopemcp/blob/main/README.md Sets up the VictoriaMetrics and vmui stack for monitoring local LLM performance. ```bash sudo ./monitoring/install.sh ``` -------------------------------- ### Apply Default Linux-native Configuration Source: https://github.com/admica/filescopemcp/blob/main/AGENTS.md Use the default template for setups where the agent and llama-server reside on the same Ubuntu host. ```bash cp broker.default.json ~/.filescope/broker.json ``` -------------------------------- ### Install Claude Code Integration Source: https://github.com/admica/filescopemcp/blob/main/README.md Adds project priming and optional hook templates for Claude Code. ```bash npm run install-claude-code # or: npx filescope-install --claude-code ``` -------------------------------- ### Install llama.cpp on macOS Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Installs the llama.cpp package using Homebrew with default Metal backend support. ```bash brew install llama.cpp ``` -------------------------------- ### Configure Broker JSON Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Example configuration for an OpenAI-compatible LLM provider. Replace YOUR_SERVER_IP with the actual remote machine address. ```json { "llm": { "provider": "openai-compatible", "model": "llm-model", "baseURL": "http://YOUR_SERVER_IP:8880/v1", "maxTokensPerCall": 1024 }, "jobTimeoutMs": 120000, "maxQueueSize": 1000 } ``` -------------------------------- ### Manage Multi-Repo Watchers Source: https://github.com/admica/filescopemcp/blob/main/README.md Commands to install, check status, and uninstall systemd user units for continuous repository watching. ```bash ./scripts/nexus.sh install-watchers # writes the unit, enables it, starts it systemctl --user status filescope-watchers.service ./scripts/nexus.sh uninstall-watchers # symmetric removal ``` -------------------------------- ### Initialize and Start FileWatcher Source: https://github.com/admica/filescopemcp/blob/main/coverage/file-watcher.ts.html Configures chokidar watch options and attaches event listeners for file additions, changes, and deletions. ```typescript console.error('FileWatcher: Already running'); return; } const watchOptions: chokidar.WatchOptions = { ignored: this.getIgnoredPatterns(), ignoreInitial: true, persistent: true, awaitWriteFinish: { stabilityThreshold: 300, pollInterval: 100 }, ignorePermissionErrors: true, depth: 99, // Maximum depth for directory traversal disableGlobbing: false, followSymlinks: false }; console.error(`FileWatcher: Starting on ${this.baseDir}`); try { this.watcher = chokidar.watch(this.baseDir, watchOptions); // Setup event handlers if watching is enabled for those events if (this.config.watchForNewFiles) { this.watcher.on('add', (filePath) => this.onFileEvent(filePath, 'add')); } if (this.config.watchForChanged) { this.watcher.on('change', (filePath) => this.onFileEvent(filePath, 'change')); } if (this.config.watchForDeleted) { this.watcher.on('unlink', (filePath) => this.onFileEvent(filePath, 'unlink')); } // Handle errors this.watcher.on('error', (error) => { console.error(`FileWatcher: Error:`, error); this.errorCount++; // If too many errors, try restarting the watcher if (this.errorCount > 10) { console.error('FileWatcher: Too many errors, restarting...'); this.restart(); } }); // Setup ready event this.watcher.on('ready', () => { console.error('FileWatcher: Initial scan complete. Ready for changes.'); }); this.isWatching = true; console.error('FileWatcher: Started successfully'); } catch (error) { console.error('FileWatcher: Error starting:', error); } } ``` -------------------------------- ### FileWatcher Implementation Source: https://github.com/admica/filescopemcp/blob/main/coverage/file-watcher.ts.html The FileWatcher class manages file system monitoring using chokidar, including configuration, base directory setup, and event callback management. ```typescript import * as chokidar from 'chokidar'; import * as path from 'path'; import { FileWatchingConfig } from './types.js'; import { getConfig, getProjectRoot } from './global-state.js'; import { normalizePath } from './file-utils.js'; /** * Types of file events that the watcher can emit */ export type FileEventType = 'add' | 'change' | 'unlink'; /** * Callback function type for file events */ export type FileEventCallback = (filePath: string, eventType: FileEventType) => void; /** * File watcher class that monitors file system changes */ export class FileWatcher { private watcher: chokidar.FSWatcher | null = null; private config: FileWatchingConfig; private baseDir: string; private isWatching: boolean = false; private eventCallbacks: FileEventCallback[] = []; private throttleTimers: Map = new Map(); private errorCount: number = 0; /** * Create a new FileWatcher instance * @param config The file watching configuration * @param baseDir The base directory to watch */ constructor(config: FileWatchingConfig, baseDir: string) { this.config = config; this.baseDir = path.normalize(baseDir); console.error(`FileWatcher: Initialized with base directory: ${this.baseDir}`); } /** * Start watching for file changes */ public start(): void { if (this.isWatching) { ``` -------------------------------- ### Initialize Broker Configuration Directory Source: https://github.com/admica/filescopemcp/blob/main/AGENTS.md Create the configuration directory and copy the default template to the user's home folder. ```bash mkdir -p ~/.filescope cp broker.default.json ~/.filescope/broker.json ``` -------------------------------- ### Initialize Broker Configuration Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Sets up the local configuration directory and copies the remote LAN broker template. ```bash mkdir -p ~/.filescope cp ~/FileScopeMCP/broker.remote-lan.json ~/.filescope/broker.json ``` -------------------------------- ### Get File Importance Source: https://github.com/admica/filescopemcp/blob/main/coverage/file-utils.ts.html Retrieves a specific node from the file tree by matching the target path. ```typescript export function getFileImportance(fileTree: FileNode, targetPath: string): FileNode | null { const normalizedInputPath = normalizePath(targetPath); log(`Looking for file: ${normalizedInputPath}`); function findNode(node: FileNode, targetPath: string): FileNode | null { // Normalize paths to handle both forward and backward slashes const normalizedTargetPath = path.normalize(targetPath).toLowerCase(); const normalizedNodePath = path.normalize(node.path).toLowerCase(); if (normalizedNodePath === normalizedTargetPath) { return node; } if (node.children) { for (const child of node.children) { const found = findNode(child, targetPath); if (found) return found; } } return null; } return findNode(fileTree, normalizedInputPath); } ``` -------------------------------- ### Build and Run Scripts Source: https://github.com/admica/filescopemcp/blob/main/AGENTS.md Standard commands for building the project and launching the application. ```bash ./build.sh # npm install + tsc + register with Claude Code ./run.sh # launch manually (build.sh generates this) ``` -------------------------------- ### Initialize MCP Server and State Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Sets up the server environment, including logging, state variables, and debounce timers for file system events. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { ReadBuffer, deserializeMessage, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js"; import { z } from "zod"; import * as fs from "fs/promises"; import * as path from "path"; import { FileNode, ToolResponse, FileTreeConfig, FileTreeStorage, MermaidDiagramConfig, FileWatchingConfig } from "./types.js"; import { scanDirectory, calculateImportance, setFileImportance, buildDependentMap, normalizePath, addFileNode, removeFileNode, excludeAndRemoveFile } from "./file-utils.js"; import { createFileTreeConfig, saveFileTree, loadFileTree, listSavedFileTrees, updateFileNode, getFileNode, normalizeAndResolvePath } from "./storage-utils.js"; import * as fsSync from "fs"; import { MermaidGenerator } from "./mermaid-generator.js"; import { setProjectRoot, getProjectRoot, setConfig, getConfig } from './global-state.js'; import { loadConfig, saveConfig } from './config-utils.js'; import { FileWatcher, FileEventType } from './file-watcher.js'; import { log, enableFileLogging } from './logger.js'; // Enable file logging for debugging enableFileLogging(false, 'mcp-debug.log'); // Initialize server state let fileTree: FileNode | null = null; let currentConfig: FileTreeConfig | null = null; let DEFAULT_CONFIG: FileTreeConfig; let fileWatcher: FileWatcher | null = null; // Map to hold debounce timers for file events const fileEventDebounceTimers: Map = new Map(); const DEBOUNCE_DURATION_MS = 2000; // 2 seconds // Check if we're running as an MCP server for Cursor ``` -------------------------------- ### Clone and Build FileScopeMCP Source: https://github.com/admica/filescopemcp/blob/main/README.md Initializes the project and registers the MCP server globally. ```bash git clone https://github.com/admica/FileScopeMCP.git cd FileScopeMCP ./build.sh # installs deps, compiles, registers with Claude Code ``` -------------------------------- ### Get File Importance Tool Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Retrieves the importance ranking and dependency data for a specific file path. ```typescript server.tool("get_file_importance", "Get the importance ranking of a specific file", { filepath: z.string().describe("The path to the file to check") }, async (params: { filepath: string }) => { log('Get file importance called with params: ' + JSON.stringify(params)); log('Current config: ' + JSON.stringify(currentConfig)); log('File tree root path: ' + fileTree?.path); try { if (!fileTree || !currentConfig) { log('No file tree loaded, building default tree'); await buildFileTree(DEFAULT_CONFIG); } const normalizedPath = normalizePath(params.filepath); log('Normalized path: ' + normalizedPath); const node = findNode(fileTree!, normalizedPath); log('Found node: ' + JSON.stringify(node ? { path: node.path, importance: node.importance, dependencies: node.dependencies?.length, dependents: node.dependents?.length } : null)); if (!node) { return createMcpResponse(`File not found: ${params.filepath}`, true); } return createMcpResponse({ path: node.path, importance: node.importance || 0, dependencies: node.dependencies || [], dependents: node.dependents || [], summary: node.summary || null }); } catch (error) { log('Error in get_file_importance: ' + error); return createMcpResponse(`Failed to get file importance: ` + error, true); } }); ``` -------------------------------- ### Understand module structure Source: https://github.com/admica/filescopemcp/blob/main/skills/filescope-mcp/SKILL.md Explore module internals, dependencies, and architectural context. ```text get_file_summary("src/coordinator.ts") → summary, deps, dependents, exports find_callees("mainExportedFn") → what it calls internally get_communities("src/coordinator.ts") → its architectural neighborhood ``` -------------------------------- ### Claude Code Tool Usage Source: https://github.com/admica/filescopemcp/blob/main/README.md Example of tool calls available to the AI within a Claude Code session. ```text find_important_files(limit: 5) status() ``` -------------------------------- ### Configure Broker in WSL Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Set up the broker configuration file for the FileScopeMCP environment. ```bash mkdir -p ~/.filescope cp ~/FileScopeMCP/broker.windows-host.json ~/.filescope/broker.json ``` -------------------------------- ### Inspect Broker Configuration Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Displays the current broker configuration file content. ```bash cat ~/.filescope/broker.json ``` -------------------------------- ### View directory structure Source: https://github.com/admica/filescopemcp/blob/main/docs/configuration.md Overview of the file system layout for per-repository and global configuration files. ```text Per-repo (inside your project): .filescope/ config.json # Project config (optional) data.db # SQLite database data.db-wal # SQLite write-ahead log data.db-shm # SQLite shared memory instance.pid # Daemon PID lock file .filescope-daemon.log # Daemon log output, daemon mode only (project root) Global (shared across all projects): ~/.filescope/ broker.json # LLM broker config broker.sock # Unix domain socket (broker IPC) broker.pid # Broker PID file broker.log # Broker log output mcp-server.log # MCP server log (always; stderr is suppressed in MCP mode) stats.json # Per-repo token usage stats nexus.json # Nexus dashboard repo registry (multi-repo aggregation) watchers.log # scripts/watchers.mjs supervisor log (only when filescope-watchers.service is installed) watcher-logs/ # one log per repo child spawned by the supervisor ``` -------------------------------- ### Initialize MCP Server Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Initializes the server and connects it to the Stdio transport. ```typescript // Start the server (async () => { try { // Initialize server first await initializeServer(); // Connect to transport const transport = new StdioTransport(); await server.connect(transport); } catch (error) { log('Server error: ' + error); process.exit(1); } })(); ``` -------------------------------- ### Pretty Print Initialization Source: https://github.com/admica/filescopemcp/blob/main/coverage/logger.ts.html Initializes the code highlighting on page load. ```javascript window.onload = function () { prettyPrint(); }; ``` -------------------------------- ### File Tree Initialization Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Loads or builds the file tree based on provided configuration. ```typescript async function buildFileTree(config: FileTreeConfig): Promise { log('\n🌲 BUILD FILE TREE STARTED'); log('=========================================='); log('Building file tree with config: ' + JSON.stringify(config, null, 2)); log('Current working directory: ' + process.cwd()); log('Config in global state: ' + (getConfig() !== null ? 'āœ… YES' : 'āŒ NO')); if (getConfig()) { log('Global config exclude patterns count: ' + (getConfig()?.excludePatterns?.length || 0)); } // First try to load from file try { const savedTree = await loadFileTree(config.filename); if (savedTree) { // Use the saved tree if (!savedTree.fileTree) { log('āŒ Invalid file tree structure in saved file'); throw new Error('Invalid file tree structure'); } log('āœ… Using existing file tree from: ' + config.filename); log('Tree root path: ' + savedTree.fileTree.path); ``` -------------------------------- ### List Files Tool Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Returns a list of all files in the project with their importance rankings, initializing the tree if necessary. ```typescript server.tool("list_files", "List all files in the project with their importance rankings", async () => { if (!fileTree) { await buildFileTree(DEFAULT_CONFIG); } return createMcpResponse(fileTree); }); ``` -------------------------------- ### Configure SessionStart hook for FileScopeMCP Source: https://github.com/admica/filescopemcp/blob/main/docs/claude-code-hooks.md Add this configuration to .claude/settings.json to trigger an orientation digest when a session begins. ```json { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "node /absolute/path/to/FileScopeMCP/scripts/filescope-helper.mjs session-start" } ] } ] } } ``` -------------------------------- ### Build llama.cpp from source on Linux Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Compiles llama.cpp with GPU support for NVIDIA or AMD hardware. ```bash git clone https://github.com/ggml-org/llama.cpp cd llama.cpp # NVIDIA: cmake -B build -DGGML_CUDA=ON # AMD (Vulkan is the recommended backend — see WSL2 section for why): cmake -B build -DGGML_VULKAN=ON cmake --build build --config Release -j ``` -------------------------------- ### File Tree Initialization and Scanning Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Logic for loading or building a file tree, including dependency mapping and importance calculation. ```typescript log('Tree has children: ' + (savedTree.fileTree.children?.length || 0)); fileTree = savedTree.fileTree; currentConfig = savedTree.config; log('🌲 BUILD FILE TREE COMPLETED (loaded from file)'); log('==========================================\n'); return fileTree; } } catch (error) { log('āŒ Failed to load existing file tree: ' + error); // Continue to build new tree } // If not found or failed to load, build from scratch log('šŸ” Building new file tree for directory: ' + config.baseDirectory); // Verify config is in global state before scanning if (!getConfig()) { log('āš ļø WARNING: No config in global state, setting it now'); // Get the current config const currentConfig = await loadConfig(); // Set the global config setConfig(currentConfig); log('Config set in global state: ' + (getConfig() !== null ? 'āœ… YES' : 'āŒ NO')); if (getConfig()) { log('Global config exclude patterns count: ' + (getConfig()?.excludePatterns?.length || 0)); } } fileTree = await scanDirectory(config.baseDirectory); if (!fileTree.children || fileTree.children.length === 0) { log('āŒ Failed to scan directory - no children found'); throw new Error('Failed to scan directory'); } else { log(`āœ… Successfully scanned directory, found ${fileTree.children.length} top-level entries`); } log('šŸ“Š Building dependency map...'); buildDependentMap(fileTree); log('šŸ“ˆ Calculating importance values...'); calculateImportance(fileTree); // Save to disk log('šŸ’¾ Saving file tree to: ' + config.filename); try { await saveFileTree(config, fileTree); log('āœ… Successfully saved file tree'); currentConfig = config; } catch (error) { log('āŒ Failed to save file tree: ' + error); throw error; } log('🌲 BUILD FILE TREE COMPLETED (built from scratch)'); log('==========================================\n'); return fileTree; } ``` -------------------------------- ### scan_all Source: https://github.com/admica/filescopemcp/blob/main/skills/filescope-mcp/SKILL.md Queues files for LLM summarization. ```APIDOC ## scan_all(min_importance?, remaining_only?) ### Description Queues files for LLM summarization. ### Parameters - **min_importance** (number) - Optional - Minimum importance threshold. - **remaining_only** (boolean) - Optional - If true, skips already-summarized files. ``` -------------------------------- ### Run llama.cpp via Docker Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Deploys the llama-server using the official CUDA Docker image with specific performance tuning flags. ```bash docker run --gpus all -p 8880:8880 \ -v $HOME/models:/models \ ghcr.io/ggml-org/llama.cpp:server-cuda \ -m /models/Qwen3.6-35B-A3B-UD-IQ4_XS.gguf \ --alias llm-model -c 98304 -n 32768 -ngl 99 --n-cpu-moe 14 \ -fa on --no-mmap --mlock -b 2048 -ub 512 \ --cache-type-k q8_0 --cache-type-v q8_0 --swa-full \ --no-context-shift --ctx-checkpoints 128 --checkpoint-every-n-tokens 4096 \ --cache-ram 4096 --jinja --reasoning-format deepseek --reasoning-budget 4096 \ --host 0.0.0.0 --port 8880 ``` -------------------------------- ### Combine PreToolUse and SessionStart hooks Source: https://github.com/admica/filescopemcp/blob/main/docs/claude-code-hooks.md Merge both hook configurations into a single hooks object within .claude/settings.json. ```json { "hooks": { "PreToolUse": [ /* ... as above ... */ ], "SessionStart": [ /* ... as above ... */ ] } } ``` -------------------------------- ### Define per-project configuration Source: https://github.com/admica/filescopemcp/blob/main/docs/configuration.md Place this JSON in .filescope/config.json to manage project-specific settings and file watching behavior. ```json { "baseDirectory": "/path/to/your/project", "excludePatterns": [ "docs/generated/**", "*.csv" ], "fileWatching": { "enabled": true, "autoRebuildTree": true, "maxWatchedDirectories": 1000, "watchForNewFiles": true, "watchForDeleted": true, "watchForChanged": true }, "llm": { "enabled": true }, "version": "1.0.0" } ``` -------------------------------- ### Create File Tree Configuration Source: https://github.com/admica/filescopemcp/blob/main/coverage/storage-utils.ts.html Initializes a new configuration object for a file tree, ensuring the base directory exists and paths are normalized. ```typescript export async function createFileTreeConfig(filename: string, baseDirectory: string): Promise { console.error('Creating file tree config...'); console.error('Input filename:', filename); console.error('Input baseDirectory:', baseDirectory); // Handle special case for current directory if (baseDirectory === '.' || baseDirectory === './') { baseDirectory = getProjectRoot(); console.error('Resolved "." to project root:', baseDirectory); } // Normalize paths const normalizedBase = normalizeAndResolvePath(baseDirectory); console.error('Normalized base directory:', normalizedBase); // For the filename, we only want the basename, not the full path const basename = path.basename(filename); const cleanFilename = basename.endsWith('.json') ? basename : `${basename}.json`; console.error('Clean filename:', cleanFilename); // Ensure the base directory exists console.error('Creating base directory if needed:', normalizedBase); await ensureDirectoryExists(normalizedBase); const config = { filename: cleanFilename, baseDirectory: normalizedBase, projectRoot: getProjectRoot(), // Always use the global project root lastUpdated: new Date() }; console.error('Created config:', config); return config; } ``` -------------------------------- ### Apply WSL2 Windows Host Configuration Source: https://github.com/admica/filescopemcp/blob/main/AGENTS.md Use the Windows host template when running FileScopeMCP in WSL2 with the LLM server on the Windows host. ```bash cp broker.windows-host.json ~/.filescope/broker.json ``` -------------------------------- ### Ignore FileScope Files Source: https://github.com/admica/filescopemcp/blob/main/README.md Recommended entries for the project's .gitignore file. ```text .filescope/ .filescope-daemon.log ``` -------------------------------- ### Storage Utilities Imports and State Source: https://github.com/admica/filescopemcp/blob/main/coverage/storage-utils.ts.html Initializes the storage utilities with necessary file system modules and a global map for tracking loaded file trees. ```typescript import * as fs from 'fs/promises'; import * as path from 'path'; import * as fsSync from 'fs'; import { FileNode, FileTreeConfig, FileTreeStorage } from './types.js'; import { getProjectRoot } from './global-state.js'; // Keep a map of all loaded file trees const loadedTrees = new Map(); ``` -------------------------------- ### Select File Tree Tool Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Loads an existing file tree configuration from a specified JSON file. ```typescript server.tool("select_file_tree", "Select an existing file tree to work with", { filename: z.string().describe("Name of the JSON file containing the file tree") }, async (params: { filename: string }) => { const storage = await loadFileTree(params.filename); if (!storage) { return createMcpResponse(`File tree not found: ${params.filename}`, true); } fileTree = storage.fileTree; currentConfig = storage.config; return createMcpResponse({ message: `File tree loaded from ${params.filename}`, config: currentConfig }); }); ``` -------------------------------- ### MCP Server Configuration and Tool Registration Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Initializes the McpServer instance and registers tools for managing file tree configurations. ```typescript // Server implementation const serverInfo = { name: "FileScopeMCP", version: "1.0.0", description: "A tool for ranking files in your codebase by importance and providing summaries with dependency tracking" }; // Create the MCP server const server = new McpServer(serverInfo, { capabilities: { tools: { listChanged: true } } }); // Register tools server.tool("list_saved_trees", "List all saved file trees", async () => { const trees = await listSavedFileTrees(); return createMcpResponse(trees); }); server.tool("delete_file_tree", "Delete a file tree configuration", { filename: z.string().describe("Name of the JSON file to delete") }, async (params: { filename: string }) => { try { const normalizedPath = normalizeAndResolvePath(params.filename); await fs.unlink(normalizedPath); // Clear from memory if it's the current tree if (currentConfig?.filename === normalizedPath) { currentConfig = null; fileTree = null; } return createMcpResponse(`Successfully deleted ${normalizedPath}`); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') { return createMcpResponse(`File tree ${params.filename} does not exist`); } return createMcpResponse(`Failed to delete ${params.filename}: ` + error, true); } }); server.tool("create_file_tree", "Create or load a file tree configuration", { filename: z.string().describe("Name of the JSON file to store the file tree"), baseDirectory: z.string().describe("Base directory to scan for files") }, async (params: { filename: string, baseDirectory: string }) => { log('Create file tree called with params: ' + JSON.stringify(params)); log('Current working directory: ' + process.cwd()); try { // Ensure we're using paths relative to the current directory const relativeFilename = path.isAbsolute(params.filename) ? path.relative(process.cwd(), params.filename) : params.filename; log('Relative filename: ' + relativeFilename); // Handle special case for current directory let baseDir = params.baseDirectory; if (baseDir === '.' || baseDir === './') { baseDir = getProjectRoot(); // Use the project root instead of cwd log('Resolved "." to project root: ' + baseDir); } // Normalize the base directory relative to project root if not absolute if (!path.isAbsolute(baseDir)) { baseDir = path.join(getProjectRoot(), baseDir); log('Resolved relative base directory: ' + baseDir); } const config = await createFileTreeConfig(relativeFilename, baseDir); log('Created config: ' + JSON.stringify(config)); // Build the tree with the new config, not the default ``` -------------------------------- ### Global State Management Implementation Source: https://github.com/admica/filescopemcp/blob/main/coverage/global-state.ts.html Provides functions to set and retrieve the project root and configuration, with logic to merge custom exclusion patterns from a local JSON file. ```typescript import { Config } from './types.js'; import * as fs from 'fs'; import * as path from 'path'; // Global state management for the MCP server let _projectRoot: string = process.cwd(); // Default to current directory let _config: Config | null = null; export function setProjectRoot(root: string) { _projectRoot = root; console.error(`Global project root set to: ${_projectRoot}`); } export function getProjectRoot(): string { return _projectRoot; } export function setConfig(config: Config) { _config = config; console.error('Global config updated:', config); } export function getConfig(): Config | null { if (!_config) return null; try { const customExcludesPath = path.join(_projectRoot, 'FileScopeMCP-excludes.json'); if (fs.existsSync(customExcludesPath)) { const customExcludes = JSON.parse(fs.readFileSync(customExcludesPath, 'utf-8')); if (Array.isArray(customExcludes)) { _config.excludePatterns = [..._config.excludePatterns, ...customExcludes]; console.error('Custom excludes loaded:', customExcludes); } } } catch (error) { console.error('Error loading custom excludes:', error); } return _config; } export function addExclusionPattern(pattern: string): void { const customExcludesPath = path.join(_projectRoot, 'FileScopeMCP-excludes.json'); let customExcludes: string[] = []; try { if (fs.existsSync(customExcludesPath)) { customExcludes = JSON.parse(fs.readFileSync(customExcludesPath, 'utf-8')); } if (!customExcludes.includes(pattern)) { customExcludes.push(pattern); fs.writeFileSync(customExcludesPath, JSON.stringify(customExcludes, null, 2), 'utf-8'); console.error(`Added exclusion pattern to FileScopeMCP-excludes.json: ${pattern}`); } else { console.error(`Pattern already exists in FileScopeMCP-excludes.json: ${pattern}`); } } catch (error) { console.error('Error updating FileScopeMCP-excludes.json:', error); } } ``` -------------------------------- ### Configure .mcp.json for Repository Auto-Discovery Source: https://github.com/admica/filescopemcp/blob/main/docs/mcp-clients.md Configuration file format for enabling auto-discovery when opening the repository in Claude Code. ```json { "mcpServers": { "FileScopeMCP": { "command": "node", "args": ["dist/mcp-server.js"] } } } ``` -------------------------------- ### Configure FileScopeMCP for WSL to Windows cross-host Source: https://github.com/admica/filescopemcp/blob/main/docs/mcp-clients.md Manually add this configuration to the Windows-side .claude.json file to allow the Claude CLI to communicate with a WSL-based MCP server. ```json { "mcpServers": { "FileScopeMCP": { "command": "wsl", "args": ["-d", "Ubuntu-24.04", "/home/yourname/FileScopeMCP/run.sh", "--base-dir=${projectRoot}"], "transport": "stdio", "disabled": false, "alwaysAllow": [] } } } ``` -------------------------------- ### Test WSL to Windows Connectivity Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Checks the default route and attempts to reach the Windows host from WSL. ```bash ip route show default | awk '{print $3}' curl http://$(ip route show default | awk '{print $3}'):8880/v1/models ``` -------------------------------- ### Configure Hermes Agent Runtime Source: https://github.com/admica/filescopemcp/blob/main/README.md Registers the FileScopeMCP server in the Hermes configuration file. ```yaml mcp_servers: filescope: command: "node" args: ["/path/to/FileScopeMCP/dist/mcp-server.js"] timeout: 120 ``` -------------------------------- ### Define Configuration Interfaces Source: https://github.com/admica/filescopemcp/blob/main/coverage/types.ts.html Defines the structure for file watching settings and the main application configuration. ```typescript import { getProjectRoot } from './global-state.js'; // File watching configuration export interface FileWatchingConfig { enabled: boolean; // Master switch for file watching debounceMs: number; // Debounce time for file change events ignoreDotFiles: boolean; // Whether to ignore files/dirs starting with a dot autoRebuildTree: boolean; // Whether to auto-rebuild the tree on file changes maxWatchedDirectories: number; // Limit to prevent watching too many directories watchForNewFiles: boolean; // Watch for file additions watchForDeleted: boolean; // Watch for file deletions watchForChanged: boolean; // Watch for file modifications } // Configuration type for the application export interface Config { baseDirectory: string; excludePatterns: string[]; fileWatching?: FileWatchingConfig; version: string; } ``` -------------------------------- ### File Tree Configuration and Storage Source: https://github.com/admica/filescopemcp/blob/main/coverage/types.ts.html Classes for managing file tree storage settings and the tree structure itself. ```typescript export class FileTreeConfig { filename: string = 'default-tree.json'; // Safe default filename baseDirectory: string = getProjectRoot(); // Use project root as fallback projectRoot: string = getProjectRoot(); // Always use project root lastUpdated?: Date = new Date(); // Current time as default } ``` ```typescript export class FileTreeStorage { config: FileTreeConfig = new FileTreeConfig(); fileTree: FileNode = new FileNode(); } ``` -------------------------------- ### Determine Optimal Layout Strategy Source: https://github.com/admica/filescopemcp/blob/main/coverage/layout-engine.ts.html Analyzes graph metrics like width, depth, and density to return a recommended layout configuration for Mermaid diagrams. ```typescript export function determineOptimalLayout( nodes: FileNode[], groups: Map, config?: Partial ): LayoutStrategy { // Calculate graph metrics const metrics: LayoutMetrics = { width: calculateGraphWidth(nodes, groups), depth: calculateGraphDepth(nodes, groups), density: calculateDensity(nodes), clusters: groups.size }; // Start with default values const strategy: LayoutStrategy = { direction: 'TB', nodeSpacing: 50, rankSeparation: 50, autoRotate: true }; // Adjust based on metrics if (metrics.width > metrics.depth * 2) { // Wide graph: use top-to-bottom layout strategy.direction = 'TB'; strategy.nodeSpacing = Math.max(30, Math.min(80, 150 / metrics.width)); strategy.rankSeparation = Math.max(40, Math.min(100, 200 / metrics.depth)); } else if (metrics.depth > metrics.width * 1.5) { // Deep graph: use left-to-right layout strategy.direction = 'LR'; strategy.nodeSpacing = Math.max(40, Math.min(100, 200 / metrics.depth)); strategy.rankSeparation = Math.max(30, Math.min(80, 150 / metrics.width)); } else { // Balanced graph: use density to decide if (metrics.density > 2) { // Dense connections: use more space strategy.nodeSpacing = 70; strategy.rankSeparation = 70; } } // Override with any user-specified config if (config?.layout) { if (config.layout.direction) strategy.direction = config.layout.direction; if (config.layout.nodeSpacing) strategy.nodeSpacing = config.layout.nodeSpacing; if (config.layout.rankSpacing) strategy.rankSeparation = config.layout.rankSpacing; } return strategy; } ``` -------------------------------- ### Verify Connection from WSL Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Test the connection to the Windows-hosted llama-server from within WSL. ```bash curl http://$(ip route show default | awk '{print $3}'):8880/v1/models ``` -------------------------------- ### Configure Cursor AI MCP Servers Source: https://github.com/admica/filescopemcp/blob/main/docs/mcp-clients.md Manual configuration blocks for Cursor AI's .cursor/mcp.json, tailored for different operating systems. ```json { "mcpServers": { "FileScopeMCP": { "command": "node", "args": ["/path/to/FileScopeMCP/dist/mcp-server.js", "--base-dir=${projectRoot}"], "transport": "stdio" } } } ``` ```json { "mcpServers": { "FileScopeMCP": { "command": "node", "args": ["C:\\FileScopeMCP\\dist\\mcp-server.js", "--base-dir=${projectRoot}"], "transport": "stdio", "disabled": false, "alwaysAllow": [] } } } ``` ```json { "mcpServers": { "FileScopeMCP": { "command": "wsl", "args": ["-d", "Ubuntu-24.04", "/home/yourname/FileScopeMCP/run.sh", "--base-dir=${projectRoot}"], "transport": "stdio", "disabled": false, "alwaysAllow": [] } } } ``` -------------------------------- ### Set Base Directory at Runtime Source: https://github.com/admica/filescopemcp/blob/main/docs/mcp-clients.md Function call to change the analyzed directory while the MCP server is running. ```text set_base_directory(path: "/path/to/your/project") ``` -------------------------------- ### Define Broker Configuration Schema Source: https://github.com/admica/filescopemcp/blob/main/AGENTS.md The broker configuration file defines the LLM provider, model alias, base URL, and queue constraints. ```json { "llm": { "provider": "openai-compatible", "model": "llm-model", "baseURL": "http://localhost:8880/v1", "maxTokensPerCall": 1024 }, "jobTimeoutMs": 300000, "maxQueueSize": 1000 } ``` -------------------------------- ### Define custom ignore patterns Source: https://github.com/admica/filescopemcp/blob/main/docs/configuration.md Use gitignore syntax in a .filescopeignore file located in the project root to exclude specific files or directories. ```gitignore docs/api/ *.csv *.parquet tmp/ vendor/ ``` -------------------------------- ### Ensure Directory Existence Source: https://github.com/admica/filescopemcp/blob/main/coverage/storage-utils.ts.html Creates a directory at the specified path if it does not already exist, ignoring EEXIST errors. ```typescript async function ensureDirectoryExists(dirPath: string): Promise { try { await fs.mkdir(dirPath, { recursive: true }); } catch (error) { // EEXIST is fine - directory already exists if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { throw error; } } } ``` -------------------------------- ### Construct File Node and Log Summary Source: https://github.com/admica/filescopemcp/blob/main/coverage/file-utils.ts.html Creates a file node object and logs the directory scan results. ```typescript const fileNode: FileNode = { path: normalizedFullPath, name: entry.name, isDirectory: false, importance: calculateInitialImportance(normalizedFullPath, normalizedBaseDir), dependencies: dependencies, packageDependencies: packageDependencies, dependents: [], summary: undefined }; rootNode.children?.push(fileNode); } } // Log summary for this directory log(`\n šŸ“Š DIRECTORY SCAN SUMMARY for ${normalizedDirPath}:`); log(` - Total entries: ${entries.length}`); ``` -------------------------------- ### Analyze function callers and dependencies Source: https://github.com/admica/filescopemcp/blob/main/skills/filescope-mcp/SKILL.md Use these tools to identify function callers and inspect file dependencies. ```text find_callers("functionName") → list of callers get_file_summary("path/to/file") → see dependents with import lines ``` -------------------------------- ### Debug List All Files Tool Source: https://github.com/admica/filescopemcp/blob/main/coverage/mcp-server.ts.html Lists all file paths and basenames in the current file tree for debugging purposes. ```typescript server.tool("debug_list_all_files", "List all file paths in the current file tree", async () => { if (!fileTree) { await buildFileTree(DEFAULT_CONFIG); } // Get a flat list of all files const allFiles = getAllFileNodes(fileTree!); // Extract just the paths and basenames const fileDetails = allFiles.map(file => ({ path: file.path, basename: path.basename(file.path), importance: file.importance || 0 })); return createMcpResponse({ totalFiles: fileDetails.length, files: fileDetails }); }); ``` -------------------------------- ### Locate files for new features Source: https://github.com/admica/filescopemcp/blob/main/skills/filescope-mcp/SKILL.md Search by concept and identify high-traffic files to determine where to implement changes. ```text search("authentication middleware") → find related files by concept find_important_files(maxItems: 5) → see the highest-traffic files get_file_summary("likely-file.ts") → verify it's the right place ``` -------------------------------- ### List JSON files in directory Source: https://github.com/admica/filescopemcp/blob/main/coverage/storage-utils.ts.html Reads the current working directory and returns a list of JSON files formatted as text objects. ```typescript const files = await fs.readdir(process.cwd()); const jsonFiles = files.filter(file => file.endsWith('.json')); return jsonFiles.map(file => ({ type: 'text' as const, text: file })); } catch (error) { console.error('Error listing file trees:', error); return []; } } ``` -------------------------------- ### Configure Hermes Integration Source: https://github.com/admica/filescopemcp/blob/main/AGENTS.md Configuration block for the Hermes runtime, placed in ~/.hermes/config.yaml. ```yaml mcp_servers: filescope: command: "node" args: ["/path/to/FileScopeMCP/dist/mcp-server.js"] timeout: 120 connect_timeout: 60 ``` -------------------------------- ### Configure PreToolUse hook for FileScopeMCP Source: https://github.com/admica/filescopemcp/blob/main/docs/claude-code-hooks.md Add this configuration to .claude/settings.json to trigger the helper script before Read, Edit, or Write tool calls. ```json { "hooks": { "PreToolUse": [ { "matcher": "Read|Edit|Write", "hooks": [ { "type": "command", "command": "node /absolute/path/to/FileScopeMCP/scripts/filescope-helper.mjs pre-tool-use" } ] } ] } } ``` -------------------------------- ### Apply Remote LAN Configuration Source: https://github.com/admica/filescopemcp/blob/main/AGENTS.md Use the remote LAN template when the LLM server is hosted on a separate machine on the network. ```bash cp broker.remote-lan.json ~/.filescope/broker.json # then edit baseURL to "http://:8880/v1" ``` -------------------------------- ### Reset Broker Configuration Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Reverts the broker configuration to the Windows host template. ```bash cp ~/FileScopeMCP/broker.windows-host.json ~/.filescope/broker.json ``` -------------------------------- ### MermaidGenerator Configuration and Initialization Source: https://github.com/admica/filescopemcp/blob/main/coverage/mermaid-generator.ts.html Defines the node shape mapping and the constructor for initializing the MermaidGenerator with a file tree and optional configuration. ```typescript }, nodeShapes: { file: 'rect', // Rectangle for files directory: 'folder', // Folder shape for directories important: 'hexagon', // Hexagon for important files package: 'ellipse', // Ellipse for packages packageScope: 'stadium' // Stadium for package scopes } }; export class MermaidGenerator { private config: MermaidDiagramConfig; private fileTree: FileNode; private nodes: Map; // path -> nodeId private nodeInfo: Map; // nodeId -> info private edges: Map; // edgeKey -> edge info private edgeCount: number; private stats: MermaidDiagramStats; private style: MermaidDiagramStyle; private definedNodes: Set; // Set of node IDs that have been defined private packageScopes: Map>; // scope -> set of package names private packageScopeNodes: Map; // scope -> nodeId constructor(fileTree: FileNode, config?: Partial) { this.fileTree = fileTree; this.config = { style: config?.style || 'hybrid', maxDepth: config?.maxDepth || 3, minImportance: config?.minImportance || 0, showDependencies: config?.showDependencies ?? true, showPackageDeps: config?.showPackageDeps ?? false, packageGrouping: config?.packageGrouping ?? true, excludePackages: config?.excludePackages || [], includeOnlyPackages: config?.includeOnlyPackages || [], autoGroupThreshold: config?.autoGroupThreshold || 8, layout: { direction: config?.layout?.direction || 'TB', rankSpacing: config?.layout?.rankSpacing || 50, nodeSpacing: config?.layout?.nodeSpacing || 40 } }; this.style = DEFAULT_STYLE; this.nodes = new Map(); this.nodeInfo = new Map(); this.edges = new Map(); this.edgeCount = 0; this.definedNodes = new Set(); this.packageScopes = new Map(); this.packageScopeNodes = new Map(); this.stats = { nodeCount: 0, edgeCount: 0, maxDepth: 0, importantFiles: 0, circularDeps: 0, packageCount: 0, packageScopeCount: 0 }; } ``` -------------------------------- ### Configure Windows Firewall Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Create an inbound rule to allow traffic on port 8880 for the llama-server. ```powershell New-NetFirewallRule -DisplayName "llama-server 8880" ` -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8880 ``` -------------------------------- ### Manage systemd service Source: https://github.com/admica/filescopemcp/blob/main/docs/llm-setup.md Commands for registering and monitoring the llama-server as a systemd service on Linux. ```bash sudo ./setup-llm.sh --install-service ``` ```bash sudo journalctl -u llama-server -f ```