diff --git a/.gitignore b/.gitignore index c61d6c1..a8a5b51 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,5 @@ data/ *.db *.sqlite -# 环境变量 -.env -.env.local +# Local roadmaps & scratch notes +*.local.md diff --git a/README.md b/README.md index 51704f6..ba65be3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# hose-use (v0.3.1) +# hose-use (v0.4.0) 合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。 @@ -60,12 +60,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 diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index 1f571db..b03e65e 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: hose-use API & MCP Tools Specification - version: 0.3.1 + version: 0.4.0 description: >- Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows. servers: diff --git a/package.json b/package.json index b958c7c..6478bcc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.3.1", + "version": "0.4.0", "module": "src/server.ts", "type": "module", "bin": { diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 7bd8df0..cb0f8ac 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -15,6 +15,32 @@ description: 合思/易快报 (ekuaibao) 企业 SaaS CLI 命令行工具与底 - **有状态 / 无状态双模式**: - **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。 - **无状态 (Stateless)**:严格要求 `--corp `,防止多租户或 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 + ``` --- diff --git a/src/cli/runner.ts b/src/cli/runner.ts index ab72b63..89c1b5e 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -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(undefined); + +export function runCli( + rawArgs: string[], + options: CliRunOptions = {} +): Promise { + const run = runQueue.then(() => runCliOnce(rawArgs, options)); + runQueue = run.then( + () => undefined, + () => undefined + ); + return run; +} + +async function runCliOnce( + rawArgs: string[], + options: CliRunOptions = {} +): Promise { + 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 { diff --git a/src/server.test.ts b/src/server.test.ts new file mode 100644 index 0000000..2b5a9c2 --- /dev/null +++ b/src/server.test.ts @@ -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()]); + } + }); +}); diff --git a/src/server.ts b/src/server.ts index 7f9c3ce..1e496d0 100644 --- a/src/server.ts +++ b/src/server.ts @@ -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; + }); + } +} diff --git a/src/version.ts b/src/version.ts index 767a57d..fab1818 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.3.1"; +export const VERSION = "0.4.0";