-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxhs-mcp-entrypoint.mjs
More file actions
448 lines (404 loc) · 14.1 KB
/
xhs-mcp-entrypoint.mjs
File metadata and controls
448 lines (404 loc) · 14.1 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/**
* Node.js HTTP entrypoint for @sillyl12324/xhs-mcp.
*
* Adds a legacy-compatible `xhs_publish_content` MCP tool on top of upstream 2.7.0,
* while preserving the upstream tool surface and routing behavior.
*/
import http from 'node:http';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ErrorCode,
McpError,
} from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { initDatabase } from '@sillyl12324/xhs-mcp/dist/db/index.js';
import { getAccountPool } from '@sillyl12324/xhs-mcp/dist/core/account-pool.js';
import { executeWithMultipleAccounts } from '@sillyl12324/xhs-mcp/dist/core/multi-account.js';
import { PUBLISH_SELECTORS } from '@sillyl12324/xhs-mcp/dist/xhs/clients/constants.js';
import { accountTools, handleAccountTools } from '@sillyl12324/xhs-mcp/dist/tools/account.js';
import { authTools, handleAuthTools } from '@sillyl12324/xhs-mcp/dist/tools/auth.js';
import { contentTools, handleContentTools } from '@sillyl12324/xhs-mcp/dist/tools/content.js';
import { publishTools, handlePublishTools } from '@sillyl12324/xhs-mcp/dist/tools/publish.js';
import { interactionTools, handleInteractionTools } from '@sillyl12324/xhs-mcp/dist/tools/interaction.js';
import { statsTools, handleStatsTools } from '@sillyl12324/xhs-mcp/dist/tools/stats.js';
import { downloadTools, handleDownloadTools } from '@sillyl12324/xhs-mcp/dist/tools/download.js';
import { draftTools, handleDraftTools } from '@sillyl12324/xhs-mcp/dist/tools/draft.js';
import { creatorTools, handleCreatorTools } from '@sillyl12324/xhs-mcp/dist/tools/creator.js';
import { notificationTools, handleNotificationTools } from '@sillyl12324/xhs-mcp/dist/tools/notification.js';
import { exploreTools, handleExploreTools } from '@sillyl12324/xhs-mcp/dist/tools/explore.js';
const port = parseInt(process.env.XHS_MCP_PORT || '18060', 10);
PUBLISH_SELECTORS.publishBtn = 'button.publishBtn, div.publish-page-publish-btn button.bg-red';
const db = await initDatabase();
const pool = getAccountPool(db);
const legacyPublishTool = {
name: 'xhs_publish_content',
description:
'Legacy compatibility tool for publishing image/text notes. Preserves the older tool name expected by AIInSight.',
inputSchema: {
type: 'object',
properties: {
title: { type: 'string', description: 'Note title (max 20 characters)' },
content: { type: 'string', description: 'Note content/description' },
images: {
type: 'array',
items: { type: 'string' },
description: 'Paths or URLs to image files',
},
tags: {
type: 'array',
items: { type: 'string' },
description: 'Optional tags/topics for the note',
},
scheduleTime: {
type: 'string',
description: 'Optional scheduled publish time (ISO 8601 format)',
},
account: {
type: 'string',
description: 'Account name or ID to use for publishing',
},
accounts: {
oneOf: [
{ type: 'array', items: { type: 'string' } },
{ type: 'string', enum: ['all'] },
],
description: 'Multiple accounts to publish to (array of names/IDs, or "all")',
},
},
required: ['title', 'content', 'images'],
},
};
const allTools = [
...accountTools,
...authTools,
...contentTools,
...publishTools,
...interactionTools,
...statsTools,
...downloadTools,
...draftTools,
...creatorTools,
...notificationTools,
...exploreTools,
legacyPublishTool,
];
/**
* Post-publish verification: query creator center for the newly published note.
* Returns the matched note object if found, or null.
*/
async function verifyPublishViaCreatorCenter(client, title, timeoutMs = 15000) {
const VERIFY_WAIT_MS = 5000;
console.error(`[publish-verify] Waiting ${VERIFY_WAIT_MS}ms for platform sync...`);
await new Promise((r) => setTimeout(r, VERIFY_WAIT_MS));
try {
console.error('[publish-verify] Querying creator center for recent notes...');
const notes = await client.getMyPublishedNotes(0, 10, timeoutMs);
console.error(`[publish-verify] Got ${notes.length} notes from creator center`);
if (!notes || notes.length === 0) return null;
const publishWindowMs = 3 * 60 * 1000; // 3 min window
const now = Date.now();
for (const note of notes) {
// Title must match exactly
if (note.title !== title) continue;
// Check publish time is within window (if available)
if (note.time) {
const noteTime = new Date(note.time).getTime();
if (now - noteTime > publishWindowMs) continue;
}
console.error(`[publish-verify] Matched note: id=${note.id}, title=${note.title}`);
return note;
}
console.error('[publish-verify] No matching note found in creator center');
return null;
} catch (err) {
console.error('[publish-verify] Creator center query failed:', err?.message || err);
return null;
}
}
async function handleLegacyPublishTool(args) {
const params = z
.object({
title: z.string().max(20),
content: z.string(),
images: z.array(z.string()).min(1),
tags: z.array(z.string()).optional(),
scheduleTime: z.string().optional(),
account: z.string().optional(),
accounts: z.union([z.array(z.string()), z.literal('all')]).optional(),
})
.parse(args ?? {});
const multiParams = {
account: params.account,
accounts: params.accounts,
};
const results = await executeWithMultipleAccounts(
pool,
db,
multiParams,
'publish_content',
async (ctx) => {
const result = await ctx.client.publishContent({
title: params.title,
content: params.content,
images: params.images,
tags: params.tags,
scheduleTime: params.scheduleTime,
});
if (!result.success) {
return result;
}
// --- Verification gate ---
// If upstream already gave us a noteId, trust it.
if (result.noteId) {
console.error(`[publish-verify] Upstream returned noteId=${result.noteId}, skipping verification`);
db.published.record({
accountId: ctx.accountId,
noteId: result.noteId,
title: params.title,
content: params.content,
noteType: 'image',
images: params.images,
tags: params.tags,
status: params.scheduleTime ? 'scheduled' : 'published',
});
return {
success: true,
noteId: result.noteId,
noteUrl: `https://www.xiaohongshu.com/explore/${result.noteId}`,
};
}
// Upstream didn't return noteId (the common case due to upstream bug).
// Verify via creator center.
const matched = await verifyPublishViaCreatorCenter(ctx.client, params.title);
if (matched && matched.id) {
console.error(`[publish-verify] Verified! noteId=${matched.id}`);
db.published.record({
accountId: ctx.accountId,
noteId: matched.id,
title: params.title,
content: params.content,
noteType: 'image',
images: params.images,
tags: params.tags,
status: params.scheduleTime ? 'scheduled' : 'published',
});
return {
success: true,
noteId: matched.id,
noteUrl: `https://www.xiaohongshu.com/explore/${matched.id}`,
verifiedVia: 'creator_center',
};
}
// Verification failed — skip db record (can't confirm publish), return error
console.error('[publish-verify] Verification failed — returning submitted_but_unverified');
return {
success: false,
error: 'submitted_but_unverified',
message: '发布动作已提交,但未在创作者中心确认到新笔记。请在小红书 App 中手动检查。',
};
},
{
logParams: { title: params.title, imageCount: params.images.length },
sequential: true,
},
);
if (results.length === 1) {
const r = results[0];
if (!r.success) {
return {
content: [{ type: 'text', text: JSON.stringify(r, null, 2) }],
isError: true,
};
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
account: r.account,
success: true,
noteId: r.result?.noteId,
noteUrl: r.result?.noteUrl,
verifiedVia: r.result?.verifiedVia,
result: r.result,
},
null,
2,
),
},
],
};
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
results: results.map((r) => ({
account: r.account,
success: r.success,
noteId: r.success ? r.result?.noteId : undefined,
noteUrl: r.success ? r.result?.noteUrl : undefined,
result: r.success ? r.result : undefined,
error: r.error,
})),
},
null,
2,
),
},
],
};
}
function createCompatibleMcpServer() {
const server = new Server(
{ name: 'xhs-mcp', version: '2.0.0' },
{ capabilities: { tools: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: allTools,
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
const { name, arguments: args } = request.params;
if (name === 'xhs_publish_content') {
return await handleLegacyPublishTool(args);
}
if (accountTools.some((t) => t.name === name)) {
return await handleAccountTools(name, args, pool, db);
}
if (authTools.some((t) => t.name === name)) {
return await handleAuthTools(name, args, pool, db);
}
if (contentTools.some((t) => t.name === name)) {
return await handleContentTools(name, args, pool, db);
}
if (publishTools.some((t) => t.name === name)) {
return await handlePublishTools(name, args, pool, db);
}
if (interactionTools.some((t) => t.name === name)) {
return await handleInteractionTools(name, args, pool, db);
}
if (statsTools.some((t) => t.name === name)) {
return await handleStatsTools(name, args, pool, db);
}
if (downloadTools.some((t) => t.name === name)) {
return await handleDownloadTools(name, args, pool, db);
}
if (draftTools.some((t) => t.name === name)) {
return await handleDraftTools(name, args, pool, db);
}
if (creatorTools.some((t) => t.name === name)) {
return await handleCreatorTools(name, args, pool, db);
}
if (notificationTools.some((t) => t.name === name)) {
return await handleNotificationTools(name, args, pool, db);
}
if (exploreTools.some((t) => t.name === name)) {
return await handleExploreTools(name, args, pool, db);
}
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
} catch (error) {
if (error instanceof z.ZodError) {
throw new McpError(
ErrorCode.InvalidParams,
`Invalid arguments: ${error.message}`,
);
}
throw error;
}
});
return server;
}
function setCorsHeaders(res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Mcp-Session-Id');
}
const httpServer = http.createServer(async (req, res) => {
setCorsHeaders(res);
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
const url = new URL(req.url, `http://localhost:${port}`);
if (url.pathname === '/health' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', server: 'xhs-mcp', version: '2.0.0' }));
return;
}
if (url.pathname === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(
JSON.stringify({
name: 'xhs-mcp',
version: '2.0.0',
description: 'Xiaohongshu MCP Server (Node.js)',
endpoints: { mcp: '/mcp', health: '/health' },
}),
);
return;
}
if (url.pathname === '/mcp' && req.method === 'POST') {
let transport;
let mcpServer;
try {
transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
mcpServer = createCompatibleMcpServer();
await mcpServer.connect(transport);
const body = await new Promise((resolve, reject) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
} catch (e) {
reject(e);
}
});
req.on('error', reject);
});
req.body = body;
await transport.handleRequest(req, res, body);
} catch (error) {
console.error('MCP request error:', error);
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(
JSON.stringify({
jsonrpc: '2.0',
error: { code: -32603, message: 'Internal server error' },
id: null,
}),
);
}
} finally {
if (transport) await transport.close().catch(() => {});
if (mcpServer) await mcpServer.close().catch(() => {});
}
return;
}
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
});
const shutdown = async () => {
console.error('Shutting down...');
await pool.closeAll();
db.close();
httpServer.close();
process.exit(0);
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
httpServer.listen(port, () => {
console.error(`Starting HTTP server on port ${port}...`);
console.error(`MCP endpoint: http://localhost:${port}/mcp`);
console.error(`HTTP server running on http://localhost:${port}`);
});