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
| #!/usr/bin/env node
/**
* MCP Server: CN Direct Search (免代理国内直连搜索引擎 MCP)
* 纯原生 Node.js 实现,零外部依赖,安全稳定。
*/
const https = require("https");
const http = require("http");
const readline = require("readline");
const { URL } = require("url");
function decodeHtml(html) {
if (!html) return "";
return html
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/'/g, "'")
.replace(/ /g, " ")
.replace(/ /g, " ")
.replace(/ /g, " ")
.replace(/·/g, "·")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function fetchHttp(targetUrl, timeoutMs = 8000) {
return new Promise((resolve, reject) => {
const parsed = new URL(targetUrl);
const client = parsed.protocol === "http:" ? http : https;
const req = client.get(
targetUrl,
{
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
},
timeout: timeoutMs,
},
(res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
const nextUrl = new URL(res.headers.location, targetUrl).toString();
return fetchHttp(nextUrl, timeoutMs).then(resolve, reject);
}
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => resolve({ statusCode: res.statusCode, body: data }));
}
);
req.on("error", reject);
req.on("timeout", () => {
req.destroy();
reject(new Error(`Request timeout after ${timeoutMs}ms`));
});
});
}
// 必应中国解析
async function searchBing(query, count = 8) {
const url = `https://cn.bing.com/search?q=${encodeURIComponent(query)}&setlang=zh-Hans`;
const res = await fetchHttp(url);
const blocks = res.body.split(/<li class="b_algo"/);
const results = [];
for (let i = 1; i < blocks.length && results.length < count; i++) {
const b = blocks[i];
const h2Match = b.match(/<h2[^>]*><a[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a><\/h2>/);
if (!h2Match) continue;
const link = h2Match[1];
const title = decodeHtml(h2Match[2]);
const pMatch = b.match(/<p[^>]*>([\s\S]*?)<\/p>/);
const snippet = pMatch ? decodeHtml(pMatch[1]) : "";
if (title && link) {
results.push({ title, url: link, snippet, engine: "bing" });
}
}
return results;
}
// 百度搜索解析
async function searchBaidu(query, count = 8) {
const url = `https://www.baidu.com/s?wd=${encodeURIComponent(query)}&ie=utf-8`;
const res = await fetchHttp(url);
const blocks = res.body.split(/<div class="[a-z0-9-_ ]*c-container/);
const results = [];
for (let i = 1; i < blocks.length && results.length < count; i++) {
const b = blocks[i];
const h3Match = b.match(/<h3[^>]*>[\s\S]*?<a[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<\/h3>/);
if (!h3Match) continue;
const link = h3Match[1];
const title = decodeHtml(h3Match[2]);
let snippet = "";
const spanMatch = b.match(/<span class="[a-z0-9-_ ]*content-right_[\s\S]*?>([\s\S]*?)<\/span>/) ||
b.match(/<div class="[a-z0-9-_ ]*c-abstract[^"]*">([\s\S]*?)<\/div>/);
if (spanMatch) snippet = decodeHtml(spanMatch[1]);
if (title && link) {
results.push({ title, url: link, snippet, engine: "baidu" });
}
}
return results;
}
// 自动选优与回退
async function doSearch(query, count = 8, engine = "auto") {
if (engine === "bing") return await searchBing(query, count);
if (engine === "baidu") return await searchBaidu(query, count);
try {
const r = await searchBing(query, count);
if (r && r.length > 0) return r;
} catch (e) {}
try {
return await searchBaidu(query, count);
} catch (e) {
return [];
}
}
// 网页正文提取
async function fetchPage(url) {
const res = await fetchHttp(url, 10000);
const html = res.body;
const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
const title = titleMatch ? decodeHtml(titleMatch[1]) : "";
const clean = html
.replace(/<script[\s\S]*?<\/script>/gi, "")
.replace(/<style[\s\S]*?<\/style>/gi, "")
.replace(/<nav[\s\S]*?<\/nav>/gi, "")
.replace(/<footer[\s\S]*?<\/footer>/gi, "");
return { title, url, content: decodeHtml(clean).slice(0, 10000) };
}
// MCP 标准工具清单
const TOOLS = [
{
name: "cn_web_search",
description: "国内免代理搜索引擎(必应中国+百度)。无需 API Key,免翻墙,响应极速。",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "搜索关键词" },
count: { type: "number", description: "返回数量(默认 8 条)" },
engine: { type: "string", enum: ["auto", "bing", "baidu"], description: "指定引擎" }
},
required: ["query"]
}
},
{
name: "cn_fetch_url",
description: "抓取并解析网页纯文本正文内容。",
inputSchema: {
type: "object",
properties: {
url: { type: "string", description: "网页 URL" }
},
required: ["url"]
}
}
];
// MCP JSON-RPC 2.0 通信处理
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
function send(msg) { process.stdout.write(JSON.stringify(msg) + "\n"); }
rl.on("line", async (line) => {
if (!line.trim()) return;
let req;
try { req = JSON.parse(line); } catch (e) { return; }
const { id, method, params } = req;
if (method === "initialize") {
return send({
jsonrpc: "2.0",
id,
result: {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "mcp-cn-search", version: "1.0.0" }
}
});
}
if (method === "notifications/initialized" || method === "ping") {
if (id !== undefined) send({ jsonrpc: "2.0", id, result: {} });
return;
}
if (method === "tools/list") {
return send({ jsonrpc: "2.0", id, result: { tools: TOOLS } });
}
if (method === "tools/call") {
try {
if (params.name === "cn_web_search") {
const res = await doSearch(params.arguments?.query, params.arguments?.count || 8, params.arguments?.engine || "auto");
return send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] } });
}
if (params.name === "cn_fetch_url") {
const res = await fetchPage(params.arguments?.url);
return send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] } });
}
} catch (err) {
return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: err.message }] } });
}
}
});
|