Persistent logging for MCP server with backup and improved file handling in Windows 10
The Model Context Protocol (MCP) is a universal adapter that facilitates seamless connections between AI applications and various data sources or tools, akin to how USB-C connects diverse devices. The "Win-10-MCP-Server---Simple-persistant-logging" server acts as an intermediary, enabling MCP clients such as Claude Desktop, Continue, and Cursor to interact with local file systems for persistent logging and backup management.
This MCP server introduces a unique feature through the logger.mjs
and modified index.js
, enhancing file handling by ensuring data integrity during backup operations. Specifically, this server addresses the issue where the write operation for files might be incomplete or corrupted due to user inactivity or system errors.
The architecture of this server aligns closely with the MCP protocol specifications, ensuring seamless integration and broad client support. The following Mermaid diagram illustrates the core interaction flow between the AI application, MCP client, and the file system.
graph TD
A[AI Application] -->|MCP Client| B[MCP Server]
B --> C[MCP Protocol]
C --> D[File System]
style A fill:#e1f5fe
style C fill:#f3e5f5
style D fill:#e8f5e8
The compatibility matrix below highlights the support for various MCP clients, demonstrating broad applicability across different AI tool ecosystems.
MCP Client | Resources | Tools | Prompts |
---|---|---|---|
Claude Desktop | ✅ | ✅ | ✅ |
Continue | ✅ | ✅ | ✅ |
Cursor | ❌ | ✅ | ❌ |
To get started, follow these steps to install and configure the "Win-10-MCP-Server---Simple-persistant-logging" server:
Ensure you have Node.js installed on your system. You can install the required dependencies by running:
npm install @modelcontextprotocol/server-filesystem
logger.mjs
Create a new file named logger.mjs
in your project root to handle logging:
// logger.mjs
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const LOG_DIR = path.join(__dirname, "logs");
async function ensureLogDir() {
try {
await fs.mkdir(LOG_DIR, { recursive: true });
} catch (err) {
console.error("Failed to create logs directory:", err);
}
}
ensureLogDir();
const LOG_FILE = path.join(LOG_DIR, "KAN_server.log");
export async function logToFile(level, message) {
const timestamp = new Date().toISOString();
const line = `[${level.toUpperCase()}] ${timestamp} - ${message}\n`;
try {
await fs.appendFile(LOG_FILE, line);
} catch (err) {
console.error("Failed to write to log file:", err);
}
}
index.js
Apply the necessary modifications to index.js
within the server-filesystem/dist
directory to ensure robust file handling:
// index.js
async function handleOperation(operation, args) {
switch (operation) {
case "write_file": {
try {
const parsed = WriteFileArgsSchema.safeParse(args);
if (!parsed.success) {
throw new Error(`Invalid arguments for write_file: ${parsed.error}`);
}
const validPath = await validatePath(parsed.data.path);
let backupName = null;
try {
await fs.access(validPath);
const now = new Date();
const mm = String(now.getMonth() + 1).padStart(2, '0');
const dd = String(now.getDate()).padStart(2, '0');
const yy = String(now.getFullYear()).slice(-2);
const hh = String(now.getHours()).padStart(2, '0');
const mn = String(now.getMinutes()).padStart(2, '0');
const dateString = `${mm}${dd}${yy}_${hh}_${mn}`;
const dirName = path.dirname(validPath);
const backupName = `${path.basename(validPath)}.${dateString}__CLDBak`;
await fs.rename(validPath, path.join(dirName, backupName));
await logToFile("INFO", `Backup created at ${backupPath}`);
} catch (err) {
if (err.code !== 'ENOENT') {
await logToFile("ERROR", `Error accessing or backing up file: ${err.message}`);
throw err;
}
// File doesn't exist; proceed without backup
await logToFile("INFO", `No existing file at ${validPath}. No backup created.`);
}
await fs.writeFile(validPath, parsed.data.content, "utf-8");
await logToFile("INFO", `Successfully wrote to ${validPath}`);
const responseText = `Successfully wrote to ${parsed.data.path}`;
if (backupName) {
responseText += `\nKAN: Backup saved to ${backupName}`;
}
const response = {
content: [{
type: "text",
text: responseText,
}],
};
return response;
} catch (error) {
await logToFile("ERROR", `write_file operation failed: ${error.message}`);
throw error;
}
}
}
}
This server is particularly useful for real-world applications where continuous monitoring of logs and data integrity are critical. For instance, in healthcare AI systems that process patient records, persistent logging ensures that any tampering or unauthorized modifications can be traced.
In financial services, this server could be integrated into regulatory compliance tools to ensure data is handled responsibly. By maintaining detailed logs, potential security breaches can be identified and addressed promptly.
The implementation supports integration with multiple MCP clients, including:
Client | Resources | Tools | Prompts |
---|---|---|---|
Claude Desktop | ✅ | ✅ | ✅ |
Continue | ✅ | ✅ | ✅ |
Cursor | ❌ | ✅ | ❌ |
How does the server handle large file transfers?
Can I switch between different MCP clients easily?
logger.mjs
and index.js
can be adapted to support various MCP clients based on their specific requirements.What happens if there is a network outage while writing a file?
How do I customize logging levels and formats?
logger.mjs
by modifying the logToFile()
function parameters or adding additional options as needed.Is there a way to integrate automated backups beyond just file writes?
index.js
. This ensures continuous data protection and reduces manual intervention.Here's an example of how the MCP configuration would look:
{
"mcpServers": {
"Win-10-MCP-Server---Simple-persistant-logging": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"env": {
"API_KEY": "your-api-key"
}
}
}
}
This document covers the essential features and operations of the "Win-10-MCP-Server---Simple-persistant-logging" server, emphasizing its role in enhancing AI application integration and data integrity. The content aligns with technical accuracy, MCP protocol specifications, and broad client support, ensuring a comprehensive guide for developers building complex AI ecosystems.
By implementing this enhanced file handling mechanism through the "Win-10-MCP-Server---Simple-persistant-logging" server, developers can significantly improve their AI applications' reliability and robustness, ensuring consistent and accurate data usage across various environments.
RuinedFooocus is a local AI image generator and chatbot image server for seamless creative control
Learn to set up MCP Airflow Database server for efficient database interactions and querying airflow data
Simplify MySQL queries with Java-based MysqlMcpServer for easy standard input-output communication
Build stunning one-page websites track engagement create QR codes monetize content easily with Acalytica
Access NASA APIs for space data, images, asteroids, weather, and exoplanets via MCP integration
Explore CoRT MCP server for advanced self-arguing AI with multi-LLM inference and enhanced evaluation methods