-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.ts
More file actions
220 lines (198 loc) · 6.58 KB
/
server.ts
File metadata and controls
220 lines (198 loc) · 6.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import fs from 'fs-extra';
import * as path from 'node:path';
import * as os from 'node:os';
import sharp from 'sharp';
// 获取桌面路径
const getDesktopPath = () => {
const { homedir } = os.userInfo();
return path.join(homedir, 'Desktop');
};
// 检查文件是否为图片
const isImageFile = (filePath: string): boolean => {
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.svg'];
const ext = path.extname(filePath).toLowerCase();
return imageExtensions.includes(ext);
};
// 获取桌面上的所有图片文件
const getDesktopImageFiles = async (): Promise<string[]> => {
const desktopPath = getDesktopPath();
try {
const files = await fs.readdir(desktopPath);
const imagePaths = files.filter(file => {
const filePath = path.join(desktopPath, file);
return fs.statSync(filePath).isFile() && isImageFile(filePath);
});
return imagePaths;
} catch (error) {
console.error(`Error reading desktop directory: ${error}`, );
return [];
}
};
// 创建 MCP 服务器
const server = new McpServer({
name: "desktop-image-manager",
version: process.env.VERSION || '1.0.0'
});
// 工具1: 统计桌面上的图片文件数量
server.tool(
"count-desktop-images",
"统计桌面上的图片文件数量",
{},
async () => {
try {
const imageFiles = await getDesktopImageFiles();
return {
content: [{
type: "text",
text: `桌面上共有 ${imageFiles.length} 个图片文件。`
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `获取图片数量时出错: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}
}
);
// 工具2: 获取桌面上的图片文件名称列表
server.tool(
"list-desktop-images",
"获取桌面上的图片文件名称列表",
{},
async () => {
try {
const imageFiles = await getDesktopImageFiles();
if (imageFiles.length === 0) {
return {
content: [{ type: "text", text: "桌面上没有找到图片文件。" }]
};
}
const fileList = imageFiles.map((file, index) => `${index + 1}. ${file}`).join('\n');
return {
content: [{
type: "text",
text: `桌面上的图片文件列表:\n${fileList}`
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `获取图片列表时出错: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}
}
);
// 工具3: 压缩图片
server.tool(
"compress-image",
'压缩图片',
{
fileName: z.string().describe("要压缩的图片文件名"),
quality: z.number().min(1).max(100).default(80).describe("压缩质量 (1-100)"),
outputName: z.string().optional().describe("输出文件名 (可选)")
},
async ({ fileName, quality, outputName }) => {
try {
const desktopPath = getDesktopPath();
const inputPath = path.join(desktopPath, fileName);
// 检查文件是否存在
if (!await fs.pathExists(inputPath)) {
return {
content: [{ type: "text", text: `文件 "${fileName}" 不存在。` }],
isError: true
};
}
// 检查是否为图片文件
if (!isImageFile(inputPath)) {
return {
content: [{ type: "text", text: `文件 "${fileName}" 不是支持的图片格式。` }],
isError: true
};
}
// 确定输出文件名
const ext = path.extname(fileName);
const baseName = path.basename(fileName, ext);
const finalOutputName = outputName || `${baseName}-compressed${ext}`;
const outputNameFilled = isImageFile(finalOutputName) ? finalOutputName : `${finalOutputName}${ext}`;
const outputPath = path.join(desktopPath, outputNameFilled);
// 根据文件扩展名确定压缩方法
const lowerExt = ext.toLowerCase();
if (['.jpg', '.jpeg'].includes(lowerExt)) {
await sharp(inputPath)
.jpeg({ quality })
.toFile(outputPath);
} else if (lowerExt === '.png') {
await sharp(inputPath)
.png({ quality })
.toFile(outputPath);
} else if (lowerExt === '.webp') {
await sharp(inputPath)
.webp({ quality })
.toFile(outputPath);
} else {
// 对于其他格式,先转换为 JPEG 再压缩
await sharp(inputPath)
.jpeg({ quality })
.toFile(outputPath);
}
// 获取原始文件和压缩后文件的大小
const originalSize = (await fs.stat(inputPath)).size;
const compressedSize = (await fs.stat(outputPath)).size;
const savingsPercent = ((originalSize - compressedSize) / originalSize * 100).toFixed(2);
return {
content: [{
type: "text",
text: `图片压缩成功!\n原始文件: ${fileName} (${originalSize} 字节)\n压缩后文件: ${outputNameFilled} (${compressedSize} 字节)\n节省空间: ${savingsPercent}%`
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `压缩图片时出错: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}
}
);
server.prompt(
'compress-image',
'压缩图片',
{
fileName: z.string().describe("要压缩的图片文件名"),
quality: z.string().describe("压缩质量 (1-100)").optional(),
outputName: z.string().optional().describe("输出文件名 (可选)")
},
async ({ fileName, quality, outputName }) => {
const convertQuality = Math.max(Math.min(100, parseInt(quality|| '0', 10) || 85), 1);
const ext = path.extname(fileName);
const baseName = path.basename(fileName, ext);
const finalOutputName = outputName || `${baseName}-compressed${ext}`;
const outputNameFilled = isImageFile(finalOutputName) ? finalOutputName : `${finalOutputName}${ext}`;
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: `请压缩图片 "${fileName}",压缩质量为 ${convertQuality}%,输出文件名为 "${outputNameFilled}"。`
}
}
]
}
})
// 启动服务器
const transport = new StdioServerTransport();
server.connect(transport)