local-file-operation-mcp
Version:
本地文件操作 MCP 服务器:安全的读写、编辑、搜索、比较、哈希、权限、压缩、监控、命令与任务管理工具集。
98 lines (83 loc) • 2.42 kB
JavaScript
/**
* 命令执行工具模块
* 支持安全的本地命令执行
*/
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
class CommandExecutionTool {
constructor(securityValidator) {
this.securityValidator = securityValidator;
}
async handle(args) {
const { command, working_directory, confirm = false } = args;
// 检查工作目录是否被允许
if (working_directory && !this.securityValidator.isPathAllowed(working_directory)) {
return {
content: [
{
type: 'text',
text: `错误: 不允许在工作目录 ${working_directory} 中执行命令`
}
]
};
}
// 检查命令是否包含危险/高危操作
const alwaysForbidden = ['passwd'];
if (alwaysForbidden.some(token => command.includes(token))) {
return {
content: [
{
type: 'text',
text: `错误: 绝对禁止执行命令: ${command}`
}
]
};
}
const highRiskIndicators = ['rm -rf', 'sudo', 'su', 'chmod 777', 'chown'];
const isHighRisk = highRiskIndicators.some(token => command.includes(token));
if (isHighRisk && !confirm) {
return {
content: [
{
type: 'text',
text: `警告: 该命令被判定为高危,需要确认后才能执行。\n命令: ${command}\n处理方式: 请在调用时加入 { "confirm": true } 明确确认。`
}
]
};
}
try {
const options = {};
if (working_directory) {
options.cwd = working_directory;
}
const { stdout, stderr } = await execAsync(command, options);
let result = `命令执行完成:\n命令: ${command}\n`;
if (working_directory) {
result += `工作目录: ${working_directory}\n`;
}
result += `\n输出:\n${stdout}`;
if (stderr) {
result += `\n错误输出:\n${stderr}`;
}
return {
content: [
{
type: 'text',
text: result
}
]
};
} catch (error) {
return {
content: [
{
type: 'text',
text: `命令执行失败:\n命令: ${command}\n错误: ${error.message}`
}
]
};
}
}
}
module.exports = CommandExecutionTool;