432 lines
13 KiB
TypeScript
432 lines
13 KiB
TypeScript
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 { createEkbClient } from "./core/auth/ekb.js";
|
|
import { getEasoClient } from "./core/auth/easo.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_ENABLED_ENV = "HOSE_USE_MCP_ENABLED";
|
|
|
|
export type HoseMcpMode = "single" | "all" | "legacy";
|
|
|
|
const serverEntryFile = fileURLToPath(import.meta.url);
|
|
const appRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\")
|
|
? dirname(dirname(dirname(serverEntryFile)))
|
|
: dirname(dirname(serverEntryFile));
|
|
|
|
export function resolveMcpEnabled(value = process.env[HOSE_MCP_ENABLED_ENV]): boolean {
|
|
if (value === undefined) return true;
|
|
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";
|
|
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");
|
|
text = redactSensitiveText(text);
|
|
return {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
text: text.trimEnd(),
|
|
},
|
|
],
|
|
isError,
|
|
};
|
|
}
|
|
|
|
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 } = {}) {
|
|
const enabled = options.enabled ?? resolveMcpEnabled();
|
|
const mode = options.mode ?? resolveMcpMode();
|
|
|
|
const server = new Server(
|
|
{
|
|
name: "hose-use",
|
|
version: VERSION,
|
|
},
|
|
{
|
|
capabilities: {
|
|
tools: {},
|
|
},
|
|
}
|
|
);
|
|
|
|
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'.",
|
|
},
|
|
},
|
|
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("tools/call", async (request: any) => {
|
|
if (!enabled) {
|
|
return cliResult({
|
|
stdout: "",
|
|
stderr: "hose-use MCP 服务在插件配置中已被禁用 (HOSE_USE_MCP_ENABLED=false)",
|
|
exitCode: 1,
|
|
});
|
|
}
|
|
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 ekbClient = await createEkbClient(currentCorp);
|
|
const { client: easoClient } = await getEasoClient(currentCorp);
|
|
const result = await platformTool.handler(
|
|
{ corp: currentCorp, ekbClient, 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 ekbClient = await createEkbClient(currentCorp);
|
|
const result = await datalinkTool.handler(
|
|
{ corp: currentCorp, ekbClient },
|
|
parsed.data as never
|
|
);
|
|
return {
|
|
content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result, null, 2) }],
|
|
};
|
|
}
|
|
|
|
return {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
text: `未知工具: ${name}。在单工具网关模式下,请通过 ${HOSE_CLI_TOOL_NAME} 调用。`,
|
|
},
|
|
],
|
|
isError: true,
|
|
};
|
|
} catch (error) {
|
|
return formatError(error);
|
|
}
|
|
});
|
|
|
|
return server;
|
|
}
|
|
|
|
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;
|
|
});
|
|
}
|
|
}
|