dsh-cothread-mcp 0.1.0 → 0.1.3

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/package.json CHANGED
@@ -1,23 +1,37 @@
1
1
  {
2
2
  "name": "dsh-cothread-mcp",
3
- "version": "0.1.0",
4
- "description": "连接共序 CoThread 远程 MCP(https://cothread.z2l.top/mcp),按账号身份与项目成员权限协作。令牌只保存在插件配置里,不写入源码或日志。",
3
+ "version": "0.1.3",
4
+ "description": "连接共序 CoThread MCP,支持浏览器授权、项目设置及消息提醒。",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/NingYuanLee/dsh-cothread-mcp.git"
9
+ },
6
10
  "type": "module",
7
11
  "main": "src/index.js",
8
12
  "exports": {
9
13
  ".": "./src/index.js",
14
+ "./client": "./lib/client.js",
10
15
  "./package.json": "./package.json"
11
16
  },
12
17
  "files": [
13
18
  "src",
19
+ "lib/client.js",
20
+ "scripts/build.mjs",
14
21
  "cordis.patch.yml",
15
22
  "icon.svg",
23
+ "LICENSE",
24
+ "CHANGELOG.md",
16
25
  "README.md"
17
26
  ],
27
+ "scripts": {
28
+ "test": "node --test test/*.test.js",
29
+ "check": "node --check src/index.js && node --check src/authorization.js && node --check src/device.js && node --check src/version.js && node --check src/environments.js && node --check src/service.js && node --check src/events.js && node --check src/automation.js && node --check src/state.js && node --check lib/client.js",
30
+ "build": "node scripts/build.mjs"
31
+ },
18
32
  "engines": {
19
33
  "node": ">=22.19.0",
20
- "dsh": ">=0.2.1-rc.2 <0.3.0-0"
34
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-0 <0.3.0-0"
21
35
  },
22
36
  "keywords": [
23
37
  "dsh",
@@ -33,11 +47,21 @@
33
47
  "manifestVersion": 1,
34
48
  "bundle": {
35
49
  "patch": "./cordis.patch.yml"
50
+ },
51
+ "client": {
52
+ "inject": [
53
+ "@deepseek-ai/dsh-client-ui-settings",
54
+ "@deepseek-ai/dsh-api-settings-controller",
55
+ "@deepseek-ai/dsh-client-ui-conversation"
56
+ ],
57
+ "platform": "web"
36
58
  }
37
59
  },
38
60
  "peerDependencies": {
39
61
  "@deepseek-ai/cordis": ">=4.0.4 <5.0.0",
62
+ "@deepseek-ai/dsh-credentials": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
40
63
  "@deepseek-ai/dsh-mcp-client": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
41
- "@deepseek-ai/schemastery": ">=3.18.4 <4.0.0"
64
+ "@deepseek-ai/schemastery": ">=3.18.4 <4.0.0",
65
+ "@deepseek-ai/dsh-session": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0"
42
66
  }
43
67
  }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 发布前的构建期校验。
3
+ *
4
+ * 这个仓库没有编译产物:lib/client.js 是手写的浏览器 bundle,
5
+ * 源码直接就是发布内容。所以 build 做的是「发布物完整性」检查:
6
+ * 每个源文件都能被解析,package.json 的 files 覆盖了实际要发的文件,
7
+ * 并且版本号在 CHANGELOG 里有对应条目——漏掉任何一样都会在发布时才暴露。
8
+ */
9
+ import { readFile, readdir, stat } from 'node:fs/promises'
10
+ import { dirname, join, resolve } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import { execFile } from 'node:child_process'
13
+ import { promisify } from 'node:util'
14
+
15
+ const run = promisify(execFile)
16
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
17
+
18
+ async function listSources(dir) {
19
+ const found = []
20
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
21
+ const full = join(dir, entry.name)
22
+ if (entry.isDirectory()) { found.push(...await listSources(full)); continue }
23
+ if (entry.name.endsWith('.js') || entry.name.endsWith('.mjs')) found.push(full)
24
+ }
25
+ return found
26
+ }
27
+
28
+ const problems = []
29
+
30
+ // 1) 每个源文件都要能被解析
31
+ for (const dir of ['src', 'lib', 'scripts', 'test']) {
32
+ let files = []
33
+ try { files = await listSources(join(root, dir)) } catch { continue }
34
+ for (const file of files) {
35
+ try { await run(process.execPath, ['--check', file]) }
36
+ catch (error) { problems.push(`语法错误:${file.replace(root + '\\', '')}\n${String(error.stderr || error.message).split('\n').slice(0, 4).join('\n')}`) }
37
+ }
38
+ }
39
+
40
+ // 2) package.json 的 files 必须覆盖实际要发的文件
41
+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
42
+ // package.json、README、LICENSE 由 npm 自动附带,不必列进 files
43
+ for (const required of ['src', 'lib/client.js', 'scripts/build.mjs', 'CHANGELOG.md', 'icon.svg']) {
44
+ if (!Array.isArray(pkg.files) || !pkg.files.includes(required)) problems.push(`package.json 的 files 里少了 ${required}`)
45
+ }
46
+ if (!pkg.version) problems.push('package.json 缺少 version')
47
+ if (!pkg.exports?.['.'] || !pkg.exports?.['./client']) problems.push('package.json 缺少主入口或 client 入口')
48
+
49
+ // 3) CHANGELOG 要有当前版本的条目
50
+ const changelog = await readFile(join(root, 'CHANGELOG.md'), 'utf8')
51
+ if (!changelog.includes(`## ${pkg.version}`)) problems.push(`CHANGELOG.md 里没有 ${pkg.version} 的条目`)
52
+
53
+ // 4) 图标得在
54
+ try { await stat(join(root, 'icon.svg')) } catch { problems.push('缺少 icon.svg') }
55
+
56
+ if (problems.length) {
57
+ console.error('构建校验未通过:')
58
+ for (const problem of problems) console.error(' - ' + problem)
59
+ process.exit(1)
60
+ }
61
+ console.log(`构建校验通过:版本 ${pkg.version}`)
@@ -0,0 +1,144 @@
1
+ import { createServer } from 'node:http'
2
+ import { randomUUID } from 'node:crypto'
3
+ import os from 'node:os'
4
+
5
+ /** 问一次服务端「这次授权怎么样了」的间隔。 */
6
+ const DEFAULT_POLL_INTERVAL_MS = 3000
7
+ /** 服务端已拍板、但凭据还没回传时的宽限时间。 */
8
+ const DEFAULT_DELIVERY_GRACE_MS = 20000
9
+
10
+ /**
11
+ * 发起一次 Agent 插件授权。
12
+ *
13
+ * @param {string} endpoint 服务根地址
14
+ * @param {object} options
15
+ * @param {Function} options.fetchImpl 便于测试
16
+ * @param {number} options.timeoutMs 整体超时
17
+ * @param {string} options.deviceId 本机稳定的设备身份;不传就临时生成一个
18
+ * @param {string} options.version 插件版本号
19
+ * @param {number} options.pollIntervalMs 轮询间隔
20
+ * @param {number} options.deliveryGraceMs 凭据回传的宽限时间
21
+ */
22
+ export async function startAuthorization(endpoint, {
23
+ fetchImpl = fetch,
24
+ timeoutMs = 600000,
25
+ deviceId,
26
+ version = '0.0.0',
27
+ pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
28
+ deliveryGraceMs = DEFAULT_DELIVERY_GRACE_MS,
29
+ } = {}) {
30
+ const origin = new URL(endpoint).origin
31
+ // 设备身份必须稳定:服务端按 device_id 认设备,每次都换新 ID 会被当成新设备——
32
+ // 旧连接器被撤销、新记录重建,而「一个成员只能有一条 active 绑定」的唯一索引
33
+ // 会让这次授权直接撞上冲突,浏览器点「确认授权」只会看到「记录已存在」。
34
+ const localDeviceId = typeof deviceId === 'string' && deviceId.trim() ? deviceId.trim() : randomUUID()
35
+ const response = await fetchImpl(new URL('/api/local-executor/v2/authorizations', origin), {
36
+ method: 'POST', headers: { 'content-type': 'application/json' },
37
+ body: JSON.stringify({ name: `DSH · ${os.hostname()}`, deviceId: localDeviceId, platform: process.platform, version }),
38
+ signal: AbortSignal.timeout(10000),
39
+ })
40
+ if (!response.ok) throw new Error(`创建授权请求失败(HTTP ${response.status})`)
41
+ const request = await response.json()
42
+ if (!request.id || !request.pollToken || !request.verificationUrl) throw new Error('授权响应不完整')
43
+ let verificationUrl = new URL(request.verificationUrl)
44
+ // The current CoThread server always returns APP_ORIGIN, including in local development.
45
+ // Rebase only its known authorization URL; never follow an arbitrary foreign origin.
46
+ if (origin === 'http://127.0.0.1:3100' && verificationUrl.origin === 'https://cothread.z2l.top' && verificationUrl.pathname === '/' && verificationUrl.searchParams.get('localExecutorAuthorization') === request.id) {
47
+ verificationUrl = new URL(verificationUrl.pathname + verificationUrl.search, origin)
48
+ }
49
+ if (verificationUrl.origin !== origin) throw new Error('授权页面与服务地址不一致')
50
+ let timer
51
+ let pollTimer
52
+ let graceTimer
53
+ let settled = false
54
+ let resolveResult
55
+ let rejectResult
56
+ const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
57
+ // A rejected result may arrive before callers attach their handler.
58
+ result.catch(() => {})
59
+ function finish() { clearTimeout(timer); clearInterval(pollTimer); clearTimeout(graceTimer); server.close() }
60
+ function succeed(payload) { if (settled) return; settled = true; finish(); resolveResult(payload) }
61
+ function fail(error) { if (settled) return; settled = true; finish(); rejectResult(error) }
62
+ const server = createServer((req, res) => {
63
+ if (req.headers.origin !== origin || req.url !== '/local-executor-authorization') { res.writeHead(403).end(); return }
64
+ res.setHeader('Access-Control-Allow-Origin', origin)
65
+ res.setHeader('Vary', 'Origin')
66
+ res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
67
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
68
+ res.setHeader('Access-Control-Private-Network', 'true')
69
+ if (req.method === 'OPTIONS') { res.writeHead(204).end(); return }
70
+ if (req.method !== 'POST') { res.writeHead(405).end(); return }
71
+ let body = ''
72
+ req.setEncoding('utf8')
73
+ req.on('data', chunk => { body += chunk; if (body.length > 8192) req.destroy() })
74
+ req.on('end', () => {
75
+ let data
76
+ try { data = JSON.parse(body) } catch { res.writeHead(400).end(); return }
77
+ if (data.authorizationId !== request.id || data.callbackSecret !== request.pollToken) { res.writeHead(403).end(); return }
78
+ if (data.status === 'approved' && typeof data.token === 'string' && data.token.startsWith('ctc_')) {
79
+ res.writeHead(200).end()
80
+ // deviceId 是我们发出去的身份(服务端按它认设备);data.id 是服务端那条连接器记录的 id,只用于排查。
81
+ succeed({ deviceId: localDeviceId, executorId: typeof data.id === 'string' ? data.id : '', token: data.token })
82
+ } else if (data.status === 'denied') {
83
+ res.writeHead(200).end(); fail(new Error('用户已拒绝授权'))
84
+ } else res.writeHead(400).end()
85
+ })
86
+ })
87
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })
88
+ verificationUrl.searchParams.set('localExecutorCallbackPort', String(server.address().port))
89
+ verificationUrl.searchParams.set('localExecutorClient', 'dsh')
90
+ const hash = new URLSearchParams(verificationUrl.hash.slice(1))
91
+ hash.set('connectorCallbackSecret', request.pollToken)
92
+ verificationUrl.hash = hash.toString()
93
+ timer = setTimeout(() => fail(new Error('授权已超时,请重新发起')), Math.min(timeoutMs, Number(request.expiresIn || 600) * 1000))
94
+ timer.unref?.()
95
+
96
+ /**
97
+ * 问一次服务端这次授权怎么样了。
98
+ *
99
+ * 浏览器那边点「拒绝」或者关掉弹窗时,回环回调可能永远不来(回调是浏览器页面发的,
100
+ * 页面关了就没了),插件就只能干等到超时。这里轮询服务端已有的 poll 接口,
101
+ * 让「用户拒绝」能立刻结束。
102
+ */
103
+ async function pollOnce() {
104
+ if (settled) return
105
+ let response
106
+ try {
107
+ response = await fetchImpl(new URL(`/api/local-executor/v2/authorizations/${request.id}/poll`, origin), {
108
+ method: 'POST', headers: { 'content-type': 'application/json' },
109
+ body: JSON.stringify({ pollToken: request.pollToken }),
110
+ signal: AbortSignal.timeout(10000),
111
+ })
112
+ } catch { return }
113
+ if (settled) return
114
+ if (response.status === 403) { fail(new Error('用户已拒绝授权')); return }
115
+ if (response.status === 410) { fail(new Error('网页登录授权已过期,请重新发起')); return }
116
+ if (response.status === 409) {
117
+ // 授权结果已经被领取:浏览器已经拍板,凭据正在回传的路上(也可能没传回来)。
118
+ // 这是正常终态,不再轮询;但留一点时间等回环回调,等到还没消息就明确报错。
119
+ clearInterval(pollTimer); pollTimer = undefined
120
+ graceTimer = setTimeout(() => fail(new Error('浏览器已确认授权,但凭据没有回传到本机,请重新授权')), deliveryGraceMs)
121
+ graceTimer.unref?.()
122
+ return
123
+ }
124
+ if (!response.ok) return
125
+ let data
126
+ try { data = await response.json() } catch { return }
127
+ if (data && data.status === 'approved' && typeof data.token === 'string' && data.token.startsWith('ctc_')) {
128
+ succeed({ deviceId: localDeviceId, executorId: typeof data.id === 'string' ? data.id : '', token: data.token })
129
+ }
130
+ }
131
+ pollTimer = setInterval(() => { void pollOnce() }, pollIntervalMs)
132
+ pollTimer.unref?.()
133
+ return { url: verificationUrl.href, result, cancel() { fail(new Error('授权已取消')) } }
134
+ }
135
+
136
+ export async function getMcpCredential(endpoint, deviceToken, fetchImpl = fetch) {
137
+ const response = await fetchImpl(new URL('/api/local-executor/mcp-credential', endpoint), {
138
+ method: 'POST', headers: { authorization: `Bearer ${deviceToken}` }, signal: AbortSignal.timeout(10000),
139
+ })
140
+ if (!response.ok) throw new Error(`获取 MCP 凭据失败(HTTP ${response.status})`)
141
+ const data = await response.json()
142
+ if (typeof data.token !== 'string' || !data.token) throw new Error('MCP 凭据响应不完整')
143
+ return data
144
+ }