import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
class FileSystemMCPServer {
constructor() {
this.server = new Server(
{ name: 'filesystem-server', version: '1.0.0' },
{ capabilities: { tools: {} } }
);
this.setupTools();
}
setupTools() {
// Register file reading tool
this.server.setRequestHandler('tools/list', async () => ({
tools: [
{
name: 'read_file',
description: 'Read contents of a file',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string', description: 'File path to read' }
},
required: ['path']
}
},
{
name: 'write_file',
description: 'Write content to a file',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string', description: 'File path to write' },
content: { type: 'string', description: 'Content to write' }
},
required: ['path', 'content']
}
}
]
}));
// Handle tool execution
this.server.setRequestHandler('tools/call', async (request) => {
const { name, arguments: args } = request.params;
switch (name) {
case 'read_file':
return await this.readFile(args.path);
case 'write_file':
return await this.writeFile(args.path, args.content);
default:
throw new Error(`Unknown tool: ${name}`);
}
});
}
async readFile(path) {
try {
const fs = await import('fs/promises');
const content = await fs.readFile(path, 'utf-8');
return {
content: [{
type: 'text',
text: `File content from ${path}:\n${content}`
}]
};
} catch (error) {
return {
content: [{
type: 'text',
text: `Error reading file: ${error.message}`
}],
isError: true
};
}
}
async writeFile(path, content) {
try {
const fs = await import('fs/promises');
await fs.writeFile(path, content, 'utf-8');
return {
content: [{
type: 'text',
text: `Successfully wrote content to ${path}`
}]
};
} catch (error) {
return {
content: [{
type: 'text',
text: `Error writing file: ${error.message}`
}],
isError: true
};
}
}
async start() {
const transport = new StdioServerTransport();
await this.server.connect(transport);
}
}
// Start the server
const server = new FileSystemMCPServer();
server.start().catch(console.error);