@buaa_smat/hometrans 0.1.0

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.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `ht config` — 打印 editors.json 路径与内容。
3
+ *
4
+ * 该命令只读:用户若要修改 editor 配置,直接编辑这个 JSON 文件即可。
5
+ * 文件不存在时自动写入默认 4 个 editor。
6
+ */
7
+ import fs from 'node:fs/promises';
8
+ import { getConfigPath, loadHomeTransConfig } from './config-store.js';
9
+ export async function configCommand() {
10
+ const configPath = getConfigPath();
11
+ // 触发不存在则写默认值的逻辑
12
+ await loadHomeTransConfig();
13
+ const raw = await fs.readFile(configPath, 'utf-8');
14
+ console.log('');
15
+ console.log(' HomeTrans Editor Config');
16
+ console.log(' =======================');
17
+ console.log('');
18
+ console.log(` Path: ${configPath}`);
19
+ console.log('');
20
+ console.log(' Content:');
21
+ console.log('');
22
+ for (const line of raw.replace(/\r?\n$/, '').split(/\r?\n/)) {
23
+ console.log(` ${line}`);
24
+ }
25
+ console.log('');
26
+ console.log(' Edit this file to add or modify editors, then re-run `ht init`.');
27
+ console.log('');
28
+ }
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { createRequire } from 'node:module';
4
+ import { initCommand } from './init.js';
5
+ import { runMcpServer } from './mcp.js';
6
+ import { configCommand } from './config.js';
7
+ import { uninstallCommand } from './uninstall.js';
8
+ const _require = createRequire(import.meta.url);
9
+ const pkg = _require('../../package.json');
10
+ const program = new Command();
11
+ program
12
+ .name('hometrans')
13
+ .description('HomeTrans installer — distribute Android-to-HarmonyOS skills and agents into AI editors')
14
+ .version(pkg.version);
15
+ program
16
+ .command('init')
17
+ .description('Initialize HomeTrans — select editors and install skills, agents, and MCP servers')
18
+ .action(async () => {
19
+ await initCommand();
20
+ });
21
+ program
22
+ .command('mcp')
23
+ .description('Run the HomeTrans MCP server (stdio)')
24
+ .action(async () => {
25
+ await runMcpServer();
26
+ });
27
+ program
28
+ .command('config')
29
+ .description('Show the editors.json path and content (~/.hometrans/editors.json). Edit the file directly to customize editors, then re-run `ht init`.')
30
+ .action(async () => {
31
+ await configCommand();
32
+ });
33
+ program
34
+ .command('uninstall')
35
+ .description('Remove all hometrans skills, agents, and MCP entries from configured editors')
36
+ .action(async () => {
37
+ await uninstallCommand();
38
+ });
39
+ program.parseAsync(process.argv).catch((err) => {
40
+ console.error(err instanceof Error ? err.message : err);
41
+ process.exit(1);
42
+ });
@@ -0,0 +1,224 @@
1
+ /**
2
+ * `ht init` — interactive initialization for HomeTrans.
3
+ *
4
+ * Displays the HomeTrans banner, lets the user select which editors to
5
+ * configure, then copies bundled skills/agents and registers MCP servers
6
+ * for the chosen editors.
7
+ */
8
+ import fs from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import os from 'node:os';
11
+ import { fileURLToPath } from 'node:url';
12
+ import chalk from 'chalk';
13
+ import figlet from 'figlet';
14
+ import inquirer from 'inquirer';
15
+ import { setupMcpForAllEditors } from './mcp-setup.js';
16
+ import { expandHome, loadHomeTransConfig, } from './config-store.js';
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = path.dirname(__filename);
19
+ export async function dirExists(dirPath) {
20
+ try {
21
+ const stat = await fs.stat(dirPath);
22
+ return stat.isDirectory();
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ async function copyDirRecursive(src, dest) {
29
+ await fs.mkdir(dest, { recursive: true });
30
+ const entries = await fs.readdir(src, { withFileTypes: true });
31
+ for (const entry of entries) {
32
+ const srcPath = path.join(src, entry.name);
33
+ const destPath = path.join(dest, entry.name);
34
+ if (entry.isDirectory()) {
35
+ await copyDirRecursive(srcPath, destPath);
36
+ }
37
+ else {
38
+ await fs.copyFile(srcPath, destPath);
39
+ }
40
+ }
41
+ }
42
+ function resolveSkillsRoot() {
43
+ return path.resolve(__dirname, '..', '..', 'skills');
44
+ }
45
+ function resolveAgentsRoot() {
46
+ return path.resolve(__dirname, '..', '..', 'agents');
47
+ }
48
+ async function installSkillsTo(skillsRoot, targetDir) {
49
+ let entries;
50
+ try {
51
+ entries = await fs.readdir(skillsRoot, { withFileTypes: true });
52
+ }
53
+ catch {
54
+ return [];
55
+ }
56
+ const installed = [];
57
+ for (const entry of entries) {
58
+ if (!entry.isDirectory())
59
+ continue;
60
+ const skillSrc = path.join(skillsRoot, entry.name);
61
+ const hasSkillFile = await fs
62
+ .access(path.join(skillSrc, 'SKILL.md'))
63
+ .then(() => true)
64
+ .catch(() => false);
65
+ if (!hasSkillFile)
66
+ continue;
67
+ const skillDest = path.join(targetDir, entry.name);
68
+ await copyDirRecursive(skillSrc, skillDest);
69
+ installed.push(entry.name);
70
+ }
71
+ return installed;
72
+ }
73
+ async function installAgentsTo(agentsRoot, targetDir) {
74
+ let entries;
75
+ try {
76
+ entries = await fs.readdir(agentsRoot, { withFileTypes: true });
77
+ }
78
+ catch {
79
+ return [];
80
+ }
81
+ await fs.mkdir(targetDir, { recursive: true });
82
+ const installed = [];
83
+ for (const entry of entries) {
84
+ const srcPath = path.join(agentsRoot, entry.name);
85
+ const destPath = path.join(targetDir, entry.name);
86
+ if (entry.isDirectory()) {
87
+ await copyDirRecursive(srcPath, destPath);
88
+ }
89
+ else if (entry.isFile()) {
90
+ await fs.copyFile(srcPath, destPath);
91
+ if (entry.name.endsWith('.md')) {
92
+ installed.push(entry.name.slice(0, -3));
93
+ }
94
+ }
95
+ }
96
+ return installed;
97
+ }
98
+ async function installForEditor(editor, skillsRoot, agentsRoot, result) {
99
+ const marker = expandHome(editor.markerDir);
100
+ if (marker && !(await dirExists(marker))) {
101
+ result.skipped.push(`${editor.name} (not installed)`);
102
+ return;
103
+ }
104
+ const skillsDir = expandHome(editor.skillsDir);
105
+ const agentsDir = expandHome(editor.agentsDir);
106
+ try {
107
+ const skills = await installSkillsTo(skillsRoot, skillsDir);
108
+ if (skills.length > 0) {
109
+ result.configured.push(`${editor.name} skills (${skills.length} -> ${prettyHome(skillsDir)})`);
110
+ }
111
+ }
112
+ catch (err) {
113
+ result.errors.push(`${editor.name} skills: ${err.message}`);
114
+ }
115
+ try {
116
+ const agents = await installAgentsTo(agentsRoot, agentsDir);
117
+ if (agents.length > 0) {
118
+ result.configured.push(`${editor.name} agents (${agents.length} -> ${prettyHome(agentsDir)})`);
119
+ }
120
+ }
121
+ catch (err) {
122
+ result.errors.push(`${editor.name} agents: ${err.message}`);
123
+ }
124
+ }
125
+ export function prettyHome(p) {
126
+ const home = os.homedir();
127
+ if (p.startsWith(home)) {
128
+ return '~' + p.slice(home.length).replace(/\\/g, '/');
129
+ }
130
+ return p.replace(/\\/g, '/');
131
+ }
132
+ async function detectInstalledEditors(editors) {
133
+ const status = new Map();
134
+ for (const editor of editors) {
135
+ const marker = expandHome(editor.markerDir);
136
+ if (!marker) {
137
+ status.set(editor.name, true);
138
+ }
139
+ else {
140
+ status.set(editor.name, await dirExists(marker));
141
+ }
142
+ }
143
+ return status;
144
+ }
145
+ export async function initCommand() {
146
+ const banner = figlet.textSync('HomeTrans', { font: 'Standard' });
147
+ console.log(chalk.cyan(`\n${banner.trimEnd()}`));
148
+ console.log(chalk.gray('\n Android-to-HarmonyOS skill & agent installer for AI editors\n'));
149
+ const skillsRoot = resolveSkillsRoot();
150
+ const agentsRoot = resolveAgentsRoot();
151
+ const hasSkills = await dirExists(skillsRoot);
152
+ const hasAgents = await dirExists(agentsRoot);
153
+ if (!hasSkills && !hasAgents) {
154
+ console.error(chalk.red(` ! Neither skills/ nor agents/ found at package root.`));
155
+ console.error(chalk.gray(` Looked in: ${skillsRoot}`));
156
+ console.error(chalk.gray(` ${agentsRoot}`));
157
+ console.error(chalk.gray(' Reinstall hometrans or run `npm run build` from the package root.'));
158
+ process.exitCode = 1;
159
+ return;
160
+ }
161
+ const { editors } = await loadHomeTransConfig();
162
+ const installedStatus = await detectInstalledEditors(editors);
163
+ const choices = editors.map((editor) => {
164
+ const installed = installedStatus.get(editor.name);
165
+ const label = installed
166
+ ? `${editor.name} ${chalk.green('(detected)')}`
167
+ : `${editor.name} ${chalk.gray('(not detected)')}`;
168
+ return {
169
+ name: label,
170
+ value: editor.name,
171
+ checked: installed,
172
+ };
173
+ });
174
+ const { selectedEditors } = await inquirer.prompt([
175
+ {
176
+ type: 'checkbox',
177
+ name: 'selectedEditors',
178
+ message: 'Select editors to configure:',
179
+ choices,
180
+ },
181
+ ]);
182
+ if (selectedEditors.length === 0) {
183
+ console.log(chalk.yellow('\n No editors selected. Nothing to do.\n'));
184
+ return;
185
+ }
186
+ console.log('');
187
+ const editorsToSetup = editors.filter((e) => selectedEditors.includes(e.name));
188
+ const result = { configured: [], skipped: [], errors: [] };
189
+ for (const editor of editorsToSetup) {
190
+ console.log(chalk.blue(` Configuring ${editor.name}...`));
191
+ await installForEditor(editor, skillsRoot, agentsRoot, result);
192
+ }
193
+ await setupMcpForAllEditors(editorsToSetup, result);
194
+ console.log('');
195
+ if (result.configured.length > 0) {
196
+ console.log(chalk.green(' Configured:'));
197
+ for (const name of result.configured)
198
+ console.log(chalk.green(` + ${name}`));
199
+ }
200
+ if (result.skipped.length > 0) {
201
+ console.log('');
202
+ console.log(chalk.yellow(' Skipped:'));
203
+ for (const name of result.skipped)
204
+ console.log(chalk.yellow(` - ${name}`));
205
+ }
206
+ if (result.errors.length > 0) {
207
+ console.log('');
208
+ console.log(chalk.red(' Errors:'));
209
+ for (const err of result.errors)
210
+ console.log(chalk.red(` ! ${err}`));
211
+ }
212
+ console.log('');
213
+ console.log(chalk.gray(` Source skills: ${skillsRoot}`));
214
+ console.log(chalk.gray(` Source agents: ${agentsRoot}`));
215
+ console.log('');
216
+ if (result.configured.length === 0 && result.errors.length === 0) {
217
+ console.log(chalk.yellow(' No editors were configured. Make sure the selected editors are installed,'));
218
+ console.log(chalk.yellow(' then re-run `ht init`.'));
219
+ }
220
+ else {
221
+ console.log(chalk.green(' Done. Re-open your editor for the new skills/agents to be picked up.'));
222
+ }
223
+ console.log('');
224
+ }
@@ -0,0 +1,262 @@
1
+ /**
2
+ * `ht init` 阶段:按 editors.json 中每个 editor 的 mcp.format 把 hometrans MCP
3
+ * server 注册到对应的 editor 配置文件。
4
+ *
5
+ * 支持的 mcp.format:
6
+ * jsonc-object Cursor / Claude Code 风格:jsonc 文件,key 路径写对象
7
+ * jsonc-command-array OpenCode 风格:jsonc 文件,value 是 {type, command:[]}
8
+ * codex-cli Codex:优先 `codex mcp add`,失败回退追加 TOML section
9
+ * toml-section 纯 TOML:追加 [<section>] 段
10
+ * none 跳过 MCP 写入
11
+ */
12
+ import fs from 'node:fs/promises';
13
+ import path from 'node:path';
14
+ import { execFile, execFileSync } from 'node:child_process';
15
+ import { createRequire } from 'node:module';
16
+ import { promisify } from 'node:util';
17
+ import { parseTree, modify, applyEdits, } from 'jsonc-parser';
18
+ import { dirExists } from './init.js';
19
+ import { expandHome } from './config-store.js';
20
+ const execFileAsync = promisify(execFile);
21
+ const _require = createRequire(import.meta.url);
22
+ const _pkg = _require('../../package.json');
23
+ if (typeof _pkg.version !== 'string' || !_pkg.version) {
24
+ throw new Error('hometrans package.json#version is missing — cannot generate MCP fallback config.');
25
+ }
26
+ const PKG_NAME = typeof _pkg.name === 'string' && _pkg.name ? _pkg.name : 'hometrans';
27
+ const NPX_REF = `${PKG_NAME}@${_pkg.version}`;
28
+ /** Locate the globally-installed `hometrans` (or `ht`) binary. */
29
+ function resolveHometransBin() {
30
+ const isWin = process.platform === 'win32';
31
+ const cmd = isWin ? 'where' : 'which';
32
+ for (const candidate of ['hometrans', 'ht']) {
33
+ try {
34
+ const output = execFileSync(cmd, [candidate], {
35
+ encoding: 'utf-8',
36
+ timeout: 5000,
37
+ stdio: ['ignore', 'pipe', 'ignore'],
38
+ });
39
+ const lines = output
40
+ .split('\n')
41
+ .map(l => l.trim())
42
+ .filter(Boolean);
43
+ if (lines.length === 0)
44
+ continue;
45
+ if (isWin) {
46
+ const cmdLine = lines.find(l => /\.(cmd|bat)$/i.test(l));
47
+ return cmdLine || lines[0];
48
+ }
49
+ return lines[0];
50
+ }
51
+ catch {
52
+ // try next candidate
53
+ }
54
+ }
55
+ return null;
56
+ }
57
+ /**
58
+ * MCP server entry written to editor config.
59
+ *
60
+ * Prefers global binary (fast startup) over `npx -y hometrans@<version> mcp`
61
+ * (cold-start may exceed Claude Code's 30s MCP connect timeout, esp. with
62
+ * arkanalyzer install). Falls back to npx when binary not on PATH.
63
+ */
64
+ function getMcpEntry() {
65
+ const bin = resolveHometransBin();
66
+ if (bin) {
67
+ return { command: bin, args: ['mcp'] };
68
+ }
69
+ if (process.platform === 'win32') {
70
+ return { command: 'cmd', args: ['/c', 'npx', '-y', NPX_REF, 'mcp'] };
71
+ }
72
+ return { command: 'npx', args: ['-y', NPX_REF, 'mcp'] };
73
+ }
74
+ /** OpenCode uses a flat command-array format. */
75
+ function getOpenCodeMcpEntry() {
76
+ const bin = resolveHometransBin();
77
+ if (bin) {
78
+ return { type: 'local', command: [bin, 'mcp'] };
79
+ }
80
+ if (process.platform === 'win32') {
81
+ return {
82
+ type: 'local',
83
+ command: ['cmd', '/c', 'npx', '-y', NPX_REF, 'mcp'],
84
+ };
85
+ }
86
+ return { type: 'local', command: ['npx', '-y', NPX_REF, 'mcp'] };
87
+ }
88
+ function detectIndentation(raw) {
89
+ const firstIndented = raw.match(/^( +|\t)/m);
90
+ if (!firstIndented)
91
+ return { tabSize: 2, insertSpaces: true };
92
+ if (firstIndented[1] === '\t')
93
+ return { tabSize: 1, insertSpaces: false };
94
+ return { tabSize: firstIndented[1].length, insertSpaces: true };
95
+ }
96
+ /**
97
+ * Merge a key/value pair into a JSONC config file, preserving comments and formatting.
98
+ * Returns false if the file is genuinely corrupt (leaves it untouched).
99
+ */
100
+ async function mergeJsoncFile(filePath, keyPath, value) {
101
+ let raw;
102
+ try {
103
+ raw = await fs.readFile(filePath, 'utf-8');
104
+ }
105
+ catch {
106
+ raw = '';
107
+ }
108
+ if (raw.trim().length === 0) {
109
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
110
+ const formattingOptions = { tabSize: 2, insertSpaces: true };
111
+ const edits = modify('{}', keyPath, value, { formattingOptions });
112
+ const result = applyEdits('{}', edits);
113
+ await fs.writeFile(filePath, result, 'utf-8');
114
+ return true;
115
+ }
116
+ const parseErrors = [];
117
+ const tree = parseTree(raw, parseErrors);
118
+ if (tree && tree.type === 'object' && parseErrors.length === 0) {
119
+ const formattingOptions = detectIndentation(raw);
120
+ const edits = modify(raw, keyPath, value, { formattingOptions });
121
+ const result = applyEdits(raw, edits);
122
+ await fs.writeFile(filePath, result, 'utf-8');
123
+ return true;
124
+ }
125
+ return false;
126
+ }
127
+ function getTomlSection(sectionHeader) {
128
+ const entry = getMcpEntry();
129
+ const command = JSON.stringify(entry.command);
130
+ const args = `[${entry.args.map(arg => JSON.stringify(arg)).join(', ')}]`;
131
+ return `[${sectionHeader}]\ncommand = ${command}\nargs = ${args}\n`;
132
+ }
133
+ async function upsertTomlSection(configPath, sectionHeader) {
134
+ let existing = '';
135
+ try {
136
+ existing = await fs.readFile(configPath, 'utf-8');
137
+ }
138
+ catch {
139
+ existing = '';
140
+ }
141
+ if (existing.includes(`[${sectionHeader}]`)) {
142
+ return;
143
+ }
144
+ const section = getTomlSection(sectionHeader);
145
+ const nextContent = existing.trim().length > 0 ? `${existing.trimEnd()}\n\n${section}` : section;
146
+ await fs.mkdir(path.dirname(configPath), { recursive: true });
147
+ await fs.writeFile(configPath, `${nextContent.trimEnd()}\n`, 'utf-8');
148
+ }
149
+ // ─── Per-format writers ────────────────────────────────────────────
150
+ async function writeJsoncObject(editor, result) {
151
+ const mcp = editor.mcp;
152
+ if (!mcp.path || !mcp.keyPath) {
153
+ result.errors.push(`${editor.name} MCP: jsonc-object format requires path + keyPath`);
154
+ return;
155
+ }
156
+ const configPath = expandHome(mcp.path);
157
+ try {
158
+ const ok = await mergeJsoncFile(configPath, mcp.keyPath, getMcpEntry());
159
+ if (ok) {
160
+ result.configured.push(`${editor.name} MCP (${prettyConfigPath(configPath)})`);
161
+ }
162
+ else {
163
+ result.errors.push(`${editor.name} MCP: ${configPath} is corrupt — skipping to preserve existing content`);
164
+ }
165
+ }
166
+ catch (err) {
167
+ result.errors.push(`${editor.name} MCP: ${err.message}`);
168
+ }
169
+ }
170
+ async function writeJsoncCommandArray(editor, result) {
171
+ const mcp = editor.mcp;
172
+ if (!mcp.path || !mcp.keyPath) {
173
+ result.errors.push(`${editor.name} MCP: jsonc-command-array format requires path + keyPath`);
174
+ return;
175
+ }
176
+ const configPath = expandHome(mcp.path);
177
+ try {
178
+ const ok = await mergeJsoncFile(configPath, mcp.keyPath, getOpenCodeMcpEntry());
179
+ if (ok) {
180
+ result.configured.push(`${editor.name} MCP (${prettyConfigPath(configPath)})`);
181
+ }
182
+ else {
183
+ result.errors.push(`${editor.name} MCP: ${configPath} is corrupt — skipping to preserve existing content`);
184
+ }
185
+ }
186
+ catch (err) {
187
+ result.errors.push(`${editor.name} MCP: ${err.message}`);
188
+ }
189
+ }
190
+ async function writeCodexCli(editor, result) {
191
+ try {
192
+ const entry = getMcpEntry();
193
+ await execFileAsync('codex', ['mcp', 'add', 'hometrans', '--', entry.command, ...entry.args], { shell: process.platform === 'win32' });
194
+ result.configured.push(`${editor.name} MCP (via codex mcp add)`);
195
+ return;
196
+ }
197
+ catch {
198
+ // Fall through to TOML write.
199
+ }
200
+ const mcp = editor.mcp;
201
+ if (!mcp.path || !mcp.section) {
202
+ result.errors.push(`${editor.name} MCP: codex-cli fallback requires path + section`);
203
+ return;
204
+ }
205
+ try {
206
+ const configPath = expandHome(mcp.path);
207
+ await upsertTomlSection(configPath, mcp.section);
208
+ result.configured.push(`${editor.name} MCP (${prettyConfigPath(configPath)})`);
209
+ }
210
+ catch (err) {
211
+ result.errors.push(`${editor.name} MCP: ${err.message}`);
212
+ }
213
+ }
214
+ async function writeTomlSection(editor, result) {
215
+ const mcp = editor.mcp;
216
+ if (!mcp.path || !mcp.section) {
217
+ result.errors.push(`${editor.name} MCP: toml-section format requires path + section`);
218
+ return;
219
+ }
220
+ try {
221
+ const configPath = expandHome(mcp.path);
222
+ await upsertTomlSection(configPath, mcp.section);
223
+ result.configured.push(`${editor.name} MCP (${prettyConfigPath(configPath)})`);
224
+ }
225
+ catch (err) {
226
+ result.errors.push(`${editor.name} MCP: ${err.message}`);
227
+ }
228
+ }
229
+ function prettyConfigPath(p) {
230
+ // 与 init.ts 中 prettyHome 行为一致,但避免循环引用:就地实现。
231
+ const home = process.env.HOME || process.env.USERPROFILE || '';
232
+ if (home && p.startsWith(home)) {
233
+ return '~' + p.slice(home.length).replace(/\\/g, '/');
234
+ }
235
+ return p.replace(/\\/g, '/');
236
+ }
237
+ async function setupOneEditor(editor, result) {
238
+ const marker = expandHome(editor.markerDir);
239
+ if (marker && !(await dirExists(marker))) {
240
+ result.skipped.push(`${editor.name} MCP (not installed)`);
241
+ return;
242
+ }
243
+ switch (editor.mcp.format) {
244
+ case 'jsonc-object':
245
+ return writeJsoncObject(editor, result);
246
+ case 'jsonc-command-array':
247
+ return writeJsoncCommandArray(editor, result);
248
+ case 'codex-cli':
249
+ return writeCodexCli(editor, result);
250
+ case 'toml-section':
251
+ return writeTomlSection(editor, result);
252
+ case 'none':
253
+ return;
254
+ default:
255
+ result.errors.push(`${editor.name} MCP: unknown mcp.format "${editor.mcp.format}"`);
256
+ }
257
+ }
258
+ export async function setupMcpForAllEditors(editors, result) {
259
+ for (const editor of editors) {
260
+ await setupOneEditor(editor, result);
261
+ }
262
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * `ht mcp` — stdio MCP server exposing HomeTrans tools.
3
+ *
4
+ * Currently registers a single tool: `extract_commit_context`, which wraps
5
+ * the vendored ArkTS commit-context extractor (src/context/index.ts).
6
+ */
7
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
8
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
9
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
10
+ import { extractCommitContext } from '../context/index.js';
11
+ // stdio is the MCP protocol channel — any console.log from vendored code
12
+ // would corrupt frames. Redirect stdout-side logging to stderr.
13
+ console.log = console.error;
14
+ console.info = console.error;
15
+ console.dir = (...args) => process.stderr.write(args.map(a => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ') + '\n');
16
+ const EXTRACT_COMMIT_CONTEXT_TOOL = {
17
+ name: 'extract_commit_context',
18
+ description: '提取 HarmonyOS 工程指定 commit 的代码上下文索引(git diff + ArkTS 语义依赖:模块依赖、字符串/复数/数组资源依赖),供 AI 评审 Android→HarmonyOS 转换代码时使用。返回 {path, kind, ranges?, resourceNames?}[]:source 文件给出 1-based 行号区间数组,调用方按需读取;resource 文件给出引用到的资源名列表。不返回文件内容,避免上下文过长。',
19
+ inputSchema: {
20
+ type: 'object',
21
+ properties: {
22
+ projectPath: {
23
+ type: 'string',
24
+ description: 'HarmonyOS 工程的绝对路径(包含 .git 目录的仓库根)',
25
+ },
26
+ commitId: {
27
+ type: 'string',
28
+ description: '要分析的 git commit id(会和它的第一个父提交做 diff)',
29
+ },
30
+ mode: {
31
+ type: 'string',
32
+ description: '分析模式:default = 构建完整 call graph 做调用链上下文;其它值跳过 call graph 构建',
33
+ default: 'default',
34
+ },
35
+ ohosSdkPath: {
36
+ type: 'string',
37
+ description: 'OpenHarmony SDK ETS 目录绝对路径(如 D:/DevEco Studio/sdk/default/openharmony/ets)。未传则读环境变量 HOMETRANS_OHOS_SDK_PATH。',
38
+ },
39
+ hmsSdkPath: {
40
+ type: 'string',
41
+ description: 'HMS SDK ETS 目录绝对路径(如 D:/DevEco Studio/sdk/default/hms/ets)。未传则读环境变量 HOMETRANS_HMS_SDK_PATH。',
42
+ },
43
+ },
44
+ required: ['projectPath', 'commitId'],
45
+ },
46
+ };
47
+ export async function runMcpServer() {
48
+ const server = new Server({ name: 'hometrans', version: '0.1.2' }, { capabilities: { tools: {} } });
49
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
50
+ tools: [EXTRACT_COMMIT_CONTEXT_TOOL],
51
+ }));
52
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
53
+ const { name, arguments: args } = request.params;
54
+ if (name !== EXTRACT_COMMIT_CONTEXT_TOOL.name) {
55
+ return {
56
+ isError: true,
57
+ content: [{ type: 'text', text: `Unknown tool: ${name}` }],
58
+ };
59
+ }
60
+ try {
61
+ const input = (args ?? {});
62
+ const result = await extractCommitContext({
63
+ projectPath: input.projectPath ?? '',
64
+ commitId: input.commitId ?? '',
65
+ mode: input.mode,
66
+ ohosSdkPath: input.ohosSdkPath,
67
+ hmsSdkPath: input.hmsSdkPath,
68
+ });
69
+ return {
70
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
71
+ };
72
+ }
73
+ catch (err) {
74
+ return {
75
+ isError: true,
76
+ content: [
77
+ {
78
+ type: 'text',
79
+ text: `extract_commit_context failed: ${err?.message ?? String(err)}`,
80
+ },
81
+ ],
82
+ };
83
+ }
84
+ });
85
+ process.on('uncaughtException', err => {
86
+ console.error('[hometrans/mcp] uncaughtException:', err);
87
+ });
88
+ process.on('unhandledRejection', err => {
89
+ console.error('[hometrans/mcp] unhandledRejection:', err);
90
+ });
91
+ const transport = new StdioServerTransport();
92
+ await server.connect(transport);
93
+ console.error('[hometrans/mcp] server connected on stdio');
94
+ }