writedock-mcp 0.0.0-stage → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +674 -0
- package/LICENSE-MULTIPOST +201 -0
- package/NOTICE.md +13 -0
- package/README.md +101 -2
- package/THIRD_PARTY_NOTICES.txt +629 -0
- package/index.cjs +50453 -0
- package/package.json +30 -3
- package/source/distribution.json +5 -0
- package/source/package.json +30 -0
- package/source/src/__tests__/article.test.ts +49 -0
- package/source/src/__tests__/bridge.test.ts +90 -0
- package/source/src/article.ts +127 -0
- package/source/src/bridge.ts +298 -0
- package/source/src/identity.ts +56 -0
- package/source/src/index.ts +27 -0
- package/source/src/media.ts +95 -0
- package/source/src/post.ts +17 -0
- package/source/src/release-info.ts +67 -0
- package/source/src/server.ts +102 -0
- package/source/tsconfig.json +32 -0
- package/source/tsup.config.ts +6 -0
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { link, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { join, resolve } from 'node:path'
|
|
5
|
+
|
|
6
|
+
interface Identity { version: 1; token: string; extensionToken: string }
|
|
7
|
+
const validToken = (value: unknown): value is string => typeof value === 'string' && /^[A-Za-z0-9_-]{24,128}$/.test(value)
|
|
8
|
+
|
|
9
|
+
export function dataDirectory() {
|
|
10
|
+
if (process.env.WRITEDOCK_DATA_DIR) return resolve(process.env.WRITEDOCK_DATA_DIR)
|
|
11
|
+
if (process.platform === 'darwin') return join(homedir(), 'Library/Application Support/WriteDock/mcp')
|
|
12
|
+
if (process.platform === 'win32') return join(process.env.LOCALAPPDATA || join(homedir(), 'AppData/Local'), 'WriteDock/mcp')
|
|
13
|
+
return join(process.env.XDG_DATA_HOME || join(homedir(), '.local/share'), 'writedock/mcp')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function loadIdentity(port: number, legacyToken?: string) {
|
|
17
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('WRITEDOCK_PORT 必须是 1024–65535 的整数')
|
|
18
|
+
const directory = dataDirectory()
|
|
19
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
20
|
+
const filename = join(directory, `identity-${port}.json`)
|
|
21
|
+
const read = async (): Promise<Identity> => {
|
|
22
|
+
const value = JSON.parse(await readFile(filename, 'utf8'))
|
|
23
|
+
if (value.version !== 1 || !validToken(value.token) || !validToken(value.extensionToken)) throw new Error('MCP 配对资料格式不正确;请保留原文件并检查备份,不会自动覆盖')
|
|
24
|
+
return value
|
|
25
|
+
}
|
|
26
|
+
let identity: Identity
|
|
27
|
+
try { identity = await read() }
|
|
28
|
+
catch (error) {
|
|
29
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
30
|
+
if (legacyToken && !validToken(legacyToken)) throw new Error('旧 WRITEDOCK_TOKEN 格式不正确,请检查原 MCP 配置')
|
|
31
|
+
const token = legacyToken || randomBytes(32).toString('hex')
|
|
32
|
+
const initial: Identity = { version: 1, token, extensionToken: token }
|
|
33
|
+
const temporary = join(directory, `.identity-${randomUUID()}.tmp`)
|
|
34
|
+
await writeFile(temporary, JSON.stringify(initial), { flag: 'wx', mode: 0o600 })
|
|
35
|
+
try {
|
|
36
|
+
// Atomically create once; simultaneous MCP clients must share the same identity.
|
|
37
|
+
try { await link(temporary, filename) }
|
|
38
|
+
catch (cause) { if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause }
|
|
39
|
+
} finally { await unlink(temporary) }
|
|
40
|
+
identity = await read()
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
token: identity.token,
|
|
44
|
+
getExtensionToken: async () => (await read()).extensionToken,
|
|
45
|
+
setExtensionToken: async (extensionToken: string) => {
|
|
46
|
+
if (!validToken(extensionToken)) throw new Error('扩展配对密钥格式不正确')
|
|
47
|
+
const current = await read()
|
|
48
|
+
if (current.token !== identity.token) throw new Error('MCP 身份已变化,请重新启动服务')
|
|
49
|
+
const temporary = join(directory, `.identity-${randomUUID()}.tmp`)
|
|
50
|
+
try {
|
|
51
|
+
await writeFile(temporary, JSON.stringify({ ...current, extensionToken }), { flag: 'wx', mode: 0o600 })
|
|
52
|
+
await rename(temporary, filename)
|
|
53
|
+
} finally { await unlink(temporary).catch(() => {}) }
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
3
|
+
import { LocalBridge } from './bridge'
|
|
4
|
+
import { createMcpServer } from './server'
|
|
5
|
+
import { loadIdentity } from './identity'
|
|
6
|
+
import mcpPackage from '../package.json'
|
|
7
|
+
|
|
8
|
+
async function main() {
|
|
9
|
+
const port = Number(process.env.WRITEDOCK_PORT || 9647)
|
|
10
|
+
const identity = await loadIdentity(port, process.env.WRITEDOCK_TOKEN)
|
|
11
|
+
const bridge = new LocalBridge({ token: identity.token, port, credentials: identity })
|
|
12
|
+
await bridge.start()
|
|
13
|
+
const server = createMcpServer(bridge)
|
|
14
|
+
let closing = false
|
|
15
|
+
const close = async () => { if (closing) return; closing = true; await bridge.close(); await server.close() }
|
|
16
|
+
process.stdin.on('end', () => { void close() })
|
|
17
|
+
process.on('SIGINT', () => { void close().finally(() => process.exit(0)) })
|
|
18
|
+
process.on('SIGTERM', () => { void close().finally(() => process.exit(0)) })
|
|
19
|
+
server.server.onclose = () => { void bridge.close() }
|
|
20
|
+
await server.connect(new StdioServerTransport())
|
|
21
|
+
}
|
|
22
|
+
if (process.argv.slice(2).some(argument => argument === '--version' || argument === '-v')) {
|
|
23
|
+
// Allow inspecting an npm archive without starting a bridge or reading pairing credentials.
|
|
24
|
+
console.log(mcpPackage.version)
|
|
25
|
+
} else {
|
|
26
|
+
main().catch(error => { console.error('[WriteDock MCP]', error instanceof Error ? error.message : String(error)); process.exit(1) })
|
|
27
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { open, realpath, stat } from 'node:fs/promises'
|
|
2
|
+
import { basename, extname, isAbsolute, relative, resolve } from 'node:path'
|
|
3
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
5
|
+
|
|
6
|
+
export interface MediaAsset { id: string; accessKey: string; port: number; name: string; type: string; size: number; fingerprint: string }
|
|
7
|
+
interface Grant { asset: MediaAsset; path: string; modified: number; expires: number }
|
|
8
|
+
const CHUNK = 1024 * 1024
|
|
9
|
+
const LEASE = 2 * 60 * 60_000
|
|
10
|
+
|
|
11
|
+
export async function mediaPath(input: string, base?: string) {
|
|
12
|
+
if (!isAbsolute(input) && !base) throw new Error('素材请提供绝对路径,或明确提供 base_directory')
|
|
13
|
+
const directory = base ? await realpath(base) : undefined
|
|
14
|
+
const path = await realpath(resolve(directory || '', input))
|
|
15
|
+
if (directory && !isAbsolute(input)) {
|
|
16
|
+
const inside = relative(directory, path)
|
|
17
|
+
if (inside === '..' || inside.startsWith('../') || inside.startsWith('..\\') || isAbsolute(inside)) throw new Error('相对素材路径必须位于 base_directory 内')
|
|
18
|
+
}
|
|
19
|
+
return path
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class MediaStore {
|
|
23
|
+
private grants = new Map<string, Grant>()
|
|
24
|
+
private seen = new Map<string, number>()
|
|
25
|
+
constructor(private port: number) {}
|
|
26
|
+
|
|
27
|
+
async register(input: string, kind: 'image' | 'video'): Promise<MediaAsset> {
|
|
28
|
+
if (!isAbsolute(input)) throw new Error('素材路径必须是绝对路径')
|
|
29
|
+
const path = await realpath(input), info = await stat(path)
|
|
30
|
+
const limit = (kind === 'video' ? 512 : 20) * 1024 * 1024
|
|
31
|
+
if (!info.isFile() || !info.size || info.size > limit) throw new Error(kind === 'video' ? '视频必须是 512 MB 以内的文件' : '单张图片必须在 20 MB 以内')
|
|
32
|
+
const file = await open(path, 'r')
|
|
33
|
+
const header = Buffer.alloc(32)
|
|
34
|
+
try { await file.read(header, 0, header.length, 0) } finally { await file.close() }
|
|
35
|
+
let type = ''
|
|
36
|
+
if (kind === 'image') {
|
|
37
|
+
if (header.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) type = 'image/png'
|
|
38
|
+
else if (header[0] === 255 && header[1] === 216 && header[2] === 255) type = 'image/jpeg'
|
|
39
|
+
else if (/^GIF8[79]a$/.test(header.subarray(0, 6).toString())) type = 'image/gif'
|
|
40
|
+
else if (header.subarray(0, 4).toString() === 'RIFF' && header.subarray(8, 12).toString() === 'WEBP') type = 'image/webp'
|
|
41
|
+
} else {
|
|
42
|
+
const extension = extname(path).toLowerCase()
|
|
43
|
+
if (header.subarray(4, 8).toString() === 'ftyp' && ['.mp4', '.m4v', '.mov'].includes(extension)) type = extension === '.mov' ? 'video/quicktime' : 'video/mp4'
|
|
44
|
+
else if (header.subarray(0, 4).equals(Buffer.from([0x1a,0x45,0xdf,0xa3])) && extension === '.webm') type = 'video/webm'
|
|
45
|
+
}
|
|
46
|
+
if (!type) throw new Error(kind === 'image' ? '图片仅支持 PNG、JPEG、GIF、WebP' : '视频仅支持 MP4、MOV、WebM')
|
|
47
|
+
for (const [id, grant] of this.grants) if (grant.expires < Date.now()) this.grants.delete(id)
|
|
48
|
+
const fingerprint = createHash('sha256').update(`${path}\0${info.size}\0${info.mtimeMs}`).digest('hex')
|
|
49
|
+
const reusable = [...this.grants.values()].find(grant => grant.asset.fingerprint === fingerprint)
|
|
50
|
+
if (reusable) { reusable.expires = Date.now() + LEASE; return reusable.asset }
|
|
51
|
+
if (this.grants.size >= 256) throw new Error('待发布素材过多,请等待现有素材授权过期后重试')
|
|
52
|
+
const asset: MediaAsset = { id: randomUUID(), accessKey: randomBytes(32).toString('hex'), port: this.port, name: basename(path), type, size: info.size, fingerprint }
|
|
53
|
+
this.grants.set(asset.id, { asset, path, modified: info.mtimeMs, expires: Date.now() + LEASE })
|
|
54
|
+
return asset
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async serve(req: IncomingMessage, res: ServerResponse, id: string) {
|
|
58
|
+
if (req.headers.origin) {
|
|
59
|
+
res.setHeader('Access-Control-Allow-Origin', req.headers.origin)
|
|
60
|
+
res.setHeader('Vary', 'Origin')
|
|
61
|
+
}
|
|
62
|
+
res.setHeader('Access-Control-Expose-Headers', 'X-Writedock-Asset-Proof, Content-Range')
|
|
63
|
+
if (req.method === 'OPTIONS') {
|
|
64
|
+
res.writeHead(204, { 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Range, X-Writedock-Asset-Nonce, X-Writedock-Asset-Time, X-Writedock-Asset-Proof' })
|
|
65
|
+
res.end(); return
|
|
66
|
+
}
|
|
67
|
+
const fail = (status: number, error: string) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error })) }
|
|
68
|
+
const grant = this.grants.get(id)
|
|
69
|
+
if (!grant || grant.expires < Date.now()) { fail(403, '素材授权已失效,请重新准备素材;不会自动重新发布'); return }
|
|
70
|
+
const range = /^bytes=(\d+)-(\d+)$/.exec(String(req.headers.range || ''))
|
|
71
|
+
const start = Number(range?.[1]), end = Number(range?.[2])
|
|
72
|
+
if (req.method !== 'GET' || !range || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || end >= grant.asset.size || end - start + 1 > CHUNK) { fail(416, '请按不超过 1 MB 的范围读取素材'); return }
|
|
73
|
+
const nonce = String(req.headers['x-writedock-asset-nonce'] || ''), time = String(req.headers['x-writedock-asset-time'] || ''), signature = String(req.headers['x-writedock-asset-proof'] || '')
|
|
74
|
+
const expected = createHmac('sha256', grant.asset.accessKey).update(`asset-request:${id}:${start}:${end}:${time}:${nonce}`).digest('hex')
|
|
75
|
+
const now = Date.now()
|
|
76
|
+
if (!/^[a-f0-9]{64}$/.test(nonce) || !/^\d+$/.test(time) || Math.abs(now - Number(time)) > 15_000 || this.seen.has(nonce) || !/^[a-f0-9]{64}$/.test(signature) || !timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) { fail(403, '素材读取认证失败'); return }
|
|
77
|
+
for (const [key, expires] of this.seen) if (expires < now) this.seen.delete(key)
|
|
78
|
+
this.seen.set(nonce, now + 30_000)
|
|
79
|
+
let file
|
|
80
|
+
try {
|
|
81
|
+
file = await open(grant.path, 'r')
|
|
82
|
+
const info = await file.stat()
|
|
83
|
+
if (info.size !== grant.asset.size || info.mtimeMs !== grant.modified) throw new Error('素材文件已经变化,请重新准备后再发布')
|
|
84
|
+
const buffer = Buffer.alloc(end - start + 1)
|
|
85
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, start)
|
|
86
|
+
if (bytesRead !== buffer.length) throw new Error('素材读取不完整')
|
|
87
|
+
grant.expires = Date.now() + LEASE
|
|
88
|
+
const hash = createHash('sha256').update(buffer).digest('hex')
|
|
89
|
+
const proof = createHmac('sha256', grant.asset.accessKey).update(`asset-response:${nonce}:${hash}`).digest('hex')
|
|
90
|
+
res.writeHead(206, { 'Content-Type': grant.asset.type, 'Content-Length': buffer.length, 'Content-Range': `bytes ${start}-${end}/${grant.asset.size}`, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-store', 'X-Writedock-Asset-Proof': proof })
|
|
91
|
+
res.end(buffer)
|
|
92
|
+
} catch (error) { fail(400, error instanceof Error ? error.message : '素材读取失败') }
|
|
93
|
+
finally { await file?.close() }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { mediaPath, type MediaAsset } from './media'
|
|
2
|
+
|
|
3
|
+
export interface PostSource { kind: 'image' | 'video'; title: string; content?: string; image_paths?: string[]; video_path?: string; cover_path?: string; tags?: string[]; base_directory?: string; weibo_video_creation?: 'original' | 'secondary' | 'repost' }
|
|
4
|
+
export interface PreparedPost { kind: 'image' | 'video'; title: string; content: string; images: MediaAsset[]; video?: MediaAsset; cover?: MediaAsset; tags: string[]; weiboVideoCreation?: 'original' | 'secondary' | 'repost' }
|
|
5
|
+
|
|
6
|
+
export async function preparePost(source: PostSource, register: (path: string, kind: 'image' | 'video') => Promise<MediaAsset>): Promise<PreparedPost> {
|
|
7
|
+
if (!source.title.trim() || source.title.trim().length > 200) throw new Error('标题需要 1–200 字')
|
|
8
|
+
if (source.kind === 'image' && (!source.image_paths?.length || source.video_path)) throw new Error('图文需要至少一张图片,不能同时提供视频')
|
|
9
|
+
if (source.kind === 'image' && source.cover_path) throw new Error('图文以第一张图片作为封面;cover_path 仅用于视频')
|
|
10
|
+
if (source.kind === 'video' && (!source.video_path || source.image_paths?.length)) throw new Error('视频投稿需要 video_path,不能同时提供图文图片列表')
|
|
11
|
+
if (source.weibo_video_creation !== undefined && (source.kind !== 'video' || !['original', 'secondary', 'repost'].includes(source.weibo_video_creation))) throw new Error('weibo_video_creation 仅用于视频,须明确传入 original、secondary 或 repost')
|
|
12
|
+
const images: MediaAsset[] = []
|
|
13
|
+
for (const path of source.image_paths || []) images.push(await register(await mediaPath(path, source.base_directory), 'image'))
|
|
14
|
+
const video = source.video_path ? await register(await mediaPath(source.video_path, source.base_directory), 'video') : undefined
|
|
15
|
+
const cover = source.cover_path ? await register(await mediaPath(source.cover_path, source.base_directory), 'image') : undefined
|
|
16
|
+
return { kind: source.kind, title: source.title.trim(), content: source.content || '', images, ...(video ? { video } : {}), ...(cover ? { cover } : {}), tags: [...new Set((source.tags || []).map(tag => tag.trim().replace(/^#+/, '')).filter(Boolean))], ...(source.weibo_video_creation ? { weiboVideoCreation: source.weibo_video_creation } : {}) }
|
|
17
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import mcpPackage from '../package.json'
|
|
2
|
+
import distribution from '../distribution.json'
|
|
3
|
+
|
|
4
|
+
const CHECK_INTERVAL = 6 * 60 * 60_000
|
|
5
|
+
const RETRY_INTERVAL = 10 * 60_000
|
|
6
|
+
let latestVersion: string | undefined
|
|
7
|
+
let checkedAt: number | undefined
|
|
8
|
+
let lastAttempt = 0
|
|
9
|
+
let checkError: string | undefined
|
|
10
|
+
let pending: Promise<void> | undefined
|
|
11
|
+
|
|
12
|
+
function parseVersion(value: string) {
|
|
13
|
+
if (value.length > 120) return undefined
|
|
14
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value)
|
|
15
|
+
if (!match) return undefined
|
|
16
|
+
const core = match.slice(1, 4).map(Number)
|
|
17
|
+
if (core.some(number => !Number.isSafeInteger(number))) return undefined
|
|
18
|
+
const pre = match[4]?.split('.')
|
|
19
|
+
if (pre?.some(part => !part || /^\d+$/.test(part) && part.length > 1 && part.startsWith('0'))) return undefined
|
|
20
|
+
return { core, pre }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function newerVersion(candidate: string, current: string) {
|
|
24
|
+
const left = parseVersion(candidate), right = parseVersion(current)
|
|
25
|
+
if (!left || !right) return false
|
|
26
|
+
for (let index = 0; index < 3; index++) if (left.core[index] !== right.core[index]) return left.core[index] > right.core[index]
|
|
27
|
+
if (!left.pre || !right.pre) return !left.pre && !!right.pre
|
|
28
|
+
for (let index = 0; index < Math.max(left.pre.length, right.pre.length); index++) {
|
|
29
|
+
const a = left.pre[index], b = right.pre[index]
|
|
30
|
+
if (a === b) continue
|
|
31
|
+
if (a === undefined || b === undefined) return a !== undefined
|
|
32
|
+
const numericA = /^\d+$/.test(a), numericB = /^\d+$/.test(b)
|
|
33
|
+
if (numericA && numericB) return a.length !== b.length ? a.length > b.length : a > b
|
|
34
|
+
if (numericA !== numericB) return !numericA
|
|
35
|
+
return a > b
|
|
36
|
+
}
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function refresh() {
|
|
41
|
+
if (pending || Date.now() - lastAttempt < (checkError ? RETRY_INTERVAL : CHECK_INTERVAL)) return
|
|
42
|
+
lastAttempt = Date.now()
|
|
43
|
+
pending = (async () => {
|
|
44
|
+
const url = `${distribution.registry.replace(/\/$/, '')}/${encodeURIComponent(distribution.name)}/${encodeURIComponent(distribution.tag)}`
|
|
45
|
+
const response = await fetch(url, { credentials: 'omit', cache: 'no-store', signal: AbortSignal.timeout(8000) })
|
|
46
|
+
if (!response.ok) throw new Error(`npm 版本查询暂不可用(HTTP ${response.status})`)
|
|
47
|
+
const data = await response.json() as { name?: unknown; version?: unknown }
|
|
48
|
+
if (data.name !== distribution.name || typeof data.version !== 'string' || !parseVersion(data.version)) throw new Error('npm 返回的版本信息无法确认')
|
|
49
|
+
latestVersion = data.version; checkError = undefined
|
|
50
|
+
})().catch(error => {
|
|
51
|
+
latestVersion = undefined
|
|
52
|
+
checkError = error instanceof Error && error.message.startsWith('npm ') ? error.message : '暂时无法检查 npm 新版本,不影响当前连接'
|
|
53
|
+
}).finally(() => { checkedAt = Date.now(); pending = undefined })
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Check asynchronously; version lookup must never delay pairing, tool calls or publication. */
|
|
57
|
+
export function mcpReleaseInfo() {
|
|
58
|
+
refresh()
|
|
59
|
+
return {
|
|
60
|
+
mcp_version: mcpPackage.version,
|
|
61
|
+
...(latestVersion ? { latest_version: latestVersion } : {}),
|
|
62
|
+
update_available: !!latestVersion && newerVersion(latestVersion, mcpPackage.version),
|
|
63
|
+
...(checkedAt ? { update_checked_at: checkedAt } : {}),
|
|
64
|
+
...(checkError ? { update_check_error: checkError } : {}),
|
|
65
|
+
update_checking: !!pending,
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { prepareSource } from './article'
|
|
4
|
+
import { LocalBridge } from './bridge'
|
|
5
|
+
import mcpPackage from '../package.json'
|
|
6
|
+
import { preparePost } from './post'
|
|
7
|
+
|
|
8
|
+
const source = {
|
|
9
|
+
file_path: z.string().optional().describe('本机 Markdown/HTML 文件的绝对路径,本地图片相对稿件目录解析'),
|
|
10
|
+
title: z.string().max(200).optional().describe('标题;也可从文件一级标题或 front matter 读取'),
|
|
11
|
+
markdown: z.string().max(2 * 1024 * 1024).optional(),
|
|
12
|
+
html: z.string().max(24 * 1024 * 1024).optional(),
|
|
13
|
+
cover: z.string().optional().describe('封面 HTTP(S) 地址、data URI 或稿件目录中的图片路径'),
|
|
14
|
+
base_directory: z.string().optional().describe('明确允许读取图片的本地目录;默认使用稿件所在目录'),
|
|
15
|
+
}
|
|
16
|
+
const requestId = z.string().min(8).max(120).regex(/^[A-Za-z0-9_-]+$/)
|
|
17
|
+
const postSource = {
|
|
18
|
+
kind: z.enum(['image', 'video']).describe('image 为图文,video 为独立视频投稿'),
|
|
19
|
+
title: z.string().min(1).max(200),
|
|
20
|
+
content: z.string().max(50_000).optional().describe('纯文本正文或视频简介'),
|
|
21
|
+
image_paths: z.array(z.string().min(1)).min(1).max(35).optional().describe('图文图片本地路径,第一张为封面;单张 20 MB、总量 100 MB 以内'),
|
|
22
|
+
video_path: z.string().optional().describe('本机 MP4/MOV/WebM 视频路径,512 MB 以内;是否接受该格式以平台控件为准'),
|
|
23
|
+
cover_path: z.string().optional().describe('可选的视频封面本地图片路径;小红书不传时使用视频第一帧'),
|
|
24
|
+
tags: z.array(z.string().min(1).max(50)).max(10).optional().describe('话题名称,不带 #;小红书、微博最多 10 个;当前抖音适配图文最多 4 个、视频最多 5 个'),
|
|
25
|
+
weibo_video_creation: z.enum(['original', 'secondary', 'repost']).optional().describe('微博独立视频必填:original 原创、secondary 二创、repost 转载。必须根据用户实际内容明确选择,不得默认原创。其他平台不使用此字段;来源、内容声明或协议需补充时转人工处理'),
|
|
26
|
+
base_directory: z.string().optional().describe('使用相对素材路径时,明确指定素材目录'),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const agentWorkflow = 'Agent 只通过 WriteDock MCP 投稿和查询回执,不依赖也不要调用浏览器、Playwright 或其他网页工具。按结果的 next_action 操作:poll_task 用原 task_id/request_id 查询 get_sync_task;report_result 直接向用户汇报逐平台状态和链接。submitted/published 已有扩展确认,不再打开网页验证;验证码、图形验证、协议、发布设置或 unknown/interrupted 都将原因和链接交给用户自行点击处理,不自动重发、不换 request_id。人工接管不代表已经发布。'
|
|
30
|
+
|
|
31
|
+
export function createMcpServer(bridge: LocalBridge) {
|
|
32
|
+
const server = new McpServer({ name: 'writedock', version: mcpPackage.version }, {
|
|
33
|
+
instructions: agentWorkflow + 'WriteDock 通过本机扩展执行投稿。先检查连接和平台登录。实际平台能力以 list_platforms 返回的 action、publishModes、tools、modeOptions、confirmation、capabilities、coverRequired 为准,扩展更新后优先按该元信息选择工具。知乎、百家号、微博长文章、B站专栏、小红书长文使用 publish_article,Agent 直接提供 Markdown/HTML 或文件路径即可发布,无需用户在扩展编辑。百家号必须提供 cover 封面;知乎另支持 <video src="本地MP4路径"></video> 文章内视频,独立封面暂未接入。prepare_article 仅供可选本机预览,不是发布的前置要求。小红书 ID 为 xiaohongshu,三种模式共用此平台:写长文用 publish_article,支持正文图片、原生自动排版后发布,标题最多 64 字、正文最多 10000 字,不接独立 cover 或文章内视频;普通图文用 publish_post(kind=image),独立视频用 publish_post(kind=video),未传 cover_path 时保留平台自动生成的第一帧封面。小红书最终均须匹配 POST /web_api/sns/v2/note 的 success=true、result=0 和笔记 ID 回执才确认 submitted。抖音平台 ID 为 douyin,图文和视频同样用 publish_post(kind=image|video),可选 cover_path;图文话题最多 4 个、视频最多 5 个,当前只接即时发布。抖音 confirmation=native_page_message,以本次操作新增的原生成功提示确认 submitted,未核对最终 HTTP 业务回执;仅跳转作品管理时仍为 unknown,Agent 不自动重发。小红书、抖音、微博普通图文与独立视频使用 prepare_post / publish_post,微博平台 ID 仍为 weibo,不另建平台。微博图文标题放入正文首行,最多 18 张图片;独立视频标题最多 30 个汉字(60 个半角字符),weibo_video_creation 必填,须依据用户实际内容传 original、secondary 或 repost,不能默认原创。微博同一次只能选图文或视频,长文章继续用 publish_article。只有用户明确要求发布并指定平台时才调用发布工具。微信公众号、搜狐号目前用 sync_article 保存文章草稿。B站专栏 ID 为 bilibili,使用 publish_article 直接发布文字和正文图片,不接视频、音频、附加内容卡片或独立封面;通过新版原生编辑器上传并发布,code=-352 时停止自动提交并转人工验证。遇到 needs_user_action 或 requires_user_action 时,把 user_actions 中的原因和稿件链接告诉用户,优先让用户切换到扩展已打开的页面处理验证码、封面、内容声明、来源、原创协议或发布设置,并手动发布;不得自动解决验证码、重新提交或换 request_id。该状态只记录人工接管,不代表用户之后的操作结果已被确认。扩展更新复用已有 MCP;需要恢复连接时调用 begin_pairing,让用户在扩展输入配对码。提交返回任务 ID,随后用 get_sync_task 查询结果。保持同一操作的 request_id 不变。publicationState=unknown 或任务中断时,向用户给出链接让其自行核对平台,Agent 不打开网页,不要自动生成新 request_id 重发。直接发布成功表示平台已接受提交,是否公开展示以平台为准。',
|
|
34
|
+
})
|
|
35
|
+
const wrap = (operation: () => Promise<unknown>) => operation().then(result => ({
|
|
36
|
+
content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
|
|
37
|
+
})).catch(error => ({ content: [{ type: 'text' as const, text: error instanceof Error ? error.message : String(error) }], isError: true }))
|
|
38
|
+
const readOnly = { readOnlyHint: true, destructiveHint: false, openWorldHint: false }
|
|
39
|
+
|
|
40
|
+
server.registerTool('get_connection_status', {
|
|
41
|
+
description: '检查本机 MCP 与扩展的连接、运行版本和 npm 更新提示。update_available=true 时告知用户重新启动 WriteDock MCP,保留配置和配对;发布任务进行中不要自动重启。旧版服务可能不返回版本字段;latest_version 缺失或 update_checking=true 时,不得声称已是最新版。', inputSchema: {}, annotations: { ...readOnly, openWorldHint: true },
|
|
42
|
+
}, () => wrap(() => bridge.status()))
|
|
43
|
+
server.registerTool('begin_pairing', {
|
|
44
|
+
description: '首次连接或扩展卸载重装后,生成 3 分钟有效的一次性配对码。让用户粘贴到扩展的 MCP 连接页即可,复用已有 MCP 和 agent 配置。新配对会替换此前浏览器的连接授权,请在用户要求连接扩展时调用。',
|
|
45
|
+
inputSchema: {}, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
|
46
|
+
}, () => wrap(() => bridge.beginPairing()))
|
|
47
|
+
server.registerTool('list_platforms', {
|
|
48
|
+
description: '列出扩展实际支持的平台、登录状态、publishModes、对应 tools 及 modeOptions 限制;小红书 article 对应 publish_article,image/video 对应 publish_post。不会返回 Cookie。',
|
|
49
|
+
inputSchema: { force_refresh: z.boolean().optional() }, annotations: { ...readOnly, openWorldHint: true },
|
|
50
|
+
}, args => wrap(() => bridge.request('listPlatforms', { forceRefresh: args.force_refresh === true })))
|
|
51
|
+
server.registerTool('check_auth', {
|
|
52
|
+
description: '检查指定平台的登录状态,未登录时请用户在装有扩展的浏览器登录。',
|
|
53
|
+
inputSchema: { platform: z.string().min(1) }, annotations: { ...readOnly, openWorldHint: true },
|
|
54
|
+
}, args => wrap(() => bridge.request('checkAuth', { platform: args.platform })))
|
|
55
|
+
server.registerTool('prepare_article', {
|
|
56
|
+
description: '可选:将 agent 写好的 Markdown/HTML、本地图片和知乎文章内 MP4 视频存入扩展供预览。本工具只准备本机稿件,不向平台提交;直发也可直接调用 publish_article。file_path、markdown、html 三选一。内嵌视频写成 <video src="本地路径"></video>,最多 5 个、总量 512 MB。',
|
|
57
|
+
inputSchema: source, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
|
58
|
+
}, args => wrap(async () => bridge.request('prepareArticle', { article: await prepareSource(args, path => bridge.registerMedia(path, 'video')) })))
|
|
59
|
+
server.registerTool('publish_article', {
|
|
60
|
+
description: agentWorkflow + '直接发布 Agent 写好的知乎、百家号、微博长文章、B站专栏或小红书长文。小红书 platforms=["xiaohongshu"],接收标题最多 64 字、正文最多 10000 字的 Markdown/HTML 及正文图片,走写长文→原生自动排版→下一步→发布;不接独立 cover、文章内视频或长文话题。普通图文和独立视频改用 publish_post。B站仅接文字和正文图片,标题长度按原生页面校验;不接视频、音频、附加内容卡片或独立 cover。原生新版编辑器生成 WBI 签名和风控参数,验证码 code=-352 时返回 needs_user_action,Agent 让用户在已打开的原稿件页完成验证并手动发布,不重发。微博长文章支持正文图片和封面,无独立封面时使用本篇首图,无正文图片时需 cover,当前标题接收 32 字以内;不接视频 URL,不自动关注官方账号或声明原创。验证码及原创协议转人工处理,用户完成验证后还需检查发布确认窗口。传 file_path/markdown/html 三选一,或 prepare_article 的 draft_id;无需用户在扩展编写。百家号必须提供 cover(本地封面图片路径或图片地址),当前标题接收 64 字以内;验证码或封面需人工处理时返回 needs_user_action,Agent 必须把原因和原稿件链接交给用户,不重试、不换 request_id。知乎支持正文图片和 <video src="本地MP4路径"></video> 内嵌视频,标题最多 100 字,不支持单独设置封面和话题。cover 可用于百家号和微博长文章;内嵌视频只允许单独投知乎。扩展触发平台原生发布。知乎优先核对匹配文章 ID 的 HTTP 成功响应,也可由扩展在同一任务标签页核对匹配文章 ID、标题的原生发布成功弹窗,confirmation 区分 http_response/native_page_message;仅跳转不算成功。其他文章平台按各自匹配的最终 HTTP 回执确认 submitted。返回 task_id 后查询 get_sync_task。',
|
|
61
|
+
inputSchema: { ...source, cover: source.cover.describe('平台封面:本地图片路径、HTTP(S) 图片地址或 data URI;按 list_platforms 的 cover 能力和 coverRequired 提供。当前百家号必填、微博长文章可选,知乎、B站专栏和小红书长文不支持独立封面'), request_id: requestId, platforms: z.array(z.string().min(1)).min(1).max(30).describe('先按 list_platforms 的 action=publish 和 publishModes=article 选择;实际支持范围由扩展校验'), draft_id: z.string().optional() },
|
|
62
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
63
|
+
}, args => wrap(async () => {
|
|
64
|
+
if (args.draft_id && Object.entries(args).some(([key, value]) => key in source && value !== undefined)) throw new Error('draft_id 与稿件内容不能同时提供')
|
|
65
|
+
return bridge.request('publishArticle', {
|
|
66
|
+
requestId: args.request_id, platforms: args.platforms,
|
|
67
|
+
...(args.draft_id ? { draftId: args.draft_id } : { article: await prepareSource(args, path => bridge.registerMedia(path, 'video')) }),
|
|
68
|
+
})
|
|
69
|
+
}))
|
|
70
|
+
server.registerTool('prepare_post', {
|
|
71
|
+
description: '准备小红书/抖音/微博普通图文或独立视频及本地素材,只保存本机预览,不点击发布。小红书写长文用 prepare_article / publish_article;小红书视频省略 cover_path 时由平台取第一帧封面。微博长文章仍用 prepare_article / publish_article。素材通过本机授权分块传输,不把视频嵌入 MCP 消息。返回 draft_id 供 publish_post 使用;素材授权两小时有效,MCP 重启后请重新准备。微博视频请明确传入 weibo_video_creation。',
|
|
72
|
+
inputSchema: postSource, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
|
73
|
+
}, args => wrap(async () => bridge.request('preparePost', { post: await preparePost(args, (path, kind) => bridge.registerMedia(path, kind)) })))
|
|
74
|
+
server.registerTool('publish_post', {
|
|
75
|
+
description: agentWorkflow + '直接向用户明确指定的小红书/抖音/微博公开投稿(平台可能先审核),支持图文和独立视频。小红书 ID 为 xiaohongshu,kind=image 上传图片后填写标题/正文并发布,kind=video 上传视频后发布,省略 cover_path 时沿用平台视频第一帧封面;写长文必须用 publish_article。小红书仅在本任务 POST /web_api/sns/v2/note 返回 success=true、result=0 及有效笔记 ID 时确认 submitted。抖音 ID 为 douyin,kind=image/video 复用原生上传、填写和发布流程,可选视频 cover_path,当前仅接即时发布;图文话题最多 4 个、视频最多 5 个。抖音以本次操作新增的原生成功提示确认 submitted,confirmation=native_page_message,未接最终 HTTP 业务回执核对;页面跳转本身不算成功,缺少明确提示则返回 unknown,不能重发。微博 ID 为 weibo,kind=image 最多 18 张,标题并入正文首行;kind=video 必须明确 weibo_video_creation(original/secondary/repost),标题最多 30 个汉字或 60 个半角字符。微博图文/视频互斥,长文章使用 publish_article。可传 prepare_post 的 draft_id,或直接传完整素材参数。通过平台原生页面上传并发送,微博只有匹配本任务的 statuses/update 成功回执才确认 submitted。验证码、来源、内容声明、封面或协议需人工处理时返回 needs_user_action,Agent 应把原因和原投稿页链接告知用户,不重试。必须使用稳定 request_id;返回 task_id 后查询 get_sync_task,unknown 时将链接交给用户自行核对,Agent 不调用浏览器。',
|
|
76
|
+
inputSchema: { ...postSource, kind: postSource.kind.optional(), title: postSource.title.optional(), draft_id: z.string().optional(), request_id: requestId, platforms: z.array(z.string().min(1)).min(1).max(30).describe('按 list_platforms 返回的 publishModes=image/video 及工具信息选择,当前为 xiaohongshu、douyin、weibo;由扩展校验,后续平台变更不要求固定枚举升级') },
|
|
77
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
78
|
+
}, args => wrap(async () => {
|
|
79
|
+
if (args.draft_id && Object.entries(args).some(([key, value]) => key in postSource && value !== undefined)) throw new Error('draft_id 与投稿内容不能同时提供')
|
|
80
|
+
if (!args.draft_id && (!args.kind || !args.title)) throw new Error('请提供 draft_id,或完整的 kind、title 和素材路径')
|
|
81
|
+
return bridge.request('publishPost', { requestId: args.request_id, platforms: args.platforms, ...(args.draft_id ? { draftId: args.draft_id } : { post: await preparePost({ ...args, kind: args.kind!, title: args.title! }, (path, kind) => bridge.registerMedia(path, kind)) }) })
|
|
82
|
+
}))
|
|
83
|
+
server.registerTool('sync_article', {
|
|
84
|
+
description: '向 list_platforms 返回 action=draft 的用户指定平台保存文章草稿,当前包括微信公众号、搜狐号。知乎、百家号、微博长文章、B站专栏、小红书长文已改用 publish_article;本工具不会把旧草稿调用自动升级成公开发布。可用 prepare_article 返回的 draft_id,或直接传 file_path/markdown/html。必须给同一操作使用稳定 request_id;相同 ID 重放不会重复提交。立即返回 task_id,再用 get_sync_task 查询进度。',
|
|
85
|
+
inputSchema: { ...source, request_id: requestId, platforms: z.array(z.string().min(1)).min(1).max(30), draft_id: z.string().optional() },
|
|
86
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
87
|
+
}, args => wrap(async () => {
|
|
88
|
+
if (args.draft_id && Object.entries(args).some(([key, value]) => key in source && value !== undefined)) throw new Error('draft_id 与稿件内容不能同时提供;请先保存修改后的稿件,再发起同步')
|
|
89
|
+
return bridge.request('syncArticle', {
|
|
90
|
+
requestId: args.request_id, platforms: args.platforms,
|
|
91
|
+
...(args.draft_id ? { draftId: args.draft_id } : { article: await prepareSource(args) }),
|
|
92
|
+
})
|
|
93
|
+
}))
|
|
94
|
+
server.registerTool('get_sync_task', {
|
|
95
|
+
description: agentWorkflow + '查询发布或草稿任务的进度、逐平台结果及内容链接。publicationState=submitted 表示扩展已按平台 confirmation 确认提交;needs_user_action 或 requires_user_action 表示需要用户接管,请将 user_actions 中的原因与链接告诉用户手动处理,不重新投稿;unknown 表示结果未确认,不能自动重发。可传 task_id 或原 request_id。',
|
|
96
|
+
inputSchema: { task_id: z.string().optional(), request_id: z.string().optional() }, annotations: readOnly,
|
|
97
|
+
}, args => wrap(() => bridge.request('getSyncTask', { taskId: args.task_id, requestId: args.request_id })))
|
|
98
|
+
server.registerTool('list_sync_history', {
|
|
99
|
+
description: '读取最近 25 次同步结果。删除本机稿件后,其关联历史也会删除。', inputSchema: {}, annotations: readOnly,
|
|
100
|
+
}, () => wrap(() => bridge.request('getSyncHistory')))
|
|
101
|
+
return server
|
|
102
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"lib": [
|
|
5
|
+
"ES2022",
|
|
6
|
+
"DOM",
|
|
7
|
+
"DOM.Iterable"
|
|
8
|
+
],
|
|
9
|
+
"module": "ESNext",
|
|
10
|
+
"moduleResolution": "bundler",
|
|
11
|
+
"resolveJsonModule": true,
|
|
12
|
+
"isolatedModules": true,
|
|
13
|
+
"esModuleInterop": true,
|
|
14
|
+
"strict": true,
|
|
15
|
+
"skipLibCheck": true,
|
|
16
|
+
"declaration": true,
|
|
17
|
+
"declarationMap": true,
|
|
18
|
+
"sourceMap": true,
|
|
19
|
+
"baseUrl": ".",
|
|
20
|
+
"types": [
|
|
21
|
+
"node"
|
|
22
|
+
],
|
|
23
|
+
"noEmit": true
|
|
24
|
+
},
|
|
25
|
+
"exclude": [
|
|
26
|
+
"node_modules",
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"include": [
|
|
30
|
+
"src/**/*.ts"
|
|
31
|
+
]
|
|
32
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { defineConfig } from 'tsup'
|
|
2
|
+
export default defineConfig({
|
|
3
|
+
entry: ['src/index.ts'], format: ['cjs'], platform: 'node', target: 'node22',
|
|
4
|
+
outExtension: () => ({ js: '.cjs' }), clean: true, sourcemap: false, metafile: true,
|
|
5
|
+
noExternal: [/.*/], external: ['bufferutil', 'utf-8-validate'],
|
|
6
|
+
})
|