refactor(mcp): remove deprecated fine-grained MCP tool definitions and simplify server to single CLI gateway

This commit is contained in:
gitea committed 2026-09-29 23:42:12 +08:00
1 parent c60d49fb8c
commit 76f7832522
11 files changed
+67 -841

No files matched your search

-79
View File
@@ -1,79 +0,0 @@
import { z } from "zod";
import { CorpContext } from "../config/manager.js";
import { createSessionClient } from "../http/session-client.js";
// ── 精简 MCP Auth Tools (其余复杂登录/刷新均由 CLI 直接提供) ───────────────────
export const authTools = [
{
name: "list_corps",
description: "列出当前所有已配置的企业列表",
parameters: z.object({}),
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
return {
activeCorp: corpContext.getCurrent()?.id,
corporations: corpContext.listCorps(),
};
},
},
{
name: "switch_corp",
description: "切换当前活跃工作企业",
parameters: z.object({
corpId: z.string().describe("目标企业 ID"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { corpId: string }
) => {
const success = corpContext.switchCorp(params.corpId);
if (!success) {
throw new Error(`企业 ${params.corpId} 不存在或未配置`);
}
const current = corpContext.getCurrent();
return {
success: true,
message: `已切换到企业: ${current?.name} (${current?.id})`,
corp: current,
};
},
},
{
name: "whoami",
description: "查看当前操作员身份、当前活跃企业与账号状态",
parameters: z.object({}),
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
const current = corpContext.getCurrent();
if (!current) {
return {
authenticated: false,
message: "未配置任何企业,请先运行 hose-use auth login",
};
}
let sessionValid = false;
let sessionData: unknown = null;
try {
const client = await createSessionClient(current);
const res = await client.get("api/account/v2/session").json<{ value?: unknown }>();
sessionData = res.value;
sessionValid = !!res.value;
} catch {
sessionValid = false;
}
return {
authenticated: sessionValid,
currentCorp: {
id: current.id,
name: current.name,
staffId: current.credentials.staffId,
source: current.source,
accountId: current.accountId,
baseUrl: current.baseUrl,
},
session: sessionData,
};
},
},
];
-101
View File
@@ -1,4 +1,3 @@
import { z } from "zod";
import { KyInstance } from "ky";
import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
@@ -53,8 +52,6 @@ import {
type FormSpecificationComponent,
type FormPriorityItem,
} from "./types.js";
import { CorpContext } from "../../core/config/manager.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { resolveDimension } from "../dimension/tools.js";
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
@@ -1353,104 +1350,6 @@ export async function searchAndFormatBills(
};
}
// ── MCP Tools 适配 ────────────────────────────────────────────────────────────
export const billTools = [
{
name: "bill_search",
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称,原生支持服务端时间与单号过滤)",
parameters: z.object({
code: z.string().optional().describe("按单据编号/单号过滤(如 jO1it3cIufDjNS)"),
keyword: z.string().optional().describe("按关键字模糊搜索标题、名称或内容"),
searchFields: z.union([z.array(z.string()), z.string()]).optional().describe("指定 keyword 检索匹配的字段列表,默认 ['name', 'code', 'form'],可传入 ['name'] 或 'name,code' 等"),
since: z.string().optional().describe("相对时间范围,如 7d (7天), 30d (30天), 90d, 1y"),
startDate: z.string().optional().describe("起始时间 (YYYY-MM-DD 或毫秒时间戳)"),
endDate: z.string().optional().describe("截止时间 (YYYY-MM-DD 或毫秒时间戳)"),
filterBy: z.string().optional().describe("原始合思 RQL 检索表达式,如 ((createTime > 1780000000000) && (code.in('BX-001')))"),
select: z.string().optional().describe("按需返回字段(逗号分隔),如 id,code,name,createTime,updateTime,form"),
distinct: z.boolean().optional().describe("是否对单据结果去重"),
stage: z.string().optional().describe("按阶段过滤(如 expense 报销, loan 借款, payment 付款)"),
state: z.string().optional().describe("按审批/支付状态过滤(如 paid 已支付, approving 审批中, draft 草稿)"),
count: z.number().optional().default(20).describe("拉取记录数"),
order: z.enum(["ASC", "DESC", "asc", "desc"]).optional().default("DESC").describe("排序方向,默认 DESC 最新在前"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: BillQueryParams
) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createSessionClient(corp);
const result = await searchAndFormatBills(client, corp.corpId || corp.id, params);
return {
corpId: corp.corpId || corp.id,
corpName: corp.name,
...result,
};
},
},
{
name: "bill_get",
description: "根据单据编号(单号)或单据 ID 精确查询单据详细信息与格式化表单明细",
parameters: z.object({
code: z.string().describe("单据编号(如 jO1it3cIufDjNS)或 单据 ID(如 ID01V0zDDjZNHp)"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { code: string }
) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createSessionClient(corp);
const bills = await getBillByCodeOrId(client, corp.corpId || corp.id, params.code);
if (bills.length === 0) {
return {
found: false,
message: `未找到单号或 ID 为 [${params.code}] 的单据`,
code: params.code,
};
}
return {
found: true,
count: bills.length,
bills,
};
},
},
{
name: "bill_schema",
description: "获取企业全部单据实体的数据模型、表单定义与中文字段 Label 字典",
parameters: z.object({}),
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createSessionClient(corp);
const { entities } = await getFieldDictionary(client, corp.corpId || corp.id, true);
return {
corpId: corp.corpId || corp.id,
totalEntities: entities.length,
entities: entities.map((e) => ({
id: e.id,
name: e.name,
type: e.type,
fieldCount: e.fields.length,
fields: e.fields.map((f) => ({
name: f.name,
label: f.label,
type: f.type,
})),
})),
};
},
},
];
export async function getTranslatorContext(
client: KyInstance,
corpId: string,
-43
View File
@@ -1,4 +1,3 @@
import { z } from "zod";
import { getEasoClient } from "../../core/http/unity-client.js";
import type { CorpConfig } from "../../core/config/types.js";
import { fetchStaffs } from "./api.js";
@@ -67,45 +66,3 @@ export async function getStaffById(
return found || null;
}
// ── MCP Tool Definitions ──────────────────────────────────────────────────────
export const contactTools = [
{
name: "contact_search",
description: "在当前企业通讯录中模糊检索员工(支持姓名、邮箱、手机号、工号)",
parameters: z.object({
keyword: z.string().describe("检索关键词,如姓名、邮箱前缀、手机号或工号"),
limit: z.number().optional().describe("最大返回条数,默认 20"),
}),
handler: async (corp: CorpConfig, params: { keyword: string; limit?: number }) => {
const results = await searchStaffs(corp, params);
return { count: results.length, staffs: results };
},
},
{
name: "contact_get",
description: "根据员工 staffId 或工号精准获取员工详细档案",
parameters: z.object({
staffId: z.string().describe("员工的完整 staffId 或 ID"),
}),
handler: async (corp: CorpConfig, params: { staffId: string }) => {
const staff = await getStaffById(corp, params.staffId);
if (!staff) {
throw new Error(`未找到员工: ${params.staffId}`);
}
return staff;
},
},
{
name: "contact_list",
description: "查看企业通讯录(带默认 20 条防爆截断与总数保护)",
parameters: z.object({
limit: z.number().optional().describe("截断返回条数,默认 20"),
allowFull: z.boolean().optional().describe("是否强制全量输出(大企业请谨慎使用)"),
}),
handler: async (corp: CorpConfig, params: { limit?: number; allowFull?: boolean }) => {
return await listStaffsProtected(corp, params);
},
},
];
-136
View File
@@ -1,136 +0,0 @@
import { z } from "zod";
import * as api from "./api.js";
const clientSchema = z.object({
corp: z.object({ credentials: z.object({ corpId: z.string() }) }).passthrough(),
ekbClient: z.any(),
});
export const datalinkTools = [
{
name: "datalink_platform_list",
description: "列出当前企业账号可见的启用自建应用(可传入 all=true 查看包含模板平台的完整列表)",
parameters: z.object({
all: z.boolean().optional().describe("是否拉取包含 HAB 模板与全量平台列表"),
}),
handler: async (clients: unknown, params: { all?: boolean } = {}) => {
const { corp, ekbClient } = clientSchema.parse(clients);
const platforms = params.all
? await api.listAllPlatforms(ekbClient, corp.credentials.corpId)
: await api.listPlatforms(ekbClient, corp.credentials.corpId);
return { platforms };
},
},
{
name: "datalink_platform_get",
description: "获取自建应用详情以及应用管理员、人员、角色和部门可见权限",
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
handler: async (clients: unknown, params: { platformId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.getPlatform(ekbClient, corp.credentials.corpId, params.platformId);
},
},
{
name: "datalink_entity_list",
description: "获取一个自建应用下的业务对象目录、字段、操作和可见性配置",
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
handler: async (clients: unknown, params: { platformId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return { entities: await api.listPlatformEntities(ekbClient, corp.credentials.corpId, params.platformId) };
},
},
{
name: "datalink_record_search",
description: "分页检索业务对象记录,支持 DataLink filterBy 表达式",
parameters: z.object({
entityId: z.string().describe("业务对象 ID"),
start: z.number().int().min(0).optional(),
count: z.number().int().min(1).max(1000).optional(),
filterBy: z.string().optional().describe("DataLink 原生过滤表达式"),
}),
handler: async (clients: unknown, params: { entityId: string; start?: number; count?: number; filterBy?: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.searchEntityRecords(ekbClient, corp.credentials.corpId, params.entityId, params);
},
},
{
name: "datalink_import_jobs",
description: "查看业务对象的导入任务和最近导入结果",
parameters: z.object({ entityId: z.string().describe("业务对象 ID") }),
handler: async (clients: unknown, params: { entityId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
const [jobs, result] = await Promise.all([
api.listImportJobs(ekbClient, corp.credentials.corpId, params.entityId),
api.getImportResult(ekbClient, corp.credentials.corpId, params.entityId),
]);
return { jobs, latestResult: result };
},
},
{
name: "datalink_record_get",
description: "获取单条业务对象记录的完整详情(模板、字段值、可见性及历史等)",
parameters: z.object({
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
}),
handler: async (clients: unknown, params: { recordId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.getRecordDetail(ekbClient, corp.credentials.corpId, params.recordId);
},
},
{
name: "datalink_record_toggle",
description: "切换业务对象记录的停启用状态 (active: true <-> false)",
parameters: z.object({
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
state: z.boolean().optional().describe("目标状态 (true 为启用,false 为停用,不传则自动翻转)"),
}),
handler: async (clients: unknown, params: { recordId: string; state?: boolean }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
const result = await api.toggleRecordState(ekbClient, corp.credentials.corpId, params.recordId, params.state);
return { success: true, ...result };
},
},
{
name: "datalink_record_edit",
description: "编辑更新业务对象记录的字段值",
parameters: z.object({
entityId: z.string().describe("业务对象 ID"),
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
form: z.record(z.string(), z.unknown()).describe("待更新的表单字段键值对"),
active: z.boolean().optional().describe("停启用状态"),
visibility: z.record(z.string(), z.unknown()).optional().describe("可见性配置"),
}),
handler: async (
clients: unknown,
params: {
entityId: string;
recordId: string;
form: Record<string, unknown>;
active?: boolean;
visibility?: Record<string, unknown>;
}
) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.editRecord(ekbClient, corp.credentials.corpId, {
dataLinkEntityId: params.entityId,
dataLinkId: params.recordId,
form: params.form,
active: params.active,
visibility: params.visibility,
});
},
},
{
name: "datalink_record_recompute",
description: "重新计算指定业务对象记录下的全部台账信息",
parameters: z.object({
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
}),
handler: async (clients: unknown, params: { recordId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.recomputeRecordLedger(ekbClient, corp.credentials.corpId, params.recordId);
},
},
];
export type DatalinkTool = (typeof datalinkTools)[number];
-19
View File
@@ -1,4 +1,3 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { getGlobalCache } from "../../core/cache/index.js";
import { listDimensionCatalogs, listDimensionItems } from "./api.js";
@@ -53,21 +52,3 @@ export async function resolveDimension(
if (!dimension) return undefined;
return { dimension, items: await getDimensionItems(client, corpId, dimension) };
}
export const dimensionTools = [
{
name: "dimension_list",
description: "列出企业档案管理中的系统/自定义档案维度目录",
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const items = await searchDimensions(
await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp)),
corp.corpId || corp.id,
{ name: params.keyword }
);
return { count: items.length, dimensions: items.slice(0, params.count ?? 100) };
},
},
];
-100
View File
@@ -1,5 +1,4 @@
import type { KyInstance } from "ky";
import { z } from "zod";
import {
FeeTypeComponent,
FeeTypeCreateInput,
@@ -447,102 +446,3 @@ export async function getFeeTypeFieldsList(
requisitionFields: (detail.specifications?.requisitionComponents ?? []).map(mapComponent),
};
}
// ── MCP Tool Definitions ─────────────────────────────────────────────────────
export const feetypeTools = [
{
name: "feetype_list",
description: "查询企业费用类型树或平铺列表 (可按关键词筛选、包含已停用)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
keyword: z.string().optional().describe("搜索关键词 (名称/编码/全路径)"),
all: z.boolean().optional().default(false).describe("是否包含已停用的费用类型"),
flat: z.boolean().optional().default(false).describe("是否以平铺列表格式返回"),
}),
handler: async (client: KyInstance, args: any) => {
return listFeeTypes(client, args.corpId, {
keyword: args.keyword,
all: args.all,
flat: args.flat,
});
},
},
{
name: "feetype_get",
description: "获取单个费用类型的详细配置与字段规格",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("费用类型 ID、编码或名称"),
includeSpecs: z.boolean().optional().default(false).describe("是否包含报账与申请字段规格定义"),
}),
handler: async (client: KyInstance, args: any) => {
return getFeeTypeDetail(client, args.corpId, args.target, {
includeSpecs: args.includeSpecs,
});
},
},
{
name: "feetype_create",
description: "新建费用类型 (支持指定父级节点、编码自增与继承字段规则)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
name: z.string().describe("费用类型名称"),
code: z.string().optional().describe("费用编码 (不提供则系统自增生成)"),
parentId: z.string().optional().describe("父级费用类型 ID、编码或名称 (不提供则建为顶级)"),
enName: z.string().optional().describe("英文名称"),
description: z.string().optional().describe("描述信息"),
color: z.string().optional().describe("标识颜色 (如 #90caf9)"),
}),
handler: async (client: KyInstance, args: any) => {
return createFeeType(client, args.corpId, args);
},
},
{
name: "feetype_update",
description: "修改费用类型属性 (名称、编码、英文名、颜色、图标或描述)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("费用类型 ID、编码或名称"),
name: z.string().optional().describe("新名称"),
code: z.string().optional().describe("新编码"),
enName: z.string().optional().describe("新英文名"),
description: z.string().optional().describe("新描述"),
color: z.string().optional().describe("新颜色"),
}),
handler: async (client: KyInstance, args: any) => {
return updateFeeTypeInfo(client, args.corpId, args.target, args);
},
},
{
name: "feetype_toggle",
description: "停用或启用费用类型",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("费用类型 ID、编码或名称"),
action: z.enum(["disable", "enable"]).describe("执行动作: disable 停用, enable 启用"),
recursive: z.boolean().optional().default(true).describe("启用时是否递归启用子节点"),
}),
handler: async (client: KyInstance, args: any) => {
if (args.action === "disable") {
return disableFeeTypeItem(client, args.corpId, args.target);
} else {
return enableFeeTypeItem(client, args.corpId, args.target, {
recursive: args.recursive,
});
}
},
},
{
name: "feetype_move",
description: "移动费用类型至新的父级节点 (传入 root 移至根目录)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("待移动的费用类型 ID、编码或名称"),
parent: z.string().describe("目标父级费用类型 ID、编码或名称 (传入 'root' 为移至顶级)"),
}),
handler: async (client: KyInstance, args: any) => {
return moveFeeTypeItem(client, args.corpId, args.target, args.parent);
},
},
];
+3 -13
View File
@@ -1,16 +1,6 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { getRolePermissions } from "./api.js";
export async function getPermissions(client: KyInstance, corpId: string) { return getRolePermissions(client, corpId); }
export const permissionTools = [{
name: "permission_role_get",
description: "读取当前企业角色模型的权限开关(只读)",
parameters: z.object({}),
handler: async ({ corpContext }: any) => {
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp));
return getPermissions(client, corp.corpId || corp.id);
},
}];
export async function getPermissions(client: KyInstance, corpId: string) {
return getRolePermissions(client, corpId);
}
-41
View File
@@ -1,41 +0,0 @@
import { z } from "zod";
import * as api from "./api.js";
import {
PlatformClients,
listAllWorkflows,
findWorkflowsByTaskType,
} from "./services.js";
// ── 精简核心 MCP Tools (其余功能均由 CLI 和底层 SDK 直接提供) ──────────────────
export const platformTools = [
{
name: "platform_workflow_list_all",
description: "跨所有启用自建应用汇总工作流列表,返回带 platformId/platformName 的聚合结果",
parameters: z.object({
page: z.number().optional().describe("页码,默认 1"),
pageSize: z.number().optional().describe("每页数量,默认 20"),
}),
handler: async (
clients: PlatformClients,
params: { page?: number; pageSize?: number }
) => {
return await listAllWorkflows(clients, params);
},
},
{
name: "platform_workflow_detail",
description: "获取工作流节点与 DSL 配置详情",
parameters: z.object({
pipelineId: z.string().describe("工作流 ID"),
}),
handler: async (
{ easoClient }: PlatformClients,
params: { pipelineId: string }
) => {
return await api.getWorkflowDetail(easoClient, params.pipelineId);
},
},
];
export type PlatformTool = (typeof platformTools)[number];
-16
View File
@@ -1,4 +1,3 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { getGlobalCache } from "../../core/cache/index.js";
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
@@ -64,18 +63,3 @@ export async function getRoleMembers(
if (!role) return undefined;
return { role, members: await listRoleMembers(client, corpId, role.id) };
}
export const roleTools = [
{
name: "role_list",
description: "列出当前企业角色定义与角色组",
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp));
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
},
},
];
+11 -59
View File
@@ -43,24 +43,13 @@ describe("hose-use MCP server & hose_cli single-gate pattern", () => {
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("resolves HOSE_MCP_MODE to single gateway mode", () => {
expect(resolveMcpMode()).toBe("single");
expect(resolveMcpMode("single")).toBe("single");
});
test("advertises only hose_cli in single mode and executes commands in-process", async () => {
const server = createServer({ mode: "single" });
test("advertises only hose_cli and executes commands in-process", async () => {
const server = createServer();
const client = new Client({ name: "hose-use-test-client", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
@@ -105,50 +94,13 @@ describe("hose-use MCP server & hose_cli single-gate pattern", () => {
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");
// Calling unknown tool returns error
const unknownToolResult = await client.callTool({
name: "legacy_removed_tool",
arguments: {},
});
expect(unknownToolResult.isError).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
+53 -234
View File
@@ -1,27 +1,17 @@
import { Server } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
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 { createSessionClient, getEasoClient, getUnityClient } from "./core/http/index.js";
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
import { authTools } from "./core/auth/tools.js";
import { platformTools } from "./domains/platform/tools.js";
import { datalinkTools } from "./domains/datalink/tools.js";
import { billTools } from "./domains/bill/tools.js";
import { feetypeTools } from "./domains/feetype/tools.js";
import { runCli } from "./cli/runner.js";
import { redactSensitiveText } from "./cli/printer.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 const HOSE_MCP_MODE_ENV = "HOSE_MCP_MODE";
export const HOSE_MCP_ENABLED_ENV = "HOSE_USE_MCP_ENABLED";
export type HoseMcpMode = "single" | "all" | "legacy";
export type HoseMcpMode = "single";
const serverEntryFile = fileURLToPath(import.meta.url);
const appRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\")
@@ -33,11 +23,7 @@ export function resolveMcpEnabled(value = process.env[HOSE_MCP_ENABLED_ENV]): bo
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
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";
export function resolveMcpMode(_value = process.env[HOSE_MCP_MODE_ENV]): HoseMcpMode {
return "single";
}
@@ -132,47 +118,8 @@ export function cliResult(result: CliResult): {
};
}
function formatError(error: unknown): {
content: Array<{ type: "text"; text: string }>;
isError: true;
} {
if (error instanceof NotLoggedInError) {
return {
content: [{ type: "text", text: "未配置企业,请先添加企业配置或登录" }],
isError: true,
};
}
if (error instanceof AuthenticationError) {
return {
content: [{ type: "text", text: `认证失败: ${error.message}` }],
isError: true,
};
}
if (error instanceof EkbError) {
return {
content: [{ type: "text", text: `错误 [${error.code}]: ${error.message}` }],
isError: true,
};
}
if (error instanceof z.ZodError) {
return {
content: [{ type: "text", text: `参数错误: ${error.message}` }],
isError: true,
};
}
return {
content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }],
isError: true,
};
}
export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean } = {}) {
export function createServer(options: { mode?: string; enabled?: boolean } = {}) {
const enabled = options.enabled ?? resolveMcpEnabled();
const mode = options.mode ?? resolveMcpMode();
const server = new Server(
{
@@ -186,48 +133,32 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
}
);
const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools, ...feetypeTools];
// 注册工具列表
// 注册单工具网关
server.setRequestHandler("tools/list", async () => {
if (!enabled) {
return { tools: [] };
}
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, including workflow get/patch/save/publish/history/logs/check. 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: 'workflow check --json', 'workflow publish <pipelineId>', or 'workflow get <pipelineId> --json -o workflow.json'.",
return {
tools: [
{
name: HOSE_CLI_TOOL_NAME,
description:
"Run hose-use CLI commands, including workflow get/patch/save/publish/history/logs/check. 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: 'workflow check --json', 'workflow publish <pipelineId>', or 'workflow get <pipelineId> --json -o workflow.json'.",
},
},
required: ["command"],
additionalProperties: false,
},
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 };
],
};
});
// 处理工具调用
@@ -241,157 +172,45 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
}
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 {
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 || {});
if (!parsed.success) {
return {
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
isError: true,
};
}
const result = await authTool.handler({ corpContext }, parsed.data as never);
return {
content: [
{
type: "text",
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
},
],
};
}
// Bill 工具
const billTool = billTools.find((t) => t.name === name);
if (billTool) {
const parsed = billTool.parameters.safeParse(args || {});
if (!parsed.success) {
return {
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
isError: true,
};
}
const result = await billTool.handler({ corpContext }, parsed.data as never);
return {
content: [
{
type: "text",
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
},
],
};
}
// Platform 业务工具
const currentCorp = corpContext.getCurrent();
if (!currentCorp) {
return {
content: [
{
type: "text",
text: "未配置企业,请先调用 auth login 登录或 auth import 导入凭证",
},
],
isError: true,
};
}
const platformTool = platformTools.find((t) => t.name === name);
if (platformTool) {
const parsed = platformTool.parameters.safeParse(args || {});
if (!parsed.success) {
return {
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
isError: true,
};
}
const sessionClient = await createSessionClient(currentCorp);
const { client: easoClient } = await getEasoClient(currentCorp).catch(() =>
getUnityClient(currentCorp)
);
const result = await platformTool.handler(
{ corp: currentCorp, ekbClient: sessionClient, easoClient },
parsed.data as never
);
return {
content: [
{
type: "text",
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
},
],
};
}
// DataLink 应用/业务对象/记录工具
const datalinkTool = datalinkTools.find((t) => t.name === name);
if (datalinkTool) {
const parsed = datalinkTool.parameters.safeParse(args || {});
if (!parsed.success) {
return {
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
isError: true,
};
}
const sessionClient = await createSessionClient(currentCorp);
const result = await datalinkTool.handler(
{ corp: currentCorp, ekbClient: sessionClient },
parsed.data as never
);
return {
content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result, null, 2) }],
};
}
if (name !== HOSE_CLI_TOOL_NAME) {
return {
content: [
{
type: "text",
text: `未知工具: ${name}。在单工具网关模式下,请通过 ${HOSE_CLI_TOOL_NAME} 调用。`,
text: `未知工具: ${name}。请通过 ${HOSE_CLI_TOOL_NAME} 调用 CLI 命令。`,
},
],
isError: true,
};
}
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 formatError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
exitCode: 1,
});
}
});