Compare commits

...
3 Commits
Author SHA1 Message Date
gitea cf44c7dcdf feat(config): 支持多层级企业配置发现、读写分离安全落盘与路径诊断并发布 v0.4.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:34:29 +08:00
gitea 9e20caf4a3 feat(mcp): 引入 MCP 单工具网关模式 (hose_cli) 与并发流调度并发布 v0.4.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:28:41 +08:00
gitea 4f510efc1b feat(auth): 支持代客协助平台凭证智能识别、Token过期感知与单据字典增强并发布 v0.3.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:08:47 +08:00
21 changed files with 1167 additions and 116 deletions

No files matched your search

+2 -3
View File
@@ -43,6 +43,5 @@ data/
*.db
*.sqlite
# 环境变量
.env
.env.local
# Local roadmaps & scratch notes
*.local.md
+14 -7
View File
@@ -1,4 +1,4 @@
# hose-use (v0.3.0)
# hose-use (v0.4.1)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -32,8 +32,9 @@ hose-use corps list # 列出名下所有已配置企
hose-use corps switch <corpId> # 切换工作企业
hose-use corps current # 查看当前激活企业
# 3. 运行模式管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式
# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式与默认企业
hose-use config paths # 查看多级企业目录发现链与配置文件位置
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
@@ -60,12 +61,18 @@ hose-use openapi --raw # 输出原生下游全量 OpenAPI
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
# 8. 一键自更新与版本发布历史
hose-use update # 自动检查并升级到最新版本 (多镜像源加速)
hose-use update --check # 仅检查新版本与 Release Notes
hose-use update --changelog # 查看最近版本发布历史
# 8. MCP Server (单工具网关模式)
hose-use mcp # 启动 MCP Server (默认暴露 hose_cli 单工具网关)
```
### AI 智能体与 MCP 单工具网关 (`hose_cli`)
`hose-use` 采用 **单工具网关架构 (Single-Gate Pattern)**。在 MCP 环境下默认仅暴露一个 `hose_cli` 工具,接收 `command` 字符串:
- 避免数十个业务工具占用大量 Prompt Tokens;
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 中,Agent 按需学习;
- 内部同进程调用 CLI 分发层,零子进程开销;
- 若需要传统细粒度工具,可通过环境变量 `HOSE_MCP_MODE=all` 开启兼容模式。
## 架构
```text
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.3.0
version: 0.4.1
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.3.0",
"version": "0.4.1",
"module": "src/server.ts",
"type": "module",
"bin": {
+29
View File
@@ -15,6 +15,32 @@ description: 合思/易快报 (ekuaibao) 企业 SaaS CLI 命令行工具与底
- **有状态 / 无状态双模式**:
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
- **无状态 (Stateless)**:严格要求 `--corp <corpId>`,防止多租户或 Agent 误操作。
- **MCP 单工具网关架构**:统一暴露 `hose_cli` 工具,避免数十个细粒度工具膨胀污染 Agent 的上下文,零子进程同构执行。
---
## 调用通道与执行协议
`hose-use` 同时支持 **MCP 工具** 与 **Shell CLI** 两种调用通道:
- **MCP 工具通道 (AI Agent 优先推荐)**:在具备 MCP 的智能体环境中,优先调用 `hose_cli` 工具网关:
```json
{
"command": "corps list"
}
```
或者执行业务检索:
```json
{
"command": "bill query --code BX20260901001 --corp ID01MCcOgJl1td"
}
```
- **Shell CLI 通道 (运维/终端/脚本)**:在终端或子进程环境中,直接执行:
```bash
hose corps list
# 或
hose-use bill query --code BX20260901001
```
---
@@ -58,6 +84,9 @@ hose-use corps current
# 查看全局运行模式与配置文件路径
hose-use config show
# 查看多级企业目录发现路径与诊断
hose-use config paths
# 切换为无状态模式 (Stateless)
hose-use config mode stateless
+58 -7
View File
@@ -3,6 +3,7 @@ import {
fullSmsLogin,
fullBrowserSyncLogin,
sendSmsVerificationCode,
importCredentials,
importF12Credentials,
parseHeadersOrCurl,
refreshAccountCorporations,
@@ -14,7 +15,7 @@ import {
} from "../../core/auth/account-store.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -171,13 +172,41 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: printJson(statusObj), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
const pairs: Record<string, unknown> = {
"当前活跃账号": activeAccount?.accountId || "未登录",
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
"当前员工工号": currentCorp?.credentials.staffId || "-",
"凭证来源类型": currentCorp?.source || "-",
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
"凭证来源类型": formatSourceLabel(currentCorp?.source),
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
});
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
};
if (currentCorp?.session) {
if (currentCorp.session.loginTime) {
pairs["会话创建时间"] = new Date(currentCorp.session.loginTime).toLocaleString("zh-CN", { hour12: false });
}
if (currentCorp.session.platform) {
pairs["官方平台类型"] = currentCorp.session.platform;
}
if (currentCorp.session.isAssistPlatform) {
pairs["协助调试模式"] = "是 (Assist Platform)";
if (currentCorp.session.operationUserName || currentCorp.session.operationUserId) {
pairs["协助操作人员"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
}
if (currentCorp.session.assistId) {
pairs["协助会话 ID"] = currentCorp.session.assistId;
}
}
if (currentCorp.session.cellphone) {
pairs["绑定手机号码"] = currentCorp.session.cellphone;
}
if (currentCorp.session.isAdmin !== undefined) {
pairs["是否企业管理"] = currentCorp.session.isAdmin ? "是" : "否";
}
}
const summary = printKeyValue(pairs);
return {
stdout: `====== 当前登录与企业状态 ======\n${summary}\n`,
@@ -209,7 +238,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
let name = stringOption(parsed.options, ["name"]);
if (!raw && !accessToken) {
raw = await prompt("请粘贴 F12 抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
raw = await prompt("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
}
if (raw) {
@@ -227,7 +256,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
}
const imported = await importF12Credentials({
const imported = await importCredentials({
accessToken,
corpId,
staffId,
@@ -238,8 +267,30 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: printJson(imported), stderr: "", exitCode: 0 };
}
const summaryPairs: Record<string, unknown> = {
"企业名称": imported.name,
"企业 ID": imported.id,
"员工工号": imported.credentials.staffId,
"员工姓名": imported.staffName || imported.session?.staffName || "-",
"凭证来源": formatSourceLabel(imported.source),
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
"保存路径": `enterprises/${imported.id}.json`,
};
if (imported.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (imported.session.operationUserName || imported.session.operationUserId) {
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
}
if (imported.session.assistId) {
summaryPairs["协助会话 ID"] = imported.session.assistId;
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n企业名称: ${imported.name}\n企业 ID: ${imported.id}\n员工工号: ${imported.credentials.staffId}\n保存路径: enterprises/${imported.id}.json\n`,
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
+48 -1
View File
@@ -2,6 +2,9 @@ import {
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
resolveEnterprisesDirs,
resolveWritableEnterprisesDir,
getEnterprisesDirCandidates,
} from "../../core/config/loader.js";
import { printJson, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -17,6 +20,10 @@ export async function handleConfigCommand(
case "get":
case "list":
return handleShow(parsed, runtime);
case "paths":
case "path":
case "dirs":
return handlePaths(parsed, runtime);
case "mode":
return handleMode(parsed, runtime);
case "set":
@@ -24,7 +31,7 @@ export async function handleConfigCommand(
default:
return {
stdout: "",
stderr: `未知 config 子命令: ${action}。支持: show, mode <stateful|stateless>, set <key> <val>\n`,
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, set <key> <val>\n`,
exitCode: 1,
};
}
@@ -125,3 +132,43 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
exitCode: 0,
};
}
async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const envDir = process.env.HOSE_ENTERPRISES_DIR;
const envUserDir = process.env.HOSE_USER_ENTERPRISES_DIR;
const envConfigFile = process.env.HOSE_CONFIG_FILE;
const existingDirs = resolveEnterprisesDirs();
const writableDir = resolveWritableEnterprisesDir();
const configFile = resolveGlobalConfigFile();
const candidates = getEnterprisesDirCandidates();
const data = {
configFile,
writableDir,
existingDirs,
env: {
HOSE_ENTERPRISES_DIR: envDir || null,
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
HOSE_CONFIG_FILE: envConfigFile || null,
},
candidates,
};
if (runtime.jsonMode) {
return { stdout: printJson(data), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"当前生效配置文件": configFile,
"凭证保存写入目录": writableDir,
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
"全部目录候选链": candidates.join("\n "),
});
return {
stdout: `====== 配置路径诊断 (Config Paths) ======\n${output}\n`,
stderr: "",
exitCode: 0,
};
}
+34 -5
View File
@@ -1,4 +1,4 @@
import { printJson, printKeyValue, printTable } from "../printer.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleCorpsCommand(
@@ -48,11 +48,12 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
c.name,
c.staffId,
c.source || "manual",
formatExpiresAt(c.expiresAt),
c.accountId || "-",
]);
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "来源", "所属账号"],
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
rows
);
@@ -100,14 +101,42 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
return { stdout: printJson(current), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
const pairs: Record<string, unknown> = {
"企业 ID": current.id,
"企业名称": current.name,
"员工工号": current.credentials.staffId,
"来源类型": current.source || "manual",
"员工姓名": current.staffName || current.session?.staffName || "-",
"凭证来源": formatSourceLabel(current.source),
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
"所属账号": current.accountId || "-",
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
});
};
if (current.session) {
if (current.session.loginTime) {
pairs["会话创建时间"] = new Date(current.session.loginTime).toLocaleString("zh-CN", { hour12: false });
}
if (current.session.platform) {
pairs["官方平台类型"] = current.session.platform;
}
if (current.session.isAssistPlatform) {
pairs["协助登录模式"] = "是 (Assist Platform)";
if (current.session.operationUserName || current.session.operationUserId) {
pairs["协助操作人员"] = `${current.session.operationUserName || ""} (${current.session.operationUserId || ""})`.trim();
}
if (current.session.assistId) {
pairs["协助会话 ID"] = current.session.assistId;
}
}
if (current.session.cellphone) {
pairs["绑定手机号码"] = current.session.cellphone;
}
if (current.session.isAdmin !== undefined) {
pairs["是否企业管理"] = current.session.isAdmin ? "是" : "否";
}
}
const output = printKeyValue(pairs);
return {
stdout: `====== 当前激活企业 ======\n${output}\n`,
+15 -3
View File
@@ -1,6 +1,6 @@
import { createClientsForCorp } from "../helpers.js";
import * as api from "../../domains/platform/api.js";
import { printJson, printKeyValue } from "../printer.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleProbeCommand(
@@ -79,14 +79,26 @@ export async function handleProbeCommand(
return { stdout: printJson(results), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
const probePairs: Record<string, unknown> = {
"企业名称": currentCorp.name,
"企业 ID": currentCorp.id,
"员工工号": currentCorp.credentials.staffId,
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
"凭证来源": formatSourceLabel(currentCorp.source),
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime),
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
});
};
if (currentCorp.session?.isAssistPlatform) {
probePairs["协助操作人"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
if (currentCorp.session.assistId) {
probePairs["协助会话 ID"] = currentCorp.session.assistId;
}
}
const summary = printKeyValue(probePairs);
return {
stdout: `====== 诊断结果 (Enterprise Probe) ======\n${summary}\n`,
+2 -2
View File
@@ -1,5 +1,5 @@
import readline from "readline";
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
import { loadCorpConfigs, loadGlobalConfig, getEnterprisesDirCandidates } from "../core/config/loader.js";
import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
import { CorpConfig } from "../core/config/types.js";
import { createEkbClient } from "../core/auth/ekb.js";
@@ -31,7 +31,7 @@ export function initCorpRuntime(
let selectedCorp: CorpConfig | null = null;
try {
selectedCorp = corpContext.resolve(options.corpId);
selectedCorp = corpContext.resolve(options.corpId, getEnterprisesDirCandidates());
} catch {
selectedCorp = null;
}
+37
View File
@@ -4,6 +4,43 @@ export function printJson(data: unknown): string {
return JSON.stringify(data, null, 2);
}
export function formatSourceLabel(source?: string): string {
switch (source) {
case "assist":
return "官方协助/代客平台 (Assist Platform)";
case "account":
return "统一认证中心 (IDP 账密/短信)";
case "browser":
return "浏览器会话同步 (WebBridge)";
case "curl":
case "f12":
return "cURL 抓包导入 (cURL/F12)";
case "manual":
return "手动配置";
default:
return source || "未知来源";
}
}
export function formatExpiresAt(expiresAt?: number): string {
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
const diffMs = expiresAt - Date.now();
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
if (diffMs <= 0) {
return `${dateStr} (⚠️ 已过期)`;
}
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 60) {
return `${dateStr} (约剩余 ${diffMins} 分钟)`;
}
const diffHours = (diffMs / 3600000).toFixed(1);
if (Number(diffHours) < 24) {
return `${dateStr} (约剩余 ${diffHours} 小时)`;
}
const diffDays = Math.floor(diffMs / 86400000);
return `${dateStr} (约剩余 ${diffDays} 天)`;
}
export function printKeyValue(pairs: Record<string, unknown>): string {
const lines: string[] = [];
const maxKeyLen = Math.max(...Object.keys(pairs).map((k) => k.length), 0);
+46 -1
View File
@@ -15,7 +15,52 @@ import { handleOpenApiCommand } from "./commands/openapi.js";
import { handleBillCommand } from "./commands/bill.js";
import type { CliResult, CliRunOptions } from "./types.js";
export async function runCli(
let runQueue = Promise.resolve<any>(undefined);
export function runCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
const run = runQueue.then(() => runCliOnce(rawArgs, options));
runQueue = run.then(
() => undefined,
() => undefined
);
return run;
}
async function runCliOnce(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
const originalLog = console.log;
const originalError = console.error;
console.log = (...values: unknown[]) => {
stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
};
console.error = (...values: unknown[]) => {
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
};
try {
const result = await dispatchCli(rawArgs, options);
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
return {
stdout: extraStdout + (result.stdout || ""),
stderr: extraStderr + (result.stderr || ""),
exitCode: result.exitCode,
};
} finally {
console.log = originalLog;
console.error = originalError;
}
}
async function dispatchCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
+148 -7
View File
@@ -263,13 +263,35 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
}
}
// 3. 从 URL 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx)
if (!result.corpId) {
const urlCorpMatch = /(?:[?&]corpId=)([^&'"\s]+)/i.exec(rawInput);
if (urlCorpMatch) {
result.corpId = decodeURIComponent(urlCorpMatch[1]);
}
}
// 4. 从 Cookie (-b / Cookie header) 中提取 ekb-access-token 或 corpId
if (!result.accessToken) {
const cookieTokenMatch = /ekb-access-token=([^;'"\s]+)/i.exec(rawInput);
if (cookieTokenMatch) {
result.accessToken = decodeURIComponent(cookieTokenMatch[1]);
}
}
if (!result.corpId) {
const cookieCorpMatch = /(?:^|;\s*)corpId=([^;'"\s]+)/i.exec(rawInput);
if (cookieCorpMatch) {
result.corpId = decodeURIComponent(cookieCorpMatch[1]);
}
}
return result;
}
/**
* 校验并导入单个 F12 抓包/手动凭证,保存到企业配置
* 校验并导入单个抓包/手动凭证,自动探测官方 Session 平台类型并保存到企业配置
*/
export async function importF12Credentials(
export async function importCredentials(
params: F12ImportParams
): Promise<CorpConfig> {
const { accessToken, corpId, staffId } = params;
@@ -279,8 +301,25 @@ export async function importF12Credentials(
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
}
// 验证凭证有效性并尝试自动获取企业名称
let corpName = params.name;
// 1. 验证凭证有效性并提取官方服务端 Session 元数据
let sessionData: {
id?: string;
userId?: string;
loginStaffId?: string;
corporationId?: string;
platform?: string;
isAssistPlatform?: boolean;
isShortTermToken?: boolean;
assistId?: string;
operationUserId?: string;
operationUserName?: string;
privilege?: string;
deviceType?: string;
loginAccountType?: string;
loginTime?: number;
expTime?: number;
} | undefined;
try {
const res = await ky
.get(`${baseUrl}/api/account/v2/session`, {
@@ -290,20 +329,102 @@ export async function importF12Credentials(
staffid: staffId,
},
})
.json<{ value?: { corporationId?: string; loginStaffId?: string; expTime?: number } }>();
.json<{
value?: {
id?: string;
userId?: string;
loginStaffId?: string;
corporationId?: string;
platform?: string;
isAssistPlatform?: boolean;
isShortTermToken?: boolean;
assistId?: string;
operationUserId?: string;
operationUserName?: string;
privilege?: string;
deviceType?: string;
loginAccountType?: string;
loginTime?: number;
expTime?: number;
};
}>();
if (!res.value?.corporationId) {
sessionData = res.value;
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
throw new Error("服务端未返回有效 Session");
}
} catch (err) {
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
}
// 2. 尝试通过 $UNITY JWT 获取真实企业名称与员工详细信息 (如果未手动指定)
let corpName = params.name;
let staffName = sessionData?.privilege;
let cellphone: string | undefined;
let isAdmin: boolean | undefined;
let sourceChannel: string | undefined;
let jwtExpMs: number | undefined;
try {
const jwtRes = await ky
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
searchParams: { corpId },
headers: {
accesstoken: accessToken,
corpid: corpId,
staffid: staffId,
},
})
.json<{ id?: string; value?: string }>();
const token = jwtRes.id || jwtRes.value;
if (token) {
const parts = token.split(".");
if (parts.length >= 2) {
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
if (!corpName && payload.corporationName) {
corpName = payload.corporationName;
}
if (payload.staffName) {
staffName = payload.staffName;
}
if (payload.cellphone) {
cellphone = payload.cellphone;
}
if (payload.isAdmin !== undefined) {
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
}
if (payload.exp) {
jwtExpMs = Number(payload.exp) * 1000;
}
}
}
} catch {
// 忽略尝试获取企业名失败
}
// 3. 智能判断语义化凭证来源
let source: import("../config/types.js").CredentialSource = "curl";
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
source = "assist";
}
// 4. 计算 Token 过期时间戳 (ms)
let expiresAt: number | undefined;
if (sessionData?.expTime && sessionData.expTime > 0) {
expiresAt = sessionData.expTime;
} else if (jwtExpMs && jwtExpMs > 0) {
expiresAt = jwtExpMs;
} else if (sessionData?.isAssistPlatform && sessionData?.loginTime) {
// 协助平台短期调试 Token 通常 2 小时有效
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
}
const corpConfig: CorpConfig = {
id: corpId,
name: corpName || `企业-${corpId}`,
baseUrl,
source: "f12",
source,
staffName,
credentials: {
accessToken,
corpId,
@@ -311,6 +432,23 @@ export async function importF12Credentials(
},
auth: {
refreshTtl: 300,
expiresAt,
},
session: {
platform: sessionData?.platform,
isAssistPlatform: sessionData?.isAssistPlatform,
isShortTermToken: sessionData?.isShortTermToken,
assistId: sessionData?.assistId,
operationUserId: sessionData?.operationUserId,
operationUserName: sessionData?.operationUserName,
staffName,
cellphone,
isAdmin,
deviceType: sessionData?.deviceType,
loginAccountType: sessionData?.loginAccountType,
loginTime: sessionData?.loginTime,
expTime: expiresAt || sessionData?.expTime,
sourceChannel,
},
};
@@ -318,6 +456,9 @@ export async function importF12Credentials(
return corpConfig;
}
// 保持历史命名兼容
export const importF12Credentials = importCredentials;
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
/**
+143
View File
@@ -0,0 +1,143 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
loadCorpConfigs,
saveCorpConfig,
resolveEnterprisesDirs,
resolveWritableEnterprisesDir,
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
} from "./loader.js";
import type { CorpConfig } from "./types.js";
describe("core/config/loader", () => {
let tempDir: string;
const originalEnv = { ...process.env };
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "hose-config-test-"));
});
afterEach(() => {
process.env = { ...originalEnv };
try {
rmSync(tempDir, { recursive: true, force: true });
} catch {
// ignore
}
});
test("resolveEnterprisesDirs prioritizes HOSE_ENTERPRISES_DIR environment variable", () => {
const customDir = join(tempDir, "custom-enterprises");
mkdirSync(customDir, { recursive: true });
process.env.HOSE_ENTERPRISES_DIR = customDir;
const dirs = resolveEnterprisesDirs();
expect(dirs).toEqual([customDir]);
});
test("resolveWritableEnterprisesDir respects HOSE_ENTERPRISES_DIR", () => {
const customDir = join(tempDir, "writable-enterprises");
mkdirSync(customDir, { recursive: true });
process.env.HOSE_ENTERPRISES_DIR = customDir;
expect(resolveWritableEnterprisesDir()).toBe(customDir);
});
const createMockCorp = (id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig => ({
id,
name,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: {
accessToken: `token-${id}`,
corpId: id,
staffId: `staff-${id}`,
},
...overrides,
});
test("loadCorpConfigs loads valid configs and skips example files", () => {
const dirA = join(tempDir, "dirA");
mkdirSync(dirA, { recursive: true });
const validCorp = createMockCorp("corp-1", "企业1");
// Save valid corp
writeFileSync(join(dirA, "corp-1.json"), JSON.stringify(validCorp));
// Save example corp
writeFileSync(
join(dirA, "example.json"),
JSON.stringify(createMockCorp("example-corp", "模板企业"))
);
const loaded = loadCorpConfigs([dirA]);
expect(loaded).toHaveLength(1);
expect(loaded[0]?.id).toBe("corp-1");
expect(loaded[0]?.name).toBe("企业1");
});
test("loadCorpConfigs merges multiple directories with earlier directory taking precedence", () => {
const dirA = join(tempDir, "dirA");
const dirB = join(tempDir, "dirB");
mkdirSync(dirA, { recursive: true });
mkdirSync(dirB, { recursive: true });
const corpInA = createMockCorp("corp-common", "本地优先企业", {
credentials: { accessToken: "token-a", corpId: "corp-common", staffId: "staff-a" },
});
const corpInB = createMockCorp("corp-common", "全局覆盖企业", {
credentials: { accessToken: "token-b", corpId: "corp-common", staffId: "staff-b" },
});
const corpOnlyB = createMockCorp("corp-b-only", "仅在B的企业", {
credentials: { accessToken: "token-b2", corpId: "corp-b-only", staffId: "staff-b2" },
});
writeFileSync(join(dirA, "corp-common.json"), JSON.stringify(corpInA));
writeFileSync(join(dirB, "corp-common.json"), JSON.stringify(corpInB));
writeFileSync(join(dirB, "corp-b-only.json"), JSON.stringify(corpOnlyB));
const loaded = loadCorpConfigs([dirA, dirB]);
expect(loaded).toHaveLength(2);
const common = loaded.find((c) => c.id === "corp-common");
expect(common?.name).toBe("本地优先企业");
const bOnly = loaded.find((c) => c.id === "corp-b-only");
expect(bOnly?.name).toBe("仅在B的企业");
});
test("saveCorpConfig writes validated JSON to target directory", () => {
const targetDir = join(tempDir, "save-target");
const corp = createMockCorp("corp-save-test", "保存测试企业", {
credentials: { accessToken: "tok-123", corpId: "corp-save-test", staffId: "stf-1" },
});
const filePath = saveCorpConfig(corp, targetDir);
expect(existsSync(filePath)).toBe(true);
const saved = JSON.parse(readFileSync(filePath, "utf-8"));
expect(saved.id).toBe("corp-save-test");
expect(saved.credentials.accessToken).toBe("tok-123");
});
test("loadGlobalConfig and saveGlobalConfig respect HOSE_CONFIG_FILE", () => {
const customConfigFile = join(tempDir, "config.json");
process.env.HOSE_CONFIG_FILE = customConfigFile;
expect(resolveGlobalConfigFile()).toBe(customConfigFile);
const initial = loadGlobalConfig();
expect(initial.stateful).toBe(true);
saveGlobalConfig({ stateful: false, defaultCorpId: "test-corp-123" });
const updated = loadGlobalConfig();
expect(updated.stateful).toBe(false);
expect(updated.defaultCorpId).toBe("test-corp-123");
});
});
+114 -37
View File
@@ -1,30 +1,96 @@
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { homedir } from "os";
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "./enterprises";
const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json");
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
function ensureDir(dir: string): void {
mkdirSync(dir, { recursive: true });
}
export function resolveEnterprisesDirs(): string[] {
const configured = process.env[CONFIG_ENV]?.trim();
if (configured) {
return existsSync(configured) ? [configured] : [];
}
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
if (configuredUserDir) {
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
}
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
const uniqueExisting: string[] = [];
for (const d of dirs) {
if (existsSync(d) && !uniqueExisting.includes(d)) {
uniqueExisting.push(d);
}
}
return uniqueExisting;
}
export function resolvePrimaryEnterprisesDir(): string | undefined {
const configured = process.env[CONFIG_ENV]?.trim();
if (configured) return existsSync(configured) ? configured : undefined;
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
return undefined;
}
export function resolveWritableEnterprisesDir(): string {
const configured = process.env[CONFIG_ENV]?.trim();
if (configured) return configured;
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
if (configuredUserDir) return configuredUserDir;
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
return PRIMARY_USER_ENTERPRISES_DIR;
}
export function getEnterprisesDirCandidates(): string[] {
return [
`${CONFIG_ENV}=<path>`,
ENTERPRISES_DIR,
PRIMARY_USER_ENTERPRISES_DIR,
LEGACY_USER_ENTERPRISES_DIR,
];
}
export function resolveGlobalConfigFile(): string {
return GLOBAL_CONFIG_PATH;
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
if (configured) return configured;
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
return PRIMARY_GLOBAL_CONFIG_FILE;
}
export function loadGlobalConfig(): GlobalConfig {
const file = resolveGlobalConfigFile();
try {
const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
return GlobalConfigSchema.parse(JSON.parse(content));
if (existsSync(file)) {
const content = readFileSync(file, "utf-8");
return GlobalConfigSchema.parse(JSON.parse(content));
}
} catch {
return {
stateful: true,
defaultCorpId: undefined,
defaultAccountId: undefined,
};
// 容错返回默认
}
return {
stateful: true,
defaultCorpId: undefined,
defaultAccountId: undefined,
};
}
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
@@ -33,50 +99,61 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
...current,
...config,
});
ensureDir(dirname(GLOBAL_CONFIG_PATH));
writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(updated, null, 2), "utf-8");
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
ensureDir(dirname(targetFile));
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
return updated;
}
export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] {
let files: string[];
try {
ensureDir(dir);
files = readdirSync(dir).filter((f) => f.endsWith(".json"));
} catch (error) {
console.error(
`[config] failed to read enterprises directory: ${error instanceof Error ? error.message : String(error)}`
);
return [];
}
export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs();
const byId = new Map<string, CorpConfig>();
const configs: CorpConfig[] = [];
for (const file of files) {
for (const dir of dirs) {
try {
const content = readFileSync(join(dir, file), "utf-8");
const parsed = JSON.parse(content);
configs.push(CorpConfigSchema.parse(parsed));
const files = readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.filter((item) => !item.startsWith("example."));
for (const file of files) {
try {
const content = readFileSync(join(dir, file), "utf-8");
const parsed = JSON.parse(content);
const corp = CorpConfigSchema.parse(parsed);
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
if (!byId.has(corp.id)) {
byId.set(corp.id, corp);
}
} catch (error) {
console.error(
`[config] failed to load ${file} from ${dir}: ${error instanceof Error ? error.message : String(error)}`
);
}
}
} catch (error) {
console.error(
`[config] failed to load ${file}: ${error instanceof Error ? error.message : String(error)}`
`[config] failed to read enterprises directory ${dir}: ${error instanceof Error ? error.message : String(error)}`
);
}
}
return configs;
return Array.from(byId.values());
}
export function saveCorpConfig(config: CorpConfig, dir: string = ENTERPRISES_DIR): string {
ensureDir(dir);
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
const targetDir = dir || resolveWritableEnterprisesDir();
ensureDir(targetDir);
const validated = CorpConfigSchema.parse(config);
const filePath = join(dir, `${validated.id}.json`);
const filePath = join(targetDir, `${validated.id}.json`);
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
return filePath;
}
export function saveMultipleCorpConfigs(
configs: CorpConfig[],
dir: string = ENTERPRISES_DIR
dir?: string
): string[] {
return configs.map((config) => saveCorpConfig(config, dir));
}
+16 -8
View File
@@ -9,6 +9,7 @@ export interface CorpSummary {
staffId: string;
baseUrl?: string;
current: boolean;
expiresAt?: number;
}
export function resolveCorpConfig(
@@ -17,7 +18,8 @@ export function resolveCorpConfig(
stateful: boolean;
defaultCorpId?: string;
corpId?: string;
}
},
candidateDirs?: string[]
): CorpConfig {
const requestedCorpId = options.corpId?.trim() || undefined;
const configuredCorpId = options.stateful
@@ -50,7 +52,8 @@ export function resolveCorpConfig(
const firstCorp = corps[0];
if (firstCorp) return firstCorp;
throw new Error("未找到任何企业配置。请先运行 `hose auth login` 或在 enterprises/ 目录下添加配置。");
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`);
}
export class CorpContext {
@@ -109,12 +112,16 @@ export class CorpContext {
return this.corps.get(corpId);
}
resolve(corpId?: string): CorpConfig {
return resolveCorpConfig(Array.from(this.corps.values()), {
stateful: this.stateful,
defaultCorpId: this.defaultCorpId,
corpId,
});
resolve(corpId?: string, candidateDirs?: string[]): CorpConfig {
return resolveCorpConfig(
Array.from(this.corps.values()),
{
stateful: this.stateful,
defaultCorpId: this.defaultCorpId,
corpId,
},
candidateDirs
);
}
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
@@ -145,6 +152,7 @@ export class CorpContext {
staffId: corp.credentials.staffId,
baseUrl: corp.baseUrl,
current: corp.id === this.current?.id,
expiresAt: corp.auth?.expiresAt || corp.session?.expTime,
}));
}
}
+29 -2
View File
@@ -1,6 +1,13 @@
import { z } from "zod";
export const CredentialSourceSchema = z.enum(["account", "manual", "browser", "f12"]);
export const CredentialSourceSchema = z.enum([
"account", // 官方统一认证中心 (IDP) 账密/短信登录
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
"browser", // 浏览器会话 / Cookie 同步
"manual", // 手动配置
"curl", // cURL 抓包 / HTTP Headers 导入
"f12", // 兼容旧版抓包标识
]);
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
export const CorpCredentialsSchema = z.object({
@@ -15,17 +22,37 @@ export const CorpAuthConfigSchema = z.object({
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
});
export const CorpSessionInfoSchema = z.object({
platform: z.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
isAssistPlatform: z.boolean().optional().describe("是否为官方协助/代客平台登录"),
isShortTermToken: z.boolean().optional().describe("是否为短期临时 Token"),
assistId: z.string().optional().describe("协助会话/工单 ID"),
operationUserId: z.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
operationUserName: z.string().optional().describe("协助操作人姓名"),
staffName: z.string().optional().describe("当前员工真实姓名"),
cellphone: z.string().optional().describe("绑定手机号"),
isAdmin: z.boolean().optional().describe("是否管理员"),
deviceType: z.string().optional().describe("设备类型"),
loginAccountType: z.string().optional().describe("登录账号类型"),
loginTime: z.number().optional().describe("登录时间戳 (ms)"),
expTime: z.number().optional().describe("过期时间戳 (ms)"),
sourceChannel: z.string().optional().describe("来源渠道 (如 APP, WEB)"),
});
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
export const CorpConfigSchema = z.object({
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
name: z.string().describe("企业名称"),
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
userId: z.string().optional().describe("所属用户 ID"),
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
staffName: z.string().optional().describe("员工真实姓名"),
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/manual/browser/f12"),
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
credentials: CorpCredentialsSchema,
auth: CorpAuthConfigSchema.optional(),
session: CorpSessionInfoSchema.optional().describe("官方服务端 Session 与操作人元数据"),
});
export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
+49 -4
View File
@@ -11,6 +11,53 @@ import {
import { CorpContext } from "../../core/config/manager.js";
import { createEkbClient } from "../../core/auth/ekb.js";
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
const COMMON_FIELD_LABELS: Record<string, string> = {
code: "单据编号",
name: "单据名称",
stage: "业务阶段",
state: "审批状态",
title: "单据标题",
amount: "单据金额",
expenseMoney: "报销金额",
payMoney: "支付金额",
apportionMoney: "分摊金额",
submitDate: "提交时间",
submitterId: "提交人ID",
ownerId: "归属人ID",
description: "事由说明",
detailType: "明细类型",
entityType: "实体类型",
settleStatus: "结算状态",
settleTime: "结算时间",
billingStatus: "开票状态",
voucherStatus: "凭证状态",
voucherCreateTime: "凭证生成时间",
writtenOffAmount: "已核销金额",
unwrittenOffAmount: "未核销金额",
linkType: "关联类型",
linkId: "关联审批流ID",
detailId: "明细ID",
detailNo: "明细序号",
feeTypeId: "费用类型ID",
attachments: "附件列表",
invoiceForm: "发票表单",
submitCount: "提交次数",
rejectionNum: "驳回次数",
reviewStatus: "审核状态",
preApprovedNodeName: "上一审批节点",
preNodeApprovedTime: "节点审批通过时间",
accountPropertyMoney: "核算属性金额",
accountPropertyDate: "核算属性日期",
flowSpecificationId: "流程规范ID",
feeDetailSpecificationId: "费用明细规范ID",
printState: "打印状态",
printCount: "打印次数",
onlyOwnerPrint: "仅提交人可打印",
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
};
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
@@ -88,10 +135,8 @@ export function formatSingleBill(
// 字典 Label 还原
const meta = dictionary.get(k);
let readableKey = meta ? meta.label : k.replace(/^E_[^_]+_/, "");
if (readableKey.startsWith("E_")) {
readableKey = readableKey.replace(/^E_/, "");
}
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
let readableKey = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || bareKey);
// 格式化字段值
let formattedVal = v;
+155
View File
@@ -0,0 +1,155 @@
import { describe, expect, test } from "bun:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import {
createServer,
resolveMcpMode,
HOSE_CLI_TOOL_NAME,
HOSE_MCP_MODE_ENV,
tokenizeCommand,
normalizeCliArgs,
} from "./server.js";
import { VERSION } from "./version.js";
describe("hose-use MCP server & hose_cli single-gate pattern", () => {
test("tokenizes complex CLI arguments with quotes and JSON payloads", () => {
expect(
tokenizeCommand(`hose-use bill query --code "BX20260901001" --corp ID01MCcOgJl1td`)
).toEqual([
"hose-use",
"bill",
"query",
"--code",
"BX20260901001",
"--corp",
"ID01MCcOgJl1td",
]);
expect(
tokenizeCommand(`hose auth import --raw 'curl "https://app.ekuaibao.com/api?corpId=123" -H "accessToken: abc"'`)
).toEqual([
"hose",
"auth",
"import",
"--raw",
`curl "https://app.ekuaibao.com/api?corpId=123" -H "accessToken: abc"`,
]);
});
test("normalizes CLI prefix binary names", () => {
expect(normalizeCliArgs(["hose-use", "version"])).toEqual(["version"]);
expect(normalizeCliArgs(["hose", "corps", "list"])).toEqual(["corps", "list"]);
expect(normalizeCliArgs(["/usr/local/bin/hose", "probe"])).toEqual(["probe"]);
expect(normalizeCliArgs(["corps", "current"])).toEqual(["corps", "current"]);
});
test("resolves HOSE_MCP_MODE from environment variable", () => {
const original = process.env[HOSE_MCP_MODE_ENV];
delete process.env[HOSE_MCP_MODE_ENV];
try {
expect(resolveMcpMode()).toBe("single");
expect(resolveMcpMode("single")).toBe("single");
expect(resolveMcpMode("all")).toBe("all");
expect(resolveMcpMode("both")).toBe("all");
expect(resolveMcpMode("legacy")).toBe("legacy");
} finally {
if (original === undefined) delete process.env[HOSE_MCP_MODE_ENV];
else process.env[HOSE_MCP_MODE_ENV] = original;
}
});
test("advertises only hose_cli in single mode and executes commands in-process", async () => {
const server = createServer({ mode: "single" });
const client = new Client({ name: "hose-use-test-client", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(1);
expect(listed.tools[0]?.name).toBe(HOSE_CLI_TOOL_NAME);
expect(listed.tools[0]?.inputSchema).toMatchObject({
type: "object",
required: ["command"],
});
// Execute 'version'
const versionResult = await client.callTool({
name: HOSE_CLI_TOOL_NAME,
arguments: { command: "hose-use version" },
});
expect(versionResult.isError).not.toBe(true);
const content = versionResult.content as Array<{ type: "text"; text: string }>;
expect(content[0]?.text).toContain(`hose-use v${VERSION}`);
// Execute 'corps list'
const corpsResult = await client.callTool({
name: HOSE_CLI_TOOL_NAME,
arguments: { command: "corps list" },
});
expect(corpsResult.isError).not.toBe(true);
const corpsContent = corpsResult.content as Array<{ type: "text"; text: string }>;
expect(corpsContent[0]?.text).toContain("已配置企业列表");
// Execute invalid command
const invalidResult = await client.callTool({
name: HOSE_CLI_TOOL_NAME,
arguments: { command: "not-a-real-command-xyz" },
});
expect(invalidResult.isError).toBe(true);
const errContent = invalidResult.content as Array<{ type: "text"; text: string }>;
expect(errContent[0]?.text).toContain("未知命令域");
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("advertises both hose_cli and fine-grained tools in all mode", async () => {
const server = createServer({ mode: "all" });
const client = new Client({ name: "hose-use-test-all", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const listed = await client.listTools();
const toolNames = listed.tools.map((t) => t.name);
expect(toolNames).toContain(HOSE_CLI_TOOL_NAME);
expect(toolNames).toContain("bill_search");
expect(toolNames).toContain("list_corps");
expect(toolNames).toContain("platform_workflow_list_all");
expect(toolNames.length).toBeGreaterThan(5);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("advertises only fine-grained tools in legacy mode", async () => {
const server = createServer({ mode: "legacy" });
const client = new Client({ name: "hose-use-test-legacy", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const listed = await client.listTools();
const toolNames = listed.tools.map((t) => t.name);
expect(toolNames).not.toContain(HOSE_CLI_TOOL_NAME);
expect(toolNames).toContain("bill_search");
expect(toolNames).toContain("list_corps");
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});
+225 -26
View File
@@ -5,6 +5,8 @@ import {
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { loadCorpConfigs } from "./core/config/loader.js";
import { CorpContext } from "./core/config/manager.js";
import { createEkbClient } from "./core/auth/ekb.js";
@@ -13,6 +15,115 @@ import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.j
import { authTools } from "./core/auth/tools.js";
import { platformTools } from "./domains/platform/tools.js";
import { billTools } from "./domains/bill/tools.js";
import { runCli } from "./cli/runner.js";
import { VERSION } from "./version.js";
import type { CliResult } from "./cli/types.js";
export const HOSE_CLI_TOOL_NAME = "hose_cli";
export const HOSE_MCP_MODE_ENV = "HOSE_MCP_MODE"; // "single" | "all" | "legacy"
export type HoseMcpMode = "single" | "all" | "legacy";
const serverEntryFile = fileURLToPath(import.meta.url);
const appRoot = dirname(dirname(serverEntryFile));
export function resolveMcpMode(value = process.env[HOSE_MCP_MODE_ENV]): HoseMcpMode {
if (!value) return "single";
const normalized = value.trim().toLowerCase();
if (normalized === "all" || normalized === "both" || normalized === "full") return "all";
if (normalized === "legacy" || normalized === "multi") return "legacy";
return "single";
}
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
let quote: "'" | '"' | undefined;
let escaped = false;
let tokenStarted = false;
for (const character of command) {
if (escaped) {
token += character;
escaped = false;
tokenStarted = true;
continue;
}
if (character === "\\" && quote !== "'") {
escaped = true;
tokenStarted = true;
continue;
}
if (quote) {
if (character === quote) {
quote = undefined;
} else {
token += character;
}
tokenStarted = true;
continue;
}
if (character === "'" || character === '"') {
quote = character;
tokenStarted = true;
continue;
}
if (/\s/.test(character)) {
if (tokenStarted) {
tokens.push(token);
token = "";
tokenStarted = false;
}
continue;
}
token += character;
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
export function normalizeCliArgs(tokens: string[]): string[] {
const first = tokens[0];
if (!first) return [];
const lower = first.toLowerCase().replace(/\\/g, "/");
if (
lower === "hose-use" ||
lower === "hose" ||
lower.endsWith("/hose-use") ||
lower.endsWith("/hose") ||
lower.endsWith("/hose-use.exe") ||
lower.endsWith("/hose.exe")
) {
return tokens.slice(1);
}
return tokens;
}
export function cliResult(result: CliResult): {
content: Array<{ type: "text"; text: string }>;
isError: boolean;
} {
const isError = result.exitCode !== 0;
let text = isError ? (result.stderr || result.stdout || "Command failed") : (result.stdout || result.stderr || "Success");
return {
content: [
{
type: "text",
text: text.trimEnd(),
},
],
isError,
};
}
function formatError(error: unknown): {
content: Array<{ type: "text"; text: string }>;
@@ -46,22 +157,19 @@ function formatError(error: unknown): {
};
}
console.error(error);
return {
content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }],
isError: true,
};
}
async function main() {
// 加载企业配置
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps);
export function createServer(options: { mode?: HoseMcpMode } = {}) {
const mode = options.mode ?? resolveMcpMode();
const server = new Server(
{
name: "ekb-mcp",
version: "0.1.0",
name: "hose-use",
version: VERSION,
},
{
capabilities: {
@@ -70,26 +178,89 @@ async function main() {
}
);
// 聚合所有工具
const allTools = [...authTools, ...platformTools, ...billTools];
const fineGrainedTools = [...authTools, ...platformTools, ...billTools];
// 注册工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: allTools.map((t) => ({
name: t.name,
description: t.description,
inputSchema: (t.parameters as any).toJSONSchema(),
})),
};
const tools: Array<{ name: string; description?: string; inputSchema: any }> = [];
// 单工具网关
if (mode === "single" || mode === "all") {
tools.push({
name: HOSE_CLI_TOOL_NAME,
description:
"Run hose-use CLI commands (e.g. 'bill query', 'corps list', 'workflow search'). See the hose-use skill for command reference.",
inputSchema: {
type: "object",
properties: {
command: {
type: "string",
description:
"A hose-use CLI command string, with or without the leading 'hose-use' or 'hose'. Example: 'corps list' or 'bill query --code BX20260901001'.",
},
},
required: ["command"],
additionalProperties: false,
},
});
}
// 细粒度工具(仅在 all 或 legacy 模式下保留)
if (mode === "all" || mode === "legacy") {
for (const t of fineGrainedTools) {
tools.push({
name: t.name,
description: t.description,
inputSchema: (t.parameters as any).toJSONSchema(),
});
}
}
return { tools };
});
// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
// 1. 处理 hose_cli 网关工具调用
if (name === HOSE_CLI_TOOL_NAME) {
const command = args && typeof args.command === "string" ? args.command : undefined;
if (!command?.trim()) {
return cliResult({
stdout: "",
stderr: "hose_cli requires a non-empty command string",
exitCode: 1,
});
}
try {
const tokens = tokenizeCommand(command);
const cliArgs = normalizeCliArgs(tokens);
if (!cliArgs.length) {
throw new Error("hose_cli requires a non-empty command string");
}
const result = await runCli(cliArgs, {
appRoot,
entryFile: serverEntryFile,
});
return cliResult(result);
} catch (error) {
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
exitCode: 1,
});
}
}
// 2. 处理细粒度工具兼容调用
try {
// 1. 检查 Auth 工具
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps);
// Auth 工具
const authTool = authTools.find((t) => t.name === name);
if (authTool) {
const parsed = authTool.parameters.safeParse(args || {});
@@ -110,7 +281,7 @@ async function main() {
};
}
// 2. 检查 Bill 工具
// Bill 工具
const billTool = billTools.find((t) => t.name === name);
if (billTool) {
const parsed = billTool.parameters.safeParse(args || {});
@@ -131,21 +302,20 @@ async function main() {
};
}
// 3. 检查 Domain 业务工具(需要当前企业上下文)
// Platform 业务工具
const currentCorp = corpContext.getCurrent();
if (!currentCorp) {
return {
content: [
{
type: "text",
text: "未配置企业,请先调用 import_f12_corp 导入凭证,或执行 bun run login 登录",
text: "未配置企业,请先调用 auth login 登录或 auth import 导入凭证",
},
],
isError: true,
};
}
// Platform 工具
const platformTool = platformTools.find((t) => t.name === name);
if (platformTool) {
const parsed = platformTool.parameters.safeParse(args || {});
@@ -175,7 +345,7 @@ async function main() {
content: [
{
type: "text",
text: `未知工具: ${name}`,
text: `未知工具: ${name}。在单工具网关模式下,请通过 ${HOSE_CLI_TOOL_NAME} 调用。`,
},
],
isError: true,
@@ -185,9 +355,38 @@ async function main() {
}
});
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("EKB MCP Server running on stdio");
return server;
}
main().catch(console.error);
export async function startServer() {
const server = createServer();
const transport = new StdioServerTransport();
await server.connect(transport);
console.error(`hose-use MCP Server (v${VERSION}) running on stdio [mode: ${resolveMcpMode()}]`);
}
async function runEmbeddedCli() {
const result = await runCli(process.argv.slice(3), {
appRoot,
entryFile: serverEntryFile,
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
process.exitCode = result.exitCode;
}
const isMainModule = Boolean(
(import.meta as any).main ||
(!import.meta.url.includes("$bunfs") && process.argv[1] && resolve(process.argv[1]) === resolve(serverEntryFile))
);
if (isMainModule) {
if (process.argv[2] === "--hose-use-cli" || process.argv[2] === "--hose-cli") {
await runEmbeddedCli();
} else {
startServer().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}
}
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.3.0";
export const VERSION = "0.4.1";