253 lines
6.8 KiB
TypeScript
253 lines
6.8 KiB
TypeScript
import { Server } from "@modelcontextprotocol/server";
|
|
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
import { dirname, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { runCli } from "./cli/runner.js";
|
|
import { redactSensitiveText, writeStdoutChunk } 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";
|
|
export const HOSE_MCP_ENABLED_ENV = "HOSE_USE_MCP_ENABLED";
|
|
|
|
export type HoseMcpMode = "single";
|
|
|
|
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 {
|
|
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,
|
|
};
|
|
}
|
|
|
|
export function createServer(options: { mode?: string; enabled?: boolean } = {}) {
|
|
const enabled = options.enabled ?? resolveMcpEnabled();
|
|
|
|
const server = new Server(
|
|
{
|
|
name: "hose-use",
|
|
version: VERSION,
|
|
},
|
|
{
|
|
capabilities: {
|
|
tools: {},
|
|
},
|
|
}
|
|
);
|
|
|
|
// 注册单工具网关
|
|
server.setRequestHandler("tools/list", async () => {
|
|
if (!enabled) {
|
|
return { tools: [] };
|
|
}
|
|
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,
|
|
},
|
|
},
|
|
],
|
|
};
|
|
});
|
|
|
|
// 处理工具调用
|
|
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;
|
|
|
|
if (name !== HOSE_CLI_TOOL_NAME) {
|
|
return {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
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 cliResult({
|
|
stdout: "",
|
|
stderr: error instanceof Error ? error.message : String(error),
|
|
exitCode: 1,
|
|
});
|
|
}
|
|
});
|
|
|
|
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,
|
|
writeStdout: writeStdoutChunk,
|
|
});
|
|
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;
|
|
});
|
|
}
|
|
}
|