xiaozhi-client 1.5.0-beta.0 → 1.5.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -9
- package/dist/adaptiveMCPPipe.d.ts +8 -0
- package/dist/adaptiveMCPPipe.js +12 -0
- package/dist/adaptiveMCPPipe.js.map +1 -0
- package/dist/autoCompletion.js +1 -1
- package/dist/autoCompletion.js.map +1 -1
- package/dist/cli.js +11 -11
- package/dist/cli.js.map +1 -1
- package/dist/configManager.d.ts +17 -4
- package/dist/configManager.js +1 -1
- package/dist/configManager.js.map +1 -1
- package/dist/mcpCommands.js +1 -1
- package/dist/mcpCommands.js.map +1 -1
- package/dist/mcpServerProxy.js +7 -7
- package/dist/mcpServerProxy.js.map +1 -1
- package/dist/modelScopeMCPClient.d.ts +35 -0
- package/dist/modelScopeMCPClient.js +3 -0
- package/dist/modelScopeMCPClient.js.map +1 -0
- package/dist/multiEndpointMCPPipe.d.ts +29 -0
- package/dist/multiEndpointMCPPipe.js +8 -0
- package/dist/multiEndpointMCPPipe.js.map +1 -0
- package/dist/services/mcpServer.js +3 -3
- package/dist/services/mcpServer.js.map +1 -1
- package/dist/webServer.js +3 -3
- package/dist/webServer.js.map +1 -1
- package/package.json +1 -1
- package/dist/mcpPipe.d.ts +0 -41
- package/dist/mcpPipe.js +0 -11
- package/dist/mcpPipe.js.map +0 -1
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { SSEMCPServerConfig } from './configManager.js';
|
|
2
|
+
import { IMCPClient } from './mcpServerProxy.js';
|
|
3
|
+
|
|
4
|
+
interface Tool {
|
|
5
|
+
name: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
inputSchema?: any;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* ModelScope MCP Client for SSE connections
|
|
11
|
+
*/
|
|
12
|
+
declare class ModelScopeMCPClient implements IMCPClient {
|
|
13
|
+
private name;
|
|
14
|
+
private config;
|
|
15
|
+
private client;
|
|
16
|
+
private transport;
|
|
17
|
+
initialized: boolean;
|
|
18
|
+
tools: Tool[];
|
|
19
|
+
originalTools: Tool[];
|
|
20
|
+
constructor(name: string, config: SSEMCPServerConfig);
|
|
21
|
+
/**
|
|
22
|
+
* 生成带前缀的工具名称
|
|
23
|
+
*/
|
|
24
|
+
private generatePrefixedToolName;
|
|
25
|
+
/**
|
|
26
|
+
* 根据前缀工具名称获取原始工具名称
|
|
27
|
+
*/
|
|
28
|
+
getOriginalToolName(prefixedToolName: string): string | null;
|
|
29
|
+
start(): Promise<void>;
|
|
30
|
+
refreshTools(): Promise<void>;
|
|
31
|
+
callTool(prefixedName: string, arguments_: any): Promise<any>;
|
|
32
|
+
stop(): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export { ModelScopeMCPClient };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var y=Object.defineProperty;var g=(r,t)=>y(r,"name",{value:t,configurable:!0});import{Client as O}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as U}from"@modelcontextprotocol/sdk/client/sse.js";import{EventSource as z}from"eventsource";import{copyFileSync as M,existsSync as m,readFileSync as P,writeFileSync as I}from"fs";import{dirname as T,resolve as d}from"path";import{fileURLToPath as $}from"url";var x=T($(import.meta.url)),h={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},C=class r{static{g(this,"ConfigManager")}static instance;defaultConfigPath;config=null;constructor(){this.defaultConfigPath=d(x,"xiaozhi.config.default.json")}getConfigFilePath(){let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return d(t,"xiaozhi.config.json")}static getInstance(){return r.instance||(r.instance=new r),r.instance}configExists(){let t=this.getConfigFilePath();return m(t)}initConfig(){if(!m(this.defaultConfigPath))throw new Error("\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.default.json \u4E0D\u5B58\u5728");if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let t=this.getConfigFilePath();M(this.defaultConfigPath,t),this.config=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let t=this.getConfigFilePath(),o=P(t,"utf8"),e=JSON.parse(o);return this.validateConfig(e),e}catch(t){throw t instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${t.message}`):t}}validateConfig(t){if(!t||typeof t!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let o=t;if(o.mcpEndpoint===void 0||o.mcpEndpoint===null)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(typeof o.mcpEndpoint!="string")if(Array.isArray(o.mcpEndpoint)){if(o.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let e of o.mcpEndpoint)if(typeof e!="string"||e.trim()==="")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u5B57\u7B26\u4E32\u6570\u7EC4");if(!o.mcpServers||typeof o.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[e,n]of Object.entries(o.mcpServers)){if(!n||typeof n!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${e} \u65E0\u6548`);let i=n;if(i.type==="sse"){if(!i.url||typeof i.url!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${e}.url \u65E0\u6548`)}else{if(!i.command||typeof i.command!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${e}.command \u65E0\u6548`);if(!Array.isArray(i.args))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${e}.args \u5FC5\u987B\u662F\u6570\u7EC4`);if(i.env&&typeof i.env!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${e}.env \u5FC5\u987B\u662F\u5BF9\u8C61`)}}}getConfig(){return this.config||(this.config=this.loadConfig()),JSON.parse(JSON.stringify(this.config))}getMcpEndpoint(){let t=this.getConfig();return Array.isArray(t.mcpEndpoint)?t.mcpEndpoint[0]||"":t.mcpEndpoint}getMcpEndpoints(){let t=this.getConfig();return Array.isArray(t.mcpEndpoint)?[...t.mcpEndpoint]:t.mcpEndpoint?[t.mcpEndpoint]:[]}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(t){return this.getMcpServerConfig()[t]?.tools||{}}isToolEnabled(t,o){return this.getServerToolsConfig(t)[o]?.enable!==!1}updateMcpEndpoint(t){if(Array.isArray(t)){if(t.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let n of t)if(!n||typeof n!="string")throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else if(!t||typeof t!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let e={...this.getConfig(),mcpEndpoint:t};this.saveConfig(e)}addMcpEndpoint(t){if(!t||typeof t!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let o=this.getConfig(),e=this.getMcpEndpoints();if(e.includes(t))throw new Error(`MCP \u7AEF\u70B9 ${t} \u5DF2\u5B58\u5728`);let n=[...e,t],i={...o,mcpEndpoint:n};this.saveConfig(i)}removeMcpEndpoint(t){if(!t||typeof t!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let o=this.getConfig(),e=this.getMcpEndpoints();if(e.indexOf(t)===-1)throw new Error(`MCP \u7AEF\u70B9 ${t} \u4E0D\u5B58\u5728`);if(e.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let i=e.filter(a=>a!==t),s={...o,mcpEndpoint:i};this.saveConfig(s)}updateMcpServer(t,o){if(!t||typeof t!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if("type"in o&&o.type==="sse"){if(!o.url||typeof o.url!="string")throw new Error("SSE \u670D\u52A1\u914D\u7F6E\u7684 url \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else{let i=o;if(!i.command||typeof i.command!="string")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 command \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(i.args))throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4");if(i.env&&typeof i.env!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61")}let e=this.getConfig(),n={...e,mcpServers:{...e.mcpServers,[t]:o}};this.saveConfig(n)}removeMcpServer(t){if(!t||typeof t!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let o=this.getConfig();if(!o.mcpServers[t])throw new Error(`\u670D\u52A1 ${t} \u4E0D\u5B58\u5728`);let e={...o.mcpServers};delete e[t];let n={...o,mcpServers:e};this.saveConfig(n)}updateServerToolsConfig(t,o){let n={...this.getConfig()};n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[t]={tools:o},this.saveConfig(n)}setToolEnabled(t,o,e,n){let s={...this.getConfig()};s.mcpServerConfig||(s.mcpServerConfig={}),s.mcpServerConfig[t]||(s.mcpServerConfig[t]={tools:{}}),s.mcpServerConfig[t].tools[o]={enable:e,...n&&{description:n}},this.saveConfig(s)}saveConfig(t){try{this.validateConfig(t);let o=this.getConfigFilePath(),e=JSON.stringify(t,null,2);I(o,e,"utf8"),this.config=t}catch(o){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`)}}reloadConfig(){this.config=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let o=this.getConfig().connection||{};return{heartbeatInterval:o.heartbeatInterval??h.heartbeatInterval,heartbeatTimeout:o.heartbeatTimeout??h.heartbeatTimeout,reconnectInterval:o.reconnectInterval??h.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(t){let o=this.getConfig(),n={...o.connection||{},...t},i={...o,connection:n};this.saveConfig(i)}setHeartbeatInterval(t){if(t<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:t})}setHeartbeatTimeout(t){if(t<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:t})}setReconnectInterval(t){if(t<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:t})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(t){let o=this.getConfig(),n={...o.modelscope||{},...t},i={...o,modelscope:n};this.saveConfig(i)}setModelScopeApiKey(t){if(!t||typeof t!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:t})}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}updateWebUIConfig(t){let o=this.getConfig(),n={...o.webUI||{},...t},i={...o,webUI:n};this.saveConfig(i)}setWebUIPort(t){if(!Number.isInteger(t)||t<=0||t>65535)throw new Error("\u7AEF\u53E3\u53F7\u5FC5\u987B\u662F 1-65535 \u4E4B\u95F4\u7684\u6574\u6570");this.updateWebUIConfig({port:t})}},S=C.getInstance();import p from"fs";import R from"path";import f from"chalk";import{createConsola as A}from"consola";function F(r){let t=r.getFullYear(),o=String(r.getMonth()+1).padStart(2,"0"),e=String(r.getDate()).padStart(2,"0"),n=String(r.getHours()).padStart(2,"0"),i=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${t}-${o}-${e} ${n}:${i}:${s}`}g(F,"formatDateTime");var u=class{static{g(this,"Logger")}logFilePath=null;writeStream=null;consolaInstance;isDaemonMode;constructor(){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.consolaInstance=A({formatOptions:{date:!1,colors:!0,compact:!0},fancy:!1});let t=this.isDaemonMode;this.consolaInstance.setReporters([{log:g(o=>{let e={info:"INFO",success:"SUCCESS",warn:"WARN",error:"ERROR",debug:"DEBUG",log:"LOG"},n={info:f.blue,success:f.green,warn:f.yellow,error:f.red,debug:f.gray,log:g(l=>l,"log")},i=e[o.type]||o.type.toUpperCase(),s=n[o.type]||(l=>l),a=F(new Date),b=s(`[${i}]`),E=`[${a}] ${b} ${o.args.join(" ")}`;if(!t)try{console.error(E)}catch(l){if(l instanceof Error&&l.message?.includes("EPIPE"))return;throw l}},"log")}])}initLogFile(t){this.logFilePath=R.join(t,"xiaozhi.log"),p.existsSync(this.logFilePath)||p.writeFileSync(this.logFilePath,""),this.writeStream=p.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"})}logToFile(t,o,...e){if(this.writeStream){let i=`[${new Date().toISOString()}] [${t.toUpperCase()}] ${o}`,s=e.length>0?`${i} ${e.map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" ")}`:i;this.writeStream.write(`${s}
|
|
2
|
+
`)}}enableFileLogging(t){t&&!this.writeStream&&this.logFilePath?this.writeStream=p.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"}):!t&&this.writeStream&&(this.writeStream.end(),this.writeStream=null)}info(t,...o){this.consolaInstance.info(t,...o),this.logToFile("info",t,...o)}success(t,...o){this.consolaInstance.success(t,...o),this.logToFile("success",t,...o)}warn(t,...o){this.consolaInstance.warn(t,...o),this.logToFile("warn",t,...o)}error(t,...o){this.consolaInstance.error(t,...o),this.logToFile("error",t,...o)}debug(t,...o){this.consolaInstance.debug(t,...o),this.logToFile("debug",t,...o)}log(t,...o){this.consolaInstance.log(t,...o),this.logToFile("log",t,...o)}withTag(t){return this}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null)}},w=new u;global.EventSource=z;var c=w.withTag("ModelScopeMCP"),v=class{static{g(this,"ModelScopeMCPClient")}name;config;client=null;transport=null;initialized=!1;tools=[];originalTools=[];constructor(t,o){this.name=t,this.config=o}generatePrefixedToolName(t){return`${this.name.replace(/-/g,"_")}_xzcli_${t}`}getOriginalToolName(t){let e=`${this.name.replace(/-/g,"_")}_xzcli_`;return t.startsWith(e)?t.substring(e.length):null}async start(){c.info(`\u6B63\u5728\u542F\u52A8 ModelScope MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{let t=S.getModelScopeApiKey();if(!t||t==="")throw new Error("\u672A\u8BBE\u7F6E ModelScope API Key\u3002\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey \u6216\u8BBE\u7F6E MODELSCOPE_API_TOKEN \u73AF\u5883\u53D8\u91CF\u3002");let o={eventSourceInit:{fetch:g(async(e,n)=>{let i={...n?.headers,Authorization:`Bearer ${t}`};return fetch(e,{...n,headers:i})},"fetch")},requestInit:{headers:{Authorization:`Bearer ${t}`}}};this.transport=new U(new URL(this.config.url),o),this.client=new O({name:"xiaozhi-modelscope-client",version:"1.0.0"},{capabilities:{}}),c.info(`\u6B63\u5728\u8FDE\u63A5\u5230 ${this.config.url}`),await this.client.connect(this.transport),c.info(`\u6210\u529F\u8FDE\u63A5\u5230 ModelScope MCP \u670D\u52A1\u5668\uFF1A${this.name}`),await this.refreshTools(),this.initialized=!0,c.info(`${this.name} ModelScope \u5BA2\u6237\u7AEF\u5DF2\u5C31\u7EEA\uFF0C\u5171 ${this.tools.length} \u4E2A\u5DE5\u5177`)}catch(t){throw c.error(`\u542F\u52A8 ModelScope MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${t instanceof Error?t.message:String(t)}`),t}}async refreshTools(){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let t=await this.client.listTools();this.originalTools=t.tools||[],this.tools=this.originalTools.map(o=>({...o,name:this.generatePrefixedToolName(o.name)})),c.info(`${this.name} \u52A0\u8F7D\u4E86 ${this.originalTools.length} \u4E2A\u5DE5\u5177\uFF1A${this.originalTools.map(o=>o.name).join(", ")}`)}catch(t){c.error(`\u4ECE ${this.name} \u83B7\u53D6\u5DE5\u5177\u5931\u8D25\uFF1A${t instanceof Error?t.message:String(t)}`),this.tools=[],this.originalTools=[]}}async callTool(t,o){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let e=this.getOriginalToolName(t);if(!e)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${t}`);c.info(`\u8C03\u7528 ModelScope \u5DE5\u5177 ${e}\uFF0C\u53C2\u6570\uFF1A${JSON.stringify(o)}`);let n=await this.client.callTool({name:e,arguments:o});return c.info(`ModelScope \u5DE5\u5177\u8C03\u7528\u8FD4\u56DE: ${JSON.stringify(n).substring(0,500)}...`),n}catch(e){throw c.error(`\u5728 ${this.name} \u4E0A\u8C03\u7528\u5DE5\u5177 ${t} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async stop(){if(this.client){c.info(`\u6B63\u5728\u505C\u6B62 ${this.name} ModelScope \u5BA2\u6237\u7AEF`);try{await this.client.close()}catch(t){c.error(`\u5173\u95ED\u5BA2\u6237\u7AEF\u65F6\u51FA\u9519\uFF1A${t instanceof Error?t.message:String(t)}`)}this.client=null,this.transport=null}this.initialized=!1}};export{v as ModelScopeMCPClient};
|
|
3
|
+
//# sourceMappingURL=modelScopeMCPClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/modelScopeMCPClient.ts","../src/configManager.ts","../src/logger.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { EventSource } from \"eventsource\";\nimport { type SSEMCPServerConfig, configManager } from \"./configManager\";\nimport { logger as globalLogger } from \"./logger\";\nimport type { IMCPClient } from \"./mcpServerProxy\";\n\n// 全局 polyfill EventSource\n(global as any).EventSource = EventSource;\n\n// 为 ModelScope MCP 创建带标签的 logger\nconst logger = globalLogger.withTag(\"ModelScopeMCP\");\n\ninterface Tool {\n name: string;\n description?: string;\n inputSchema?: any;\n}\n\n/**\n * ModelScope MCP Client for SSE connections\n */\nexport class ModelScopeMCPClient implements IMCPClient {\n private name: string;\n private config: SSEMCPServerConfig;\n private client: Client | null = null;\n private transport: SSEClientTransport | null = null;\n public initialized = false;\n public tools: Tool[] = [];\n public originalTools: Tool[] = [];\n\n constructor(name: string, config: SSEMCPServerConfig) {\n this.name = name;\n this.config = config;\n }\n\n /**\n * 生成带前缀的工具名称\n */\n private generatePrefixedToolName(originalToolName: string): string {\n const normalizedServerName = this.name.replace(/-/g, \"_\");\n return `${normalizedServerName}_xzcli_${originalToolName}`;\n }\n\n /**\n * 根据前缀工具名称获取原始工具名称\n */\n getOriginalToolName(prefixedToolName: string): string | null {\n const normalizedServerName = this.name.replace(/-/g, \"_\");\n const prefix = `${normalizedServerName}_xzcli_`;\n\n if (prefixedToolName.startsWith(prefix)) {\n return prefixedToolName.substring(prefix.length);\n }\n\n return null;\n }\n\n async start() {\n logger.info(`正在启动 ModelScope MCP 客户端:${this.name}`);\n\n try {\n // 从配置或环境变量获取 API Token\n const token = configManager.getModelScopeApiKey();\n if (!token || token === \"\") {\n throw new Error(\n \"未设置 ModelScope API Key。请在配置文件中设置 modelscope.apiKey 或设置 MODELSCOPE_API_TOKEN 环境变量。\"\n );\n }\n\n // 创建 SSE 传输层\n const sseOptions = {\n eventSourceInit: {\n fetch: async (url: string | URL | Request, init?: RequestInit) => {\n // 添加认证头\n const headers = {\n ...init?.headers,\n Authorization: `Bearer ${token}`,\n };\n\n return fetch(url, { ...init, headers });\n },\n },\n requestInit: {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n };\n\n this.transport = new SSEClientTransport(\n new URL(this.config.url),\n sseOptions\n );\n\n // 创建 MCP 客户端\n this.client = new Client(\n {\n name: \"xiaozhi-modelscope-client\",\n version: \"1.0.0\",\n },\n {\n capabilities: {},\n }\n );\n\n // 连接到服务器\n logger.info(`正在连接到 ${this.config.url}`);\n await this.client.connect(this.transport);\n logger.info(`成功连接到 ModelScope MCP 服务器:${this.name}`);\n\n // 获取工具列表\n await this.refreshTools();\n\n this.initialized = true;\n logger.info(\n `${this.name} ModelScope 客户端已就绪,共 ${this.tools.length} 个工具`\n );\n } catch (error) {\n logger.error(\n `启动 ModelScope MCP 客户端 ${this.name} 失败:${\n error instanceof Error ? error.message : String(error)\n }`\n );\n throw error;\n }\n }\n\n async refreshTools(): Promise<void> {\n try {\n if (!this.client) {\n throw new Error(\"客户端未初始化\");\n }\n\n const result = await this.client.listTools();\n this.originalTools = result.tools || [];\n\n // 为每个工具生成带前缀的名称\n this.tools = this.originalTools.map((tool) => ({\n ...tool,\n name: this.generatePrefixedToolName(tool.name),\n }));\n\n logger.info(\n `${this.name} 加载了 ${this.originalTools.length} 个工具:${this.originalTools\n .map((t) => t.name)\n .join(\", \")}`\n );\n } catch (error) {\n logger.error(\n `从 ${this.name} 获取工具失败:${\n error instanceof Error ? error.message : String(error)\n }`\n );\n this.tools = [];\n this.originalTools = [];\n }\n }\n\n async callTool(prefixedName: string, arguments_: any): Promise<any> {\n try {\n if (!this.client) {\n throw new Error(\"客户端未初始化\");\n }\n\n // 将前缀名称转换回原始名称\n const originalName = this.getOriginalToolName(prefixedName);\n if (!originalName) {\n throw new Error(`无效的工具名称格式:${prefixedName}`);\n }\n\n logger.info(\n `调用 ModelScope 工具 ${originalName},参数:${JSON.stringify(\n arguments_\n )}`\n );\n\n const result = await this.client.callTool({\n name: originalName,\n arguments: arguments_,\n });\n\n logger.info(\n `ModelScope 工具调用返回: ${JSON.stringify(result).substring(0, 500)}...`\n );\n\n return result;\n } catch (error) {\n logger.error(\n `在 ${this.name} 上调用工具 ${prefixedName} 失败:${\n error instanceof Error ? error.message : String(error)\n }`\n );\n throw error;\n }\n }\n\n async stop(): Promise<void> {\n if (this.client) {\n logger.info(`正在停止 ${this.name} ModelScope 客户端`);\n try {\n await this.client.close();\n } catch (error) {\n logger.error(\n `关闭客户端时出错:${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n this.client = null;\n this.transport = null;\n }\n this.initialized = false;\n }\n}\n","import { copyFileSync, existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// 在 ESM 中,需要从 import.meta.url 获取当前文件目录\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// 默认连接配置\nconst DEFAULT_CONNECTION_CONFIG: Required<ConnectionConfig> = {\n heartbeatInterval: 30000, // 30秒心跳间隔\n heartbeatTimeout: 10000, // 10秒心跳超时\n reconnectInterval: 5000, // 5秒重连间隔\n};\n\n// 配置文件接口定义\n// 本地 MCP 服务配置\nexport interface LocalMCPServerConfig {\n command: string;\n args: string[];\n env?: Record<string, string>;\n}\n\n// ModelScope SSE MCP 服务配置\nexport interface SSEMCPServerConfig {\n type: \"sse\";\n url: string;\n}\n\n// 统一的 MCP 服务配置\nexport type MCPServerConfig = LocalMCPServerConfig | SSEMCPServerConfig;\n\nexport interface MCPToolConfig {\n description?: string;\n enable: boolean;\n}\n\nexport interface MCPServerToolsConfig {\n tools: Record<string, MCPToolConfig>;\n}\n\nexport interface ConnectionConfig {\n heartbeatInterval?: number; // 心跳检测间隔(毫秒),默认30000\n heartbeatTimeout?: number; // 心跳超时时间(毫秒),默认10000\n reconnectInterval?: number; // 重连间隔(毫秒),默认5000\n}\n\nexport interface ModelScopeConfig {\n apiKey?: string; // ModelScope API 密钥\n}\n\nexport interface WebUIConfig {\n port?: number; // Web UI 端口号,默认 9999\n}\n\nexport interface AppConfig {\n mcpEndpoint: string | string[];\n mcpServers: Record<string, MCPServerConfig>;\n mcpServerConfig?: Record<string, MCPServerToolsConfig>;\n connection?: ConnectionConfig; // 连接配置(可选,用于向后兼容)\n modelscope?: ModelScopeConfig; // ModelScope 配置(可选)\n webUI?: WebUIConfig; // Web UI 配置(可选)\n}\n\n/**\n * 配置管理类\n * 负责管理应用配置,提供只读访问和安全的配置更新功能\n */\nexport class ConfigManager {\n private static instance: ConfigManager;\n private defaultConfigPath: string;\n private config: AppConfig | null = null;\n\n private constructor() {\n this.defaultConfigPath = resolve(__dirname, \"xiaozhi.config.default.json\");\n }\n\n /**\n * 获取配置文件路径(动态计算)\n */\n private getConfigFilePath(): string {\n // 配置文件路径 - 优先使用环境变量指定的目录,否则使用当前工作目录\n const configDir = process.env.XIAOZHI_CONFIG_DIR || process.cwd();\n return resolve(configDir, \"xiaozhi.config.json\");\n }\n\n /**\n * 获取配置管理器单例实例\n */\n public static getInstance(): ConfigManager {\n if (!ConfigManager.instance) {\n ConfigManager.instance = new ConfigManager();\n }\n return ConfigManager.instance;\n }\n\n /**\n * 检查配置文件是否存在\n */\n public configExists(): boolean {\n const configPath = this.getConfigFilePath();\n return existsSync(configPath);\n }\n\n /**\n * 初始化配置文件\n * 从 config.default.json 复制到 config.json\n */\n public initConfig(): void {\n if (!existsSync(this.defaultConfigPath)) {\n throw new Error(\"默认配置文件 xiaozhi.config.default.json 不存在\");\n }\n\n if (this.configExists()) {\n throw new Error(\"配置文件 xiaozhi.config.json 已存在,无需重复初始化\");\n }\n\n const configPath = this.getConfigFilePath();\n copyFileSync(this.defaultConfigPath, configPath);\n this.config = null; // 重置缓存\n }\n\n /**\n * 加载配置文件\n */\n private loadConfig(): AppConfig {\n if (!this.configExists()) {\n throw new Error(\n \"配置文件 xiaozhi.config.json 不存在,请先运行 xiaozhi init 初始化配置\"\n );\n }\n\n try {\n const configPath = this.getConfigFilePath();\n const configData = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(configData) as AppConfig;\n\n // 验证配置结构\n this.validateConfig(config);\n\n return config;\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(`配置文件格式错误: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * 验证配置文件结构\n */\n private validateConfig(config: unknown): void {\n if (!config || typeof config !== \"object\") {\n throw new Error(\"配置文件格式错误:根对象无效\");\n }\n\n const configObj = config as Record<string, unknown>;\n\n if (configObj.mcpEndpoint === undefined || configObj.mcpEndpoint === null) {\n throw new Error(\"配置文件格式错误:mcpEndpoint 字段无效\");\n }\n\n // 验证 mcpEndpoint 类型(字符串或字符串数组)\n if (typeof configObj.mcpEndpoint === \"string\") {\n // 空字符串是允许的,getMcpEndpoints 会返回空数组\n } else if (Array.isArray(configObj.mcpEndpoint)) {\n if (configObj.mcpEndpoint.length === 0) {\n throw new Error(\"配置文件格式错误:mcpEndpoint 数组不能为空\");\n }\n for (const endpoint of configObj.mcpEndpoint) {\n if (typeof endpoint !== \"string\" || endpoint.trim() === \"\") {\n throw new Error(\n \"配置文件格式错误:mcpEndpoint 数组中的每个元素必须是非空字符串\"\n );\n }\n }\n } else {\n throw new Error(\"配置文件格式错误:mcpEndpoint 必须是字符串或字符串数组\");\n }\n\n if (!configObj.mcpServers || typeof configObj.mcpServers !== \"object\") {\n throw new Error(\"配置文件格式错误:mcpServers 字段无效\");\n }\n\n // 验证每个 MCP 服务配置\n for (const [serverName, serverConfig] of Object.entries(\n configObj.mcpServers as Record<string, unknown>\n )) {\n if (!serverConfig || typeof serverConfig !== \"object\") {\n throw new Error(`配置文件格式错误:mcpServers.${serverName} 无效`);\n }\n\n const sc = serverConfig as Record<string, unknown>;\n\n // 检查是否是 SSE 类型\n if (sc.type === \"sse\") {\n // SSE 类型的验证\n if (!sc.url || typeof sc.url !== \"string\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.url 无效`\n );\n }\n } else {\n // 本地类型的验证\n if (!sc.command || typeof sc.command !== \"string\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.command 无效`\n );\n }\n\n if (!Array.isArray(sc.args)) {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.args 必须是数组`\n );\n }\n\n if (sc.env && typeof sc.env !== \"object\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.env 必须是对象`\n );\n }\n }\n }\n }\n\n /**\n * 获取配置(只读)\n */\n public getConfig(): Readonly<AppConfig> {\n if (!this.config) {\n this.config = this.loadConfig();\n }\n\n // 返回深度只读副本\n return JSON.parse(JSON.stringify(this.config));\n }\n\n /**\n * 获取 MCP 端点(向后兼容)\n * @deprecated 使用 getMcpEndpoints() 获取所有端点\n */\n public getMcpEndpoint(): string {\n const config = this.getConfig();\n if (Array.isArray(config.mcpEndpoint)) {\n return config.mcpEndpoint[0] || \"\";\n }\n return config.mcpEndpoint;\n }\n\n /**\n * 获取所有 MCP 端点\n */\n public getMcpEndpoints(): string[] {\n const config = this.getConfig();\n if (Array.isArray(config.mcpEndpoint)) {\n return [...config.mcpEndpoint];\n }\n return config.mcpEndpoint ? [config.mcpEndpoint] : [];\n }\n\n /**\n * 获取 MCP 服务配置\n */\n public getMcpServers(): Readonly<Record<string, MCPServerConfig>> {\n const config = this.getConfig();\n return config.mcpServers;\n }\n\n /**\n * 获取 MCP 服务工具配置\n */\n public getMcpServerConfig(): Readonly<Record<string, MCPServerToolsConfig>> {\n const config = this.getConfig();\n return config.mcpServerConfig || {};\n }\n\n /**\n * 获取指定服务的工具配置\n */\n public getServerToolsConfig(\n serverName: string\n ): Readonly<Record<string, MCPToolConfig>> {\n const serverConfig = this.getMcpServerConfig();\n return serverConfig[serverName]?.tools || {};\n }\n\n /**\n * 检查工具是否启用\n */\n public isToolEnabled(serverName: string, toolName: string): boolean {\n const toolsConfig = this.getServerToolsConfig(serverName);\n const toolConfig = toolsConfig[toolName];\n return toolConfig?.enable !== false; // 默认启用\n }\n\n /**\n * 更新 MCP 端点(支持字符串或数组)\n */\n public updateMcpEndpoint(endpoint: string | string[]): void {\n if (Array.isArray(endpoint)) {\n if (endpoint.length === 0) {\n throw new Error(\"MCP 端点数组不能为空\");\n }\n for (const ep of endpoint) {\n if (!ep || typeof ep !== \"string\") {\n throw new Error(\"MCP 端点数组中的每个元素必须是非空字符串\");\n }\n }\n } else {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n }\n\n const config = this.getConfig();\n const newConfig = { ...config, mcpEndpoint: endpoint };\n this.saveConfig(newConfig);\n }\n\n /**\n * 添加 MCP 端点\n */\n public addMcpEndpoint(endpoint: string): void {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n\n const config = this.getConfig();\n const currentEndpoints = this.getMcpEndpoints();\n\n // 检查是否已存在\n if (currentEndpoints.includes(endpoint)) {\n throw new Error(`MCP 端点 ${endpoint} 已存在`);\n }\n\n const newEndpoints = [...currentEndpoints, endpoint];\n const newConfig = { ...config, mcpEndpoint: newEndpoints };\n this.saveConfig(newConfig);\n }\n\n /**\n * 移除 MCP 端点\n */\n public removeMcpEndpoint(endpoint: string): void {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n\n const config = this.getConfig();\n const currentEndpoints = this.getMcpEndpoints();\n\n // 检查是否存在\n const index = currentEndpoints.indexOf(endpoint);\n if (index === -1) {\n throw new Error(`MCP 端点 ${endpoint} 不存在`);\n }\n\n // 不允许删除最后一个端点\n if (currentEndpoints.length === 1) {\n throw new Error(\"不能删除最后一个 MCP 端点\");\n }\n\n const newEndpoints = currentEndpoints.filter((ep) => ep !== endpoint);\n const newConfig = { ...config, mcpEndpoint: newEndpoints };\n this.saveConfig(newConfig);\n }\n\n /**\n * 更新 MCP 服务配置\n */\n public updateMcpServer(\n serverName: string,\n serverConfig: MCPServerConfig\n ): void {\n if (!serverName || typeof serverName !== \"string\") {\n throw new Error(\"服务名称必须是非空字符串\");\n }\n\n // 验证服务配置\n if (\"type\" in serverConfig && serverConfig.type === \"sse\") {\n // SSE 类型的验证\n if (!serverConfig.url || typeof serverConfig.url !== \"string\") {\n throw new Error(\"SSE 服务配置的 url 字段必须是非空字符串\");\n }\n } else {\n // 本地类型的验证\n const localConfig = serverConfig as LocalMCPServerConfig;\n if (!localConfig.command || typeof localConfig.command !== \"string\") {\n throw new Error(\"服务配置的 command 字段必须是非空字符串\");\n }\n\n if (!Array.isArray(localConfig.args)) {\n throw new Error(\"服务配置的 args 字段必须是数组\");\n }\n\n if (localConfig.env && typeof localConfig.env !== \"object\") {\n throw new Error(\"服务配置的 env 字段必须是对象\");\n }\n }\n\n const config = this.getConfig();\n const newConfig = {\n ...config,\n mcpServers: {\n ...config.mcpServers,\n [serverName]: serverConfig,\n },\n };\n this.saveConfig(newConfig);\n }\n\n /**\n * 删除 MCP 服务配置\n */\n public removeMcpServer(serverName: string): void {\n if (!serverName || typeof serverName !== \"string\") {\n throw new Error(\"服务名称必须是非空字符串\");\n }\n\n const config = this.getConfig();\n if (!config.mcpServers[serverName]) {\n throw new Error(`服务 ${serverName} 不存在`);\n }\n\n const newMcpServers = { ...config.mcpServers };\n delete newMcpServers[serverName];\n\n const newConfig = {\n ...config,\n mcpServers: newMcpServers,\n };\n this.saveConfig(newConfig);\n }\n\n /**\n * 更新服务工具配置\n */\n public updateServerToolsConfig(\n serverName: string,\n toolsConfig: Record<string, MCPToolConfig>\n ): void {\n const config = this.getConfig();\n const newConfig = { ...config };\n\n // 确保 mcpServerConfig 存在\n if (!newConfig.mcpServerConfig) {\n newConfig.mcpServerConfig = {};\n }\n\n // 更新指定服务的工具配置\n newConfig.mcpServerConfig[serverName] = {\n tools: toolsConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置工具启用状态\n */\n public setToolEnabled(\n serverName: string,\n toolName: string,\n enabled: boolean,\n description?: string\n ): void {\n const config = this.getConfig();\n const newConfig = { ...config };\n\n // 确保 mcpServerConfig 存在\n if (!newConfig.mcpServerConfig) {\n newConfig.mcpServerConfig = {};\n }\n\n // 确保服务配置存在\n if (!newConfig.mcpServerConfig[serverName]) {\n newConfig.mcpServerConfig[serverName] = { tools: {} };\n }\n\n // 更新工具配置\n newConfig.mcpServerConfig[serverName].tools[toolName] = {\n enable: enabled,\n ...(description && { description }),\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 保存配置到文件\n */\n private saveConfig(config: AppConfig): void {\n try {\n // 验证配置\n this.validateConfig(config);\n\n // 格式化 JSON 并保存\n const configPath = this.getConfigFilePath();\n const configJson = JSON.stringify(config, null, 2);\n writeFileSync(configPath, configJson, \"utf8\");\n\n // 更新缓存\n this.config = config;\n } catch (error) {\n throw new Error(\n `保存配置失败: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * 重新加载配置(清除缓存)\n */\n public reloadConfig(): void {\n this.config = null;\n }\n\n /**\n * 获取配置文件路径\n */\n public getConfigPath(): string {\n return this.getConfigFilePath();\n }\n\n /**\n * 获取默认配置文件路径\n */\n public getDefaultConfigPath(): string {\n return this.defaultConfigPath;\n }\n\n /**\n * 获取连接配置(包含默认值)\n */\n public getConnectionConfig(): Required<ConnectionConfig> {\n const config = this.getConfig();\n const connectionConfig = config.connection || {};\n\n return {\n heartbeatInterval:\n connectionConfig.heartbeatInterval ??\n DEFAULT_CONNECTION_CONFIG.heartbeatInterval,\n heartbeatTimeout:\n connectionConfig.heartbeatTimeout ??\n DEFAULT_CONNECTION_CONFIG.heartbeatTimeout,\n reconnectInterval:\n connectionConfig.reconnectInterval ??\n DEFAULT_CONNECTION_CONFIG.reconnectInterval,\n };\n }\n\n /**\n * 获取心跳检测间隔(毫秒)\n */\n public getHeartbeatInterval(): number {\n return this.getConnectionConfig().heartbeatInterval;\n }\n\n /**\n * 获取心跳超时时间(毫秒)\n */\n public getHeartbeatTimeout(): number {\n return this.getConnectionConfig().heartbeatTimeout;\n }\n\n /**\n * 获取重连间隔(毫秒)\n */\n public getReconnectInterval(): number {\n return this.getConnectionConfig().reconnectInterval;\n }\n\n /**\n * 更新连接配置\n */\n public updateConnectionConfig(\n connectionConfig: Partial<ConnectionConfig>\n ): void {\n const config = this.getConfig();\n const currentConnectionConfig = config.connection || {};\n\n const newConnectionConfig = {\n ...currentConnectionConfig,\n ...connectionConfig,\n };\n\n const newConfig = {\n ...config,\n connection: newConnectionConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置心跳检测间隔\n */\n public setHeartbeatInterval(interval: number): void {\n if (interval <= 0) {\n throw new Error(\"心跳检测间隔必须大于0\");\n }\n this.updateConnectionConfig({ heartbeatInterval: interval });\n }\n\n /**\n * 设置心跳超时时间\n */\n public setHeartbeatTimeout(timeout: number): void {\n if (timeout <= 0) {\n throw new Error(\"心跳超时时间必须大于0\");\n }\n this.updateConnectionConfig({ heartbeatTimeout: timeout });\n }\n\n /**\n * 设置重连间隔\n */\n public setReconnectInterval(interval: number): void {\n if (interval <= 0) {\n throw new Error(\"重连间隔必须大于0\");\n }\n this.updateConnectionConfig({ reconnectInterval: interval });\n }\n\n /**\n * 获取 ModelScope 配置\n */\n public getModelScopeConfig(): Readonly<ModelScopeConfig> {\n const config = this.getConfig();\n return config.modelscope || {};\n }\n\n /**\n * 获取 ModelScope API Key\n * 优先从配置文件读取,其次从环境变量读取\n */\n public getModelScopeApiKey(): string | undefined {\n const modelScopeConfig = this.getModelScopeConfig();\n return modelScopeConfig.apiKey || process.env.MODELSCOPE_API_TOKEN;\n }\n\n /**\n * 更新 ModelScope 配置\n */\n public updateModelScopeConfig(\n modelScopeConfig: Partial<ModelScopeConfig>\n ): void {\n const config = this.getConfig();\n const currentModelScopeConfig = config.modelscope || {};\n\n const newModelScopeConfig = {\n ...currentModelScopeConfig,\n ...modelScopeConfig,\n };\n\n const newConfig = {\n ...config,\n modelscope: newModelScopeConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置 ModelScope API Key\n */\n public setModelScopeApiKey(apiKey: string): void {\n if (!apiKey || typeof apiKey !== \"string\") {\n throw new Error(\"API Key 必须是非空字符串\");\n }\n this.updateModelScopeConfig({ apiKey });\n }\n\n /**\n * 获取 Web UI 配置\n */\n public getWebUIConfig(): Readonly<WebUIConfig> {\n const config = this.getConfig();\n return config.webUI || {};\n }\n\n /**\n * 获取 Web UI 端口号\n */\n public getWebUIPort(): number {\n const webUIConfig = this.getWebUIConfig();\n return webUIConfig.port ?? 9999; // 默认端口 9999\n }\n\n /**\n * 更新 Web UI 配置\n */\n public updateWebUIConfig(webUIConfig: Partial<WebUIConfig>): void {\n const config = this.getConfig();\n const currentWebUIConfig = config.webUI || {};\n\n const newWebUIConfig = {\n ...currentWebUIConfig,\n ...webUIConfig,\n };\n\n const newConfig = {\n ...config,\n webUI: newWebUIConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置 Web UI 端口号\n */\n public setWebUIPort(port: number): void {\n if (!Number.isInteger(port) || port <= 0 || port > 65535) {\n throw new Error(\"端口号必须是 1-65535 之间的整数\");\n }\n this.updateWebUIConfig({ port });\n }\n}\n\n// 导出单例实例\nexport const configManager = ConfigManager.getInstance();\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport chalk from \"chalk\";\nimport { type consola, createConsola } from \"consola\";\n\nfunction formatDateTime(date: Date) {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n const day = String(date.getDate()).padStart(2, \"0\");\n const hours = String(date.getHours()).padStart(2, \"0\");\n const minutes = String(date.getMinutes()).padStart(2, \"0\");\n const seconds = String(date.getSeconds()).padStart(2, \"0\");\n\n return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;\n}\n\nexport class Logger {\n private logFilePath: string | null = null;\n private writeStream: fs.WriteStream | null = null;\n private consolaInstance: typeof consola;\n private isDaemonMode: boolean;\n\n constructor() {\n // 检查是否为守护进程模式\n this.isDaemonMode = process.env.XIAOZHI_DAEMON === \"true\";\n // 创建自定义的 consola 实例,禁用图标并自定义格式\n this.consolaInstance = createConsola({\n formatOptions: {\n date: false,\n colors: true,\n compact: true,\n },\n fancy: false,\n });\n\n // 保存对当前实例的引用,以便在闭包中访问\n const isDaemonMode = this.isDaemonMode;\n\n // 自定义格式化器\n this.consolaInstance.setReporters([\n {\n log: (logObj) => {\n const levelMap: Record<string, string> = {\n info: \"INFO\",\n success: \"SUCCESS\",\n warn: \"WARN\",\n error: \"ERROR\",\n debug: \"DEBUG\",\n log: \"LOG\",\n };\n\n const colorMap: Record<string, (text: string) => string> = {\n info: chalk.blue,\n success: chalk.green,\n warn: chalk.yellow,\n error: chalk.red,\n debug: chalk.gray,\n log: (text: string) => text,\n };\n\n const level = levelMap[logObj.type] || logObj.type.toUpperCase();\n const colorFn = colorMap[logObj.type] || ((text: string) => text);\n const timestamp = formatDateTime(new Date());\n\n // 为级别添加颜色\n const coloredLevel = colorFn(`[${level}]`);\n const message = `[${timestamp}] ${coloredLevel} ${logObj.args.join(\n \" \"\n )}`;\n\n // 守护进程模式下不输出到控制台,只写入文件\n if (!isDaemonMode) {\n // 输出到 stderr(与原来保持一致)\n try {\n console.error(message);\n } catch (error) {\n // 忽略 EPIPE 错误\n if (error instanceof Error && error.message?.includes(\"EPIPE\")) {\n return;\n }\n throw error;\n }\n }\n },\n },\n ]);\n }\n\n /**\n * 初始化日志文件\n * @param projectDir 项目目录\n */\n initLogFile(projectDir: string): void {\n this.logFilePath = path.join(projectDir, \"xiaozhi.log\");\n\n // 确保日志文件存在\n if (!fs.existsSync(this.logFilePath)) {\n fs.writeFileSync(this.logFilePath, \"\");\n }\n\n // 创建写入流,追加模式\n this.writeStream = fs.createWriteStream(this.logFilePath, {\n flags: \"a\",\n encoding: \"utf8\",\n });\n }\n\n /**\n * 记录日志到文件\n * @param level 日志级别\n * @param message 日志消息\n * @param args 额外参数\n */\n private logToFile(level: string, message: string, ...args: any[]): void {\n if (this.writeStream) {\n const timestamp = new Date().toISOString();\n const formattedMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;\n const fullMessage =\n args.length > 0\n ? `${formattedMessage} ${args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \")}`\n : formattedMessage;\n\n this.writeStream.write(`${fullMessage}\\n`);\n }\n }\n\n /**\n * 设置是否启用文件日志\n * @param enable 是否启用\n */\n enableFileLogging(enable: boolean): void {\n if (enable && !this.writeStream && this.logFilePath) {\n this.writeStream = fs.createWriteStream(this.logFilePath, {\n flags: \"a\",\n encoding: \"utf8\",\n });\n } else if (!enable && this.writeStream) {\n this.writeStream.end();\n this.writeStream = null;\n }\n }\n\n /**\n * 日志方法\n */\n info(message: string, ...args: any[]): void {\n this.consolaInstance.info(message, ...args);\n this.logToFile(\"info\", message, ...args);\n }\n\n success(message: string, ...args: any[]): void {\n this.consolaInstance.success(message, ...args);\n this.logToFile(\"success\", message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.consolaInstance.warn(message, ...args);\n this.logToFile(\"warn\", message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.consolaInstance.error(message, ...args);\n this.logToFile(\"error\", message, ...args);\n }\n\n debug(message: string, ...args: any[]): void {\n this.consolaInstance.debug(message, ...args);\n this.logToFile(\"debug\", message, ...args);\n }\n\n log(message: string, ...args: any[]): void {\n this.consolaInstance.log(message, ...args);\n this.logToFile(\"log\", message, ...args);\n }\n\n /**\n * 创建一个带标签的日志实例(已废弃,直接返回原实例)\n * @param tag 标签(不再使用)\n * @deprecated 标签功能已移除\n */\n withTag(tag: string): Logger {\n // 不再添加标签,直接返回共享实例\n return this;\n }\n\n /**\n * 关闭日志文件流\n */\n close(): void {\n if (this.writeStream) {\n this.writeStream.end();\n this.writeStream = null;\n }\n }\n}\n\n// 导出单例实例\nexport const logger = new Logger();\n"],"mappings":"+EAAA,OAAS,UAAAA,MAAc,4CACvB,OAAS,sBAAAC,MAA0B,0CACnC,OAAS,eAAAC,MAAmB,cCF5B,OAAS,gBAAAC,EAAc,cAAAC,EAAY,gBAAAC,EAAc,i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F,OAASH,EAAO,CACdhB,EAAO,MACL,UAAK,KAAK,IAAI,8CACZgB,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,EACF,EACA,KAAK,MAAQ,CAAC,EACd,KAAK,cAAgB,CAAC,CACxB,CACF,CAEA,MAAM,SAASI,EAAsBC,EAA+B,CAClE,GAAI,CACF,GAAI,CAAC,KAAK,OACR,MAAM,IAAI,MAAM,4CAAS,EAI3B,IAAMC,EAAe,KAAK,oBAAoBF,CAAY,EAC1D,GAAI,CAACE,EACH,MAAM,IAAI,MAAM,+DAAaF,CAAY,EAAE,EAG7CpB,EAAO,KACL,wCAAoBsB,CAAY,2BAAO,KAAK,UAC1CD,CACF,CAAC,EACH,EAEA,IAAMJ,EAAS,MAAM,KAAK,OAAO,SAAS,CACxC,KAAMK,EACN,UAAWD,CACb,CAAC,EAED,OAAArB,EAAO,KACL,oDAAsB,KAAK,UAAUiB,CAAM,EAAE,UAAU,EAAG,GAAG,CAAC,KAChE,EAEOA,CACT,OAASD,EAAO,CACd,MAAAhB,EAAO,MACL,UAAK,KAAK,IAAI,mCAAUoB,CAAY,sBAClCJ,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,EACF,EACMA,CACR,CACF,CAEA,MAAM,MAAsB,CAC1B,GAAI,KAAK,OAAQ,CACfhB,EAAO,KAAK,4BAAQ,KAAK,IAAI,gCAAiB,EAC9C,GAAI,CACF,MAAM,KAAK,OAAO,MAAM,CAC1B,OAASgB,EAAO,CACdhB,EAAO,MACL,yDACEgB,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,EACF,CACF,CACA,KAAK,OAAS,KACd,KAAK,UAAY,IACnB,CACA,KAAK,YAAc,EACrB,CACF","names":["Client","SSEClientTransport","EventSource","copyFileSync","existsSync","readFileSync","writeFileSync","dirname","resolve","fileURLToPath","__dirname","dirname","fileURLToPath","DEFAULT_CONNECTION_CONFIG","ConfigManager","_ConfigManager","__name","resolve","configDir","configPath","existsSync","copyFileSync","configData","readFileSync","config","error","configObj","endpoint","serverName","serverConfig","sc","toolName","ep","newConfig","currentEndpoints","newEndpoints","localConfig","newMcpServers","toolsConfig","enabled","description","configJson","writeFileSync","connectionConfig","newConnectionConfig","interval","timeout","modelScopeConfig","newModelScopeConfig","apiKey","webUIConfig","newWebUIConfig","port","configManager","fs","path","chalk","createConsola","formatDateTime","date","year","month","day","hours","minutes","seconds","__name","Logger","createConsola","isDaemonMode","logObj","levelMap","colorMap","chalk","text","level","colorFn","timestamp","coloredLevel","message","error","projectDir","path","fs","args","formattedMessage","fullMessage","arg","enable","tag","logger","EventSource","logger","ModelScopeMCPClient","__name","name","config","originalToolName","prefixedToolName","prefix","token","configManager","sseOptions","url","init","headers","SSEClientTransport","Client","error","result","tool","t","prefixedName","arguments_","originalName"]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Multi-Endpoint MCP Pipe - 支持多个 MCP 接入点
|
|
4
|
+
* 管理多个 WebSocket 连接,并正确路由消息到对应的接入点
|
|
5
|
+
*/
|
|
6
|
+
declare class MultiEndpointMCPPipe {
|
|
7
|
+
private mcpScript;
|
|
8
|
+
private endpoints;
|
|
9
|
+
private shouldReconnect;
|
|
10
|
+
private shutdownResolve?;
|
|
11
|
+
private connectionConfig;
|
|
12
|
+
constructor(mcpScript: string, endpointUrls: string[]);
|
|
13
|
+
start(): Promise<void>;
|
|
14
|
+
connectToAllEndpoints(): Promise<void>;
|
|
15
|
+
connectToEndpoint(endpointUrl: string): Promise<void>;
|
|
16
|
+
scheduleReconnect(endpointUrl: string): void;
|
|
17
|
+
startMCPProcessForEndpoint(endpointUrl: string): void;
|
|
18
|
+
handleMCPMessage(endpointUrl: string, line: string): void;
|
|
19
|
+
sendToEndpoint(endpointUrl: string, message: string): void;
|
|
20
|
+
startHeartbeat(endpointUrl: string): void;
|
|
21
|
+
stopHeartbeat(endpointUrl: string): void;
|
|
22
|
+
cleanup(): void;
|
|
23
|
+
shutdown(): void;
|
|
24
|
+
private reportStatusToWebUI;
|
|
25
|
+
hasAnyConnection(): boolean;
|
|
26
|
+
}
|
|
27
|
+
declare function setupSignalHandlers(mcpPipe: MultiEndpointMCPPipe): void;
|
|
28
|
+
|
|
29
|
+
export { MultiEndpointMCPPipe, setupSignalHandlers };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var y=Object.defineProperty;var g=(s,e)=>y(s,"name",{value:e,configurable:!0});import{spawn as O}from"child_process";import a from"process";import d from"ws";import{copyFileSync as P,existsSync as v,readFileSync as M,writeFileSync as $}from"fs";import{dirname as R,resolve as S}from"path";import{fileURLToPath as A}from"url";var F=R(A(import.meta.url)),C={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},m=class s{static{g(this,"ConfigManager")}static instance;defaultConfigPath;config=null;constructor(){this.defaultConfigPath=S(F,"xiaozhi.config.default.json")}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return S(e,"xiaozhi.config.json")}static getInstance(){return s.instance||(s.instance=new s),s.instance}configExists(){let e=this.getConfigFilePath();return v(e)}initConfig(){if(!v(this.defaultConfigPath))throw new Error("\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.default.json \u4E0D\u5B58\u5728");if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let e=this.getConfigFilePath();P(this.defaultConfigPath,e),this.config=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let e=this.getConfigFilePath(),t=M(e,"utf8"),n=JSON.parse(t);return this.validateConfig(n),n}catch(e){throw e instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${e.message}`):e}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let t=e;if(t.mcpEndpoint===void 0||t.mcpEndpoint===null)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(typeof t.mcpEndpoint!="string")if(Array.isArray(t.mcpEndpoint)){if(t.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let n of t.mcpEndpoint)if(typeof n!="string"||n.trim()==="")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u5B57\u7B26\u4E32\u6570\u7EC4");if(!t.mcpServers||typeof t.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[n,o]of Object.entries(t.mcpServers)){if(!o||typeof o!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n} \u65E0\u6548`);let i=o;if(i.type==="sse"){if(!i.url||typeof i.url!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.url \u65E0\u6548`)}else{if(!i.command||typeof i.command!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.command \u65E0\u6548`);if(!Array.isArray(i.args))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.args \u5FC5\u987B\u662F\u6570\u7EC4`);if(i.env&&typeof i.env!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.env \u5FC5\u987B\u662F\u5BF9\u8C61`)}}}getConfig(){return this.config||(this.config=this.loadConfig()),JSON.parse(JSON.stringify(this.config))}getMcpEndpoint(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?e.mcpEndpoint[0]||"":e.mcpEndpoint}getMcpEndpoints(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?[...e.mcpEndpoint]:e.mcpEndpoint?[e.mcpEndpoint]:[]}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(e){return this.getMcpServerConfig()[e]?.tools||{}}isToolEnabled(e,t){return this.getServerToolsConfig(e)[t]?.enable!==!1}updateMcpEndpoint(e){if(Array.isArray(e)){if(e.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let o of e)if(!o||typeof o!="string")throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let n={...this.getConfig(),mcpEndpoint:e};this.saveConfig(n)}addMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig(),n=this.getMcpEndpoints();if(n.includes(e))throw new Error(`MCP \u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728`);let o=[...n,e],i={...t,mcpEndpoint:o};this.saveConfig(i)}removeMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig(),n=this.getMcpEndpoints();if(n.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(n.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let i=n.filter(f=>f!==e),c={...t,mcpEndpoint:i};this.saveConfig(c)}updateMcpServer(e,t){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if("type"in t&&t.type==="sse"){if(!t.url||typeof t.url!="string")throw new Error("SSE \u670D\u52A1\u914D\u7F6E\u7684 url \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else{let i=t;if(!i.command||typeof i.command!="string")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 command \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(i.args))throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4");if(i.env&&typeof i.env!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61")}let n=this.getConfig(),o={...n,mcpServers:{...n.mcpServers,[e]:t}};this.saveConfig(o)}removeMcpServer(e){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig();if(!t.mcpServers[e])throw new Error(`\u670D\u52A1 ${e} \u4E0D\u5B58\u5728`);let n={...t.mcpServers};delete n[e];let o={...t,mcpServers:n};this.saveConfig(o)}updateServerToolsConfig(e,t){let o={...this.getConfig()};o.mcpServerConfig||(o.mcpServerConfig={}),o.mcpServerConfig[e]={tools:t},this.saveConfig(o)}setToolEnabled(e,t,n,o){let c={...this.getConfig()};c.mcpServerConfig||(c.mcpServerConfig={}),c.mcpServerConfig[e]||(c.mcpServerConfig[e]={tools:{}}),c.mcpServerConfig[e].tools[t]={enable:n,...o&&{description:o}},this.saveConfig(c)}saveConfig(e){try{this.validateConfig(e);let t=this.getConfigFilePath(),n=JSON.stringify(e,null,2);$(t,n,"utf8"),this.config=e}catch(t){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}reloadConfig(){this.config=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let t=this.getConfig().connection||{};return{heartbeatInterval:t.heartbeatInterval??C.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??C.heartbeatTimeout,reconnectInterval:t.reconnectInterval??C.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(e){let t=this.getConfig(),o={...t.connection||{},...e},i={...t,connection:o};this.saveConfig(i)}setHeartbeatInterval(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:e})}setHeartbeatTimeout(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:e})}setReconnectInterval(e){if(e<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:e})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(e){let t=this.getConfig(),o={...t.modelscope||{},...e},i={...t,modelscope:o};this.saveConfig(i)}setModelScopeApiKey(e){if(!e||typeof e!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:e})}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}updateWebUIConfig(e){let t=this.getConfig(),o={...t.webUI||{},...e},i={...t,webUI:o};this.saveConfig(i)}setWebUIPort(e){if(!Number.isInteger(e)||e<=0||e>65535)throw new Error("\u7AEF\u53E3\u53F7\u5FC5\u987B\u662F 1-65535 \u4E4B\u95F4\u7684\u6574\u6570");this.updateWebUIConfig({port:e})}},b=m.getInstance();import h from"fs";import x from"path";import p from"chalk";import{createConsola as W}from"consola";function k(s){let e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),o=String(s.getHours()).padStart(2,"0"),i=String(s.getMinutes()).padStart(2,"0"),c=String(s.getSeconds()).padStart(2,"0");return`${e}-${t}-${n} ${o}:${i}:${c}`}g(k,"formatDateTime");var w=class{static{g(this,"Logger")}logFilePath=null;writeStream=null;consolaInstance;isDaemonMode;constructor(){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.consolaInstance=W({formatOptions:{date:!1,colors:!0,compact:!0},fancy:!1});let e=this.isDaemonMode;this.consolaInstance.setReporters([{log:g(t=>{let n={info:"INFO",success:"SUCCESS",warn:"WARN",error:"ERROR",debug:"DEBUG",log:"LOG"},o={info:p.blue,success:p.green,warn:p.yellow,error:p.red,debug:p.gray,log:g(l=>l,"log")},i=n[t.type]||t.type.toUpperCase(),c=o[t.type]||(l=>l),f=k(new Date),I=c(`[${i}]`),T=`[${f}] ${I} ${t.args.join(" ")}`;if(!e)try{console.error(T)}catch(l){if(l instanceof Error&&l.message?.includes("EPIPE"))return;throw l}},"log")}])}initLogFile(e){this.logFilePath=x.join(e,"xiaozhi.log"),h.existsSync(this.logFilePath)||h.writeFileSync(this.logFilePath,""),this.writeStream=h.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"})}logToFile(e,t,...n){if(this.writeStream){let i=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${t}`,c=n.length>0?`${i} ${n.map(f=>typeof f=="object"?JSON.stringify(f):String(f)).join(" ")}`:i;this.writeStream.write(`${c}
|
|
3
|
+
`)}}enableFileLogging(e){e&&!this.writeStream&&this.logFilePath?this.writeStream=h.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"}):!e&&this.writeStream&&(this.writeStream.end(),this.writeStream=null)}info(e,...t){this.consolaInstance.info(e,...t),this.logToFile("info",e,...t)}success(e,...t){this.consolaInstance.success(e,...t),this.logToFile("success",e,...t)}warn(e,...t){this.consolaInstance.warn(e,...t),this.logToFile("warn",e,...t)}error(e,...t){this.consolaInstance.error(e,...t),this.logToFile("error",e,...t)}debug(e,...t){this.consolaInstance.debug(e,...t),this.logToFile("debug",e,...t)}log(e,...t){this.consolaInstance.log(e,...t),this.logToFile("log",e,...t)}withTag(e){return this}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null)}},u=new w;var r=u.withTag("MULTI_MCP_PIPE");a.env.XIAOZHI_DAEMON==="true"&&a.env.XIAOZHI_CONFIG_DIR&&(u.initLogFile(a.env.XIAOZHI_CONFIG_DIR),u.enableFileLogging(!0));var E=class{static{g(this,"MultiEndpointMCPPipe")}mcpScript;endpoints;shouldReconnect;shutdownResolve;connectionConfig;constructor(e,t){this.mcpScript=e,this.endpoints=new Map,this.shouldReconnect=!0,r.info(t.length===1?`\u521D\u59CB\u5316\u5355\u7AEF\u70B9\u8FDE\u63A5: ${t[0]}`:`\u521D\u59CB\u5316\u591A\u7AEF\u70B9\u8FDE\u63A5\uFF08${t.length} \u4E2A\u7AEF\u70B9\uFF09`);for(let n of t)this.endpoints.set(n,{url:n,websocket:null,isConnected:!1,reconnectAttempt:0,process:null,stdoutBuffer:""});try{this.connectionConfig=b.getConnectionConfig(),r.info(`\u8FDE\u63A5\u914D\u7F6E: \u5FC3\u8DF3\u95F4\u9694=${this.connectionConfig.heartbeatInterval}ms, \u5FC3\u8DF3\u8D85\u65F6=${this.connectionConfig.heartbeatTimeout}ms, \u91CD\u8FDE\u95F4\u9694=${this.connectionConfig.reconnectInterval}ms`)}catch(n){this.connectionConfig={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},r.warn(`\u65E0\u6CD5\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u503C: ${n instanceof Error?n.message:String(n)}`)}}async start(){return await this.connectToAllEndpoints(),this.reportStatusToWebUI(),new Promise(e=>{this.shutdownResolve=e})}async connectToAllEndpoints(){let e=[];for(let[t,n]of this.endpoints)e.push(this.connectToEndpoint(t));await Promise.allSettled(e)}async connectToEndpoint(e){let t=this.endpoints.get(e);if(!t||t.isConnected)return;this.startMCPProcessForEndpoint(e),r.info(`\u6B63\u5728\u8FDE\u63A5\u5230 WebSocket \u670D\u52A1\u5668: ${e}`);let n=new d(e);t.websocket=n,n.on("open",()=>{r.info(`\u6210\u529F\u8FDE\u63A5\u5230 WebSocket \u670D\u52A1\u5668: ${e}`),t.isConnected=!0,t.reconnectAttempt=0,this.reportStatusToWebUI(),this.startHeartbeat(e)}),n.on("message",o=>{let i=o.toString();r.info(`<< [${e}] WebSocket\u6536\u5230\u6D88\u606F: ${i}`),t.process?.stdin&&!t.process.stdin.destroyed&&t.process.stdin.write(`${i}
|
|
4
|
+
`)}),n.on("close",(o,i)=>{r.error(`[${e}] WebSocket \u8FDE\u63A5\u5DF2\u5173\u95ED: ${o} ${i}`),t.isConnected=!1,t.websocket=null,this.stopHeartbeat(e),this.reportStatusToWebUI(),this.shouldReconnect&&o!==4004&&this.scheduleReconnect(e)}),n.on("error",o=>{r.error(`[${e}] WebSocket \u9519\u8BEF: ${o.message}`),t.isConnected=!1,this.stopHeartbeat(e)}),n.on("pong",()=>{t.heartbeatTimeoutTimer&&(clearTimeout(t.heartbeatTimeoutTimer),t.heartbeatTimeoutTimer=void 0)})}scheduleReconnect(e){let t=this.endpoints.get(e);!t||!this.shouldReconnect||(t.reconnectTimer&&clearTimeout(t.reconnectTimer),t.reconnectAttempt++,r.info(`[${e}] \u8BA1\u5212\u5728 ${(this.connectionConfig.reconnectInterval/1e3).toFixed(2)} \u79D2\u540E\u8FDB\u884C\u7B2C ${t.reconnectAttempt} \u6B21\u91CD\u8FDE\u5C1D\u8BD5...`),t.reconnectTimer=setTimeout(()=>{this.shouldReconnect&&((!t.process||t.process.killed)&&r.info(`[${e}] MCP \u8FDB\u7A0B\u672A\u8FD0\u884C\uFF0C\u5C06\u5728\u91CD\u8FDE\u65F6\u542F\u52A8...`),this.connectToEndpoint(e))},this.connectionConfig.reconnectInterval))}startMCPProcessForEndpoint(e){let t=this.endpoints.get(e);if(!t){r.error(`\u7AEF\u70B9\u4E0D\u5B58\u5728: ${e}`);return}if(t.process){r.info(`[${e}] MCP \u8FDB\u7A0B\u5DF2\u5728\u8FD0\u884C`);return}r.info(`[${e}] \u6B63\u5728\u542F\u52A8 MCP \u8FDB\u7A0B`),t.process=O("node",[this.mcpScript],{stdio:["pipe","pipe","pipe"]}),t.process.stdout?.on("data",n=>{t.stdoutBuffer+=n.toString();let o=t.stdoutBuffer.split(`
|
|
5
|
+
`);t.stdoutBuffer=o.pop()||"";for(let i of o)i.trim()&&this.handleMCPMessage(e,i)}),t.process.stderr?.on("data",n=>{if(a.env.XIAOZHI_DAEMON!=="true")try{a.stderr.write(n)}catch{}}),t.process.on("exit",(n,o)=>{r.warn(`[${e}] MCP \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u9000\u51FA\u7801: ${n}, \u4FE1\u53F7: ${o}`),t.process=null,this.shouldReconnect&&o!=="SIGTERM"&&o!=="SIGKILL"&&r.info(`[${e}] MCP \u8FDB\u7A0B\u610F\u5916\u9000\u51FA\uFF0C\u5C06\u5728\u4E0B\u6B21\u91CD\u8FDE\u65F6\u5C1D\u8BD5\u91CD\u542F`)}),t.process.on("error",n=>{r.error(`[${e}] \u8FDB\u7A0B\u9519\u8BEF: ${n.message}`),t.process=null,this.shouldReconnect&&r.info(`[${e}] MCP \u8FDB\u7A0B\u53D1\u751F\u9519\u8BEF\uFF0C\u5C06\u5728\u4E0B\u6B21\u91CD\u8FDE\u65F6\u5C1D\u8BD5\u91CD\u542F`)})}handleMCPMessage(e,t){r.info(`>> [${e}] mcpServerProxy\u53D1\u9001\u6D88\u606F\u957F\u5EA6: ${t.length} \u5B57\u8282`),r.info(`>> [${e}] mcpServerProxy\u53D1\u9001\u6D88\u606F: ${t.substring(0,500)}...`),this.sendToEndpoint(e,t)}sendToEndpoint(e,t){let n=this.endpoints.get(e);if(!n||!n.websocket||n.websocket.readyState!==d.OPEN){r.warn(`[${e}] \u7AEF\u70B9\u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u65E0\u6CD5\u53D1\u9001`);return}try{n.websocket.send(`${t}
|
|
6
|
+
`),r.info(`>> [${e}] \u6210\u529F\u53D1\u9001\u6D88\u606F\u5230 WebSocket`)}catch(o){r.error(`>> [${e}] \u53D1\u9001\u6D88\u606F\u5230 WebSocket \u5931\u8D25: ${o}`)}}startHeartbeat(e){let t=this.endpoints.get(e);t&&(this.stopHeartbeat(e),t.heartbeatTimer=setInterval(()=>{t.websocket&&t.websocket.readyState===d.OPEN&&(t.websocket.ping(),t.heartbeatTimeoutTimer=setTimeout(()=>{r.warn(`[${e}] \u5FC3\u8DF3\u8D85\u65F6\uFF0C\u65AD\u5F00\u8FDE\u63A5`),t.websocket?.close()},this.connectionConfig.heartbeatTimeout))},this.connectionConfig.heartbeatInterval))}stopHeartbeat(e){let t=this.endpoints.get(e);t&&(t.heartbeatTimer&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0),t.heartbeatTimeoutTimer&&(clearTimeout(t.heartbeatTimeoutTimer),t.heartbeatTimeoutTimer=void 0))}cleanup(){for(let e of this.endpoints.keys())this.stopHeartbeat(e);for(let[e,t]of this.endpoints){if(t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.stdoutBuffer="",t.process){r.info(`[${e}] \u6B63\u5728\u7EC8\u6B62 MCP \u8FDB\u7A0B`);try{t.process.kill("SIGTERM"),setTimeout(()=>{t.process&&!t.process.killed&&t.process.kill("SIGKILL")},5e3)}catch(n){r.error(`[${e}] \u7EC8\u6B62\u8FDB\u7A0B\u65F6\u51FA\u9519: ${n instanceof Error?n.message:String(n)}`)}t.process=null}if(t.websocket){try{t.websocket.close()}catch(n){r.warn(`[${e}] \u5173\u95ED WebSocket \u65F6\u51FA\u9519: ${n}`)}t.websocket=null}}}shutdown(){r.info("\u6B63\u5728\u5173\u95ED Multi-Endpoint MCP Pipe..."),this.shouldReconnect=!1;for(let e of this.endpoints.values())e.isConnected=!1;this.reportStatusToWebUI(),this.cleanup(),this.shutdownResolve&&this.shutdownResolve(),setTimeout(()=>{a.exit(0)},100)}async reportStatusToWebUI(){if(!(a.env.NODE_ENV==="test"||a.env.VITEST==="true"))try{let e=b.getWebUIPort(),t=new d(`ws://localhost:${e}`);t.on("open",()=>{let n=[];for(let[i,c]of this.endpoints)n.push({url:i,connected:c.isConnected});let o={type:"clientStatus",data:{status:this.hasAnyConnection()?"connected":"disconnected",mcpEndpoints:n,activeMCPServers:[],lastHeartbeat:Date.now()}};t.send(JSON.stringify(o)),r.debug("\u5DF2\u5411 Web UI \u62A5\u544A\u72B6\u6001"),setTimeout(()=>{t.close()},1e3)}),t.on("error",n=>{r.debug(`Web UI \u8FDE\u63A5\u5931\u8D25\uFF08\u53EF\u80FD\u672A\u8FD0\u884C\uFF09: ${n.message}`)})}catch(e){r.debug(`\u5411 Web UI \u62A5\u544A\u72B6\u6001\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}hasAnyConnection(){for(let e of this.endpoints.values())if(e.isConnected)return!0;return!1}};function Q(s){let e=a.env.XIAOZHI_DAEMON==="true";a.on("SIGINT",()=>{r.info("\u6536\u5230\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED..."),s.shutdown()}),a.on("SIGTERM",()=>{r.info("\u6536\u5230\u7EC8\u6B62\u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED..."),s.shutdown()}),e&&(a.on("SIGHUP",()=>{r.info("\u6536\u5230 SIGHUP \u4FE1\u53F7\uFF08\u7EC8\u7AEF\u5DF2\u5173\u95ED\uFF09\uFF0C\u7EE7\u7EED\u5728\u5B88\u62A4\u8FDB\u7A0B\u6A21\u5F0F\u4E0B\u8FD0\u884C...")}),a.on("uncaughtException",t=>{t.message?.includes("EPIPE")||r.error(`\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${t.message||t}
|
|
7
|
+
${t.stack||""}`)}),a.on("unhandledRejection",(t,n)=>{r.error(`\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${t instanceof Error?t.message:String(t)}`)}))}g(Q,"setupSignalHandlers");export{E as MultiEndpointMCPPipe,Q as setupSignalHandlers};
|
|
8
|
+
//# sourceMappingURL=multiEndpointMCPPipe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/multiEndpointMCPPipe.ts","../src/configManager.ts","../src/logger.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Multi-Endpoint MCP Pipe - 支持多个 MCP 接入点\n * 管理多个 WebSocket 连接,并正确路由消息到对应的接入点\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport process from \"node:process\";\nimport WebSocket from \"ws\";\nimport { configManager } from \"./configManager.js\";\nimport { logger as globalLogger } from \"./logger.js\";\n\n// 为 MultiEndpointMCPPipe 创建带标签的 logger\nconst logger = globalLogger.withTag(\"MULTI_MCP_PIPE\");\n\n// 如果在守护进程模式下运行,初始化日志文件\nif (process.env.XIAOZHI_DAEMON === \"true\" && process.env.XIAOZHI_CONFIG_DIR) {\n globalLogger.initLogFile(process.env.XIAOZHI_CONFIG_DIR);\n globalLogger.enableFileLogging(true);\n}\n\ninterface EndpointConnection {\n url: string;\n websocket: WebSocket | null;\n isConnected: boolean;\n reconnectAttempt: number;\n reconnectTimer?: NodeJS.Timeout;\n heartbeatTimer?: NodeJS.Timeout;\n heartbeatTimeoutTimer?: NodeJS.Timeout;\n process: ChildProcess | null; // 每个端点独立的 MCP 进程\n stdoutBuffer: string; // 每个端点独立的输出缓冲区\n}\n\nexport class MultiEndpointMCPPipe {\n private mcpScript: string;\n private endpoints: Map<string, EndpointConnection>;\n private shouldReconnect: boolean;\n private shutdownResolve?: () => void;\n private connectionConfig: {\n heartbeatInterval: number;\n heartbeatTimeout: number;\n reconnectInterval: number;\n };\n\n constructor(mcpScript: string, endpointUrls: string[]) {\n this.mcpScript = mcpScript;\n this.endpoints = new Map();\n this.shouldReconnect = true;\n\n // 记录端点数量,明确表示支持单端点和多端点\n logger.info(\n endpointUrls.length === 1\n ? `初始化单端点连接: ${endpointUrls[0]}`\n : `初始化多端点连接(${endpointUrls.length} 个端点)`\n );\n\n // 初始化所有端点\n for (const url of endpointUrls) {\n this.endpoints.set(url, {\n url,\n websocket: null,\n isConnected: false,\n reconnectAttempt: 0,\n process: null,\n stdoutBuffer: \"\",\n });\n }\n\n // 获取连接配置\n try {\n this.connectionConfig = configManager.getConnectionConfig();\n logger.info(\n `连接配置: 心跳间隔=${this.connectionConfig.heartbeatInterval}ms, ` +\n `心跳超时=${this.connectionConfig.heartbeatTimeout}ms, ` +\n `重连间隔=${this.connectionConfig.reconnectInterval}ms`\n );\n } catch (error) {\n this.connectionConfig = {\n heartbeatInterval: 30000,\n heartbeatTimeout: 10000,\n reconnectInterval: 5000,\n };\n logger.warn(\n `无法获取连接配置,使用默认值: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n async start() {\n // 连接到所有端点(每个端点会启动自己的 MCP 进程)\n await this.connectToAllEndpoints();\n\n // 报告状态到 Web UI\n this.reportStatusToWebUI();\n\n // 保持进程运行\n return new Promise<void>((resolve) => {\n this.shutdownResolve = resolve;\n });\n }\n\n async connectToAllEndpoints() {\n const connectionPromises: Promise<void>[] = [];\n\n for (const [url, endpoint] of this.endpoints) {\n connectionPromises.push(this.connectToEndpoint(url));\n }\n\n await Promise.allSettled(connectionPromises);\n }\n\n async connectToEndpoint(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint || endpoint.isConnected) {\n return;\n }\n\n // 先为该端点启动 MCP 进程\n this.startMCPProcessForEndpoint(endpointUrl);\n\n logger.info(`正在连接到 WebSocket 服务器: ${endpointUrl}`);\n\n const ws = new WebSocket(endpointUrl);\n endpoint.websocket = ws;\n\n ws.on(\"open\", () => {\n logger.info(`成功连接到 WebSocket 服务器: ${endpointUrl}`);\n endpoint.isConnected = true;\n endpoint.reconnectAttempt = 0;\n\n // 报告状态\n this.reportStatusToWebUI();\n\n // 启动心跳检测\n this.startHeartbeat(endpointUrl);\n });\n\n ws.on(\"message\", (data: WebSocket.Data) => {\n const message = data.toString();\n logger.info(`<< [${endpointUrl}] WebSocket收到消息: ${message}`);\n\n // 将消息写入对应端点的进程标准输入\n if (endpoint.process?.stdin && !endpoint.process.stdin.destroyed) {\n endpoint.process.stdin.write(`${message}\\n`);\n }\n });\n\n ws.on(\"close\", (code: number, reason: Buffer) => {\n logger.error(`[${endpointUrl}] WebSocket 连接已关闭: ${code} ${reason}`);\n endpoint.isConnected = false;\n endpoint.websocket = null;\n\n // 停止心跳检测\n this.stopHeartbeat(endpointUrl);\n\n // 报告断开状态\n this.reportStatusToWebUI();\n\n // 如果应该重连且不是永久错误\n if (this.shouldReconnect && code !== 4004) {\n this.scheduleReconnect(endpointUrl);\n }\n });\n\n ws.on(\"error\", (error: Error) => {\n logger.error(`[${endpointUrl}] WebSocket 错误: ${error.message}`);\n endpoint.isConnected = false;\n\n // 停止心跳检测\n this.stopHeartbeat(endpointUrl);\n });\n\n // 处理 pong 响应\n ws.on(\"pong\", () => {\n // 收到 pong 响应,清除心跳超时定时器\n if (endpoint.heartbeatTimeoutTimer) {\n clearTimeout(endpoint.heartbeatTimeoutTimer);\n endpoint.heartbeatTimeoutTimer = undefined;\n }\n });\n }\n\n scheduleReconnect(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint || !this.shouldReconnect) return;\n\n // 清除之前的重连定时器\n if (endpoint.reconnectTimer) {\n clearTimeout(endpoint.reconnectTimer);\n }\n\n endpoint.reconnectAttempt++;\n\n logger.info(\n `[${endpointUrl}] 计划在 ${(\n this.connectionConfig.reconnectInterval / 1000\n ).toFixed(2)} 秒后进行第 ${endpoint.reconnectAttempt} 次重连尝试...`\n );\n\n endpoint.reconnectTimer = setTimeout(() => {\n if (this.shouldReconnect) {\n // 如果MCP进程不存在,先尝试重启\n if (!endpoint.process || endpoint.process.killed) {\n logger.info(`[${endpointUrl}] MCP 进程未运行,将在重连时启动...`);\n }\n this.connectToEndpoint(endpointUrl);\n }\n }, this.connectionConfig.reconnectInterval);\n }\n\n startMCPProcessForEndpoint(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint) {\n logger.error(`端点不存在: ${endpointUrl}`);\n return;\n }\n\n if (endpoint.process) {\n logger.info(`[${endpointUrl}] MCP 进程已在运行`);\n return;\n }\n\n logger.info(`[${endpointUrl}] 正在启动 MCP 进程`);\n\n endpoint.process = spawn(\"node\", [this.mcpScript], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n // 处理进程标准输出 - 发送到对应的 WebSocket\n endpoint.process.stdout?.on(\"data\", (data: Buffer) => {\n // 将数据添加到缓冲区\n endpoint.stdoutBuffer += data.toString();\n\n // 按换行符分割消息\n const lines = endpoint.stdoutBuffer.split(\"\\n\");\n endpoint.stdoutBuffer = lines.pop() || \"\"; // 保留最后一个不完整的行\n\n // 处理每个完整的消息\n for (const line of lines) {\n if (line.trim()) {\n this.handleMCPMessage(endpointUrl, line);\n }\n }\n });\n\n // 处理进程标准错误\n endpoint.process.stderr?.on(\"data\", (data: Buffer) => {\n if (process.env.XIAOZHI_DAEMON !== \"true\") {\n try {\n process.stderr.write(data);\n } catch (error) {\n // 忽略 EPIPE 错误\n }\n }\n });\n\n // 处理进程退出\n endpoint.process.on(\n \"exit\",\n (code: number | null, signal: NodeJS.Signals | null) => {\n logger.warn(\n `[${endpointUrl}] MCP 进程已退出,退出码: ${code}, 信号: ${signal}`\n );\n endpoint.process = null;\n\n if (\n this.shouldReconnect &&\n signal !== \"SIGTERM\" &&\n signal !== \"SIGKILL\"\n ) {\n logger.info(\n `[${endpointUrl}] MCP 进程意外退出,将在下次重连时尝试重启`\n );\n }\n }\n );\n\n // 处理进程错误\n endpoint.process.on(\"error\", (error: Error) => {\n logger.error(`[${endpointUrl}] 进程错误: ${error.message}`);\n endpoint.process = null;\n\n if (this.shouldReconnect) {\n logger.info(\n `[${endpointUrl}] MCP 进程发生错误,将在下次重连时尝试重启`\n );\n }\n });\n }\n\n handleMCPMessage(endpointUrl: string, line: string) {\n logger.info(\n `>> [${endpointUrl}] mcpServerProxy发送消息长度: ${line.length} 字节`\n );\n logger.info(\n `>> [${endpointUrl}] mcpServerProxy发送消息: ${line.substring(0, 500)}...`\n );\n\n // 直接发送回对应的端点\n this.sendToEndpoint(endpointUrl, line);\n }\n\n sendToEndpoint(endpointUrl: string, message: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (\n !endpoint ||\n !endpoint.websocket ||\n endpoint.websocket.readyState !== WebSocket.OPEN\n ) {\n logger.warn(`[${endpointUrl}] 端点不可用,消息无法发送`);\n return;\n }\n\n try {\n endpoint.websocket.send(`${message}\\n`);\n logger.info(`>> [${endpointUrl}] 成功发送消息到 WebSocket`);\n } catch (error) {\n logger.error(`>> [${endpointUrl}] 发送消息到 WebSocket 失败: ${error}`);\n }\n }\n\n startHeartbeat(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint) return;\n\n // 清除之前的心跳定时器\n this.stopHeartbeat(endpointUrl);\n\n // 设置心跳定时器\n endpoint.heartbeatTimer = setInterval(() => {\n if (\n endpoint.websocket &&\n endpoint.websocket.readyState === WebSocket.OPEN\n ) {\n // 发送 ping\n endpoint.websocket.ping();\n\n // 设置心跳超时定时器\n endpoint.heartbeatTimeoutTimer = setTimeout(() => {\n logger.warn(`[${endpointUrl}] 心跳超时,断开连接`);\n endpoint.websocket?.close();\n }, this.connectionConfig.heartbeatTimeout);\n }\n }, this.connectionConfig.heartbeatInterval);\n }\n\n stopHeartbeat(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint) return;\n\n if (endpoint.heartbeatTimer) {\n clearInterval(endpoint.heartbeatTimer);\n endpoint.heartbeatTimer = undefined;\n }\n\n if (endpoint.heartbeatTimeoutTimer) {\n clearTimeout(endpoint.heartbeatTimeoutTimer);\n endpoint.heartbeatTimeoutTimer = undefined;\n }\n }\n\n cleanup() {\n // 停止所有心跳检测\n for (const url of this.endpoints.keys()) {\n this.stopHeartbeat(url);\n }\n\n // 清除所有重连定时器,清理进程和缓冲区\n for (const [url, endpoint] of this.endpoints) {\n if (endpoint.reconnectTimer) {\n clearTimeout(endpoint.reconnectTimer);\n endpoint.reconnectTimer = undefined;\n }\n\n // 清空每个端点的缓冲区\n endpoint.stdoutBuffer = \"\";\n\n // 终止每个端点的进程\n if (endpoint.process) {\n logger.info(`[${url}] 正在终止 MCP 进程`);\n try {\n endpoint.process.kill(\"SIGTERM\");\n\n // 强制终止\n setTimeout(() => {\n if (endpoint.process && !endpoint.process.killed) {\n endpoint.process.kill(\"SIGKILL\");\n }\n }, 5000);\n } catch (error) {\n logger.error(\n `[${url}] 终止进程时出错: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n endpoint.process = null;\n }\n\n // 关闭 WebSocket 连接\n if (endpoint.websocket) {\n try {\n endpoint.websocket.close();\n } catch (error) {\n logger.warn(`[${url}] 关闭 WebSocket 时出错: ${error}`);\n }\n endpoint.websocket = null;\n }\n }\n }\n\n shutdown() {\n logger.info(\"正在关闭 Multi-Endpoint MCP Pipe...\");\n this.shouldReconnect = false;\n\n // 报告断开状态\n for (const endpoint of this.endpoints.values()) {\n endpoint.isConnected = false;\n }\n this.reportStatusToWebUI();\n\n this.cleanup();\n\n if (this.shutdownResolve) {\n this.shutdownResolve();\n }\n\n // 给状态报告一点时间\n setTimeout(() => {\n process.exit(0);\n }, 100);\n }\n\n // 报告状态到 Web UI 服务器\n private async reportStatusToWebUI() {\n // 在测试环境中跳过\n if (process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\") {\n return;\n }\n\n try {\n // 从配置获取 WebUI 端口\n const port = configManager.getWebUIPort();\n const statusWs = new WebSocket(`ws://localhost:${port}`);\n\n statusWs.on(\"open\", () => {\n // 收集所有端点的状态\n const endpointStatuses: { url: string; connected: boolean }[] = [];\n for (const [url, endpoint] of this.endpoints) {\n endpointStatuses.push({\n url,\n connected: endpoint.isConnected,\n });\n }\n\n const status = {\n type: \"clientStatus\",\n data: {\n status: this.hasAnyConnection() ? \"connected\" : \"disconnected\",\n mcpEndpoints: endpointStatuses,\n activeMCPServers: [], // 由 mcpServerProxy 填充\n lastHeartbeat: Date.now(),\n },\n };\n statusWs.send(JSON.stringify(status));\n logger.debug(\"已向 Web UI 报告状态\");\n\n // 发送状态后关闭连接\n setTimeout(() => {\n statusWs.close();\n }, 1000);\n });\n\n statusWs.on(\"error\", (error) => {\n logger.debug(`Web UI 连接失败(可能未运行): ${error.message}`);\n });\n } catch (error) {\n logger.debug(\n `向 Web UI 报告状态失败: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n hasAnyConnection(): boolean {\n for (const endpoint of this.endpoints.values()) {\n if (endpoint.isConnected) {\n return true;\n }\n }\n return false;\n }\n}\n\n// 信号处理器\nexport function setupSignalHandlers(mcpPipe: MultiEndpointMCPPipe): void {\n const isDaemon = process.env.XIAOZHI_DAEMON === \"true\";\n\n process.on(\"SIGINT\", () => {\n logger.info(\"收到中断信号,正在关闭...\");\n mcpPipe.shutdown();\n });\n\n process.on(\"SIGTERM\", () => {\n logger.info(\"收到终止信号,正在关闭...\");\n mcpPipe.shutdown();\n });\n\n // 守护进程模式下的额外信号处理\n if (isDaemon) {\n process.on(\"SIGHUP\", () => {\n logger.info(\n \"收到 SIGHUP 信号(终端已关闭),继续在守护进程模式下运行...\"\n );\n });\n\n process.on(\"uncaughtException\", (error) => {\n if (error.message?.includes(\"EPIPE\")) {\n return;\n }\n logger.error(\n `未捕获的异常: ${error.message || error}\\n${error.stack || \"\"}`\n );\n });\n\n process.on(\"unhandledRejection\", (reason, promise) => {\n logger.error(\n `未处理的 Promise 拒绝: ${\n reason instanceof Error ? reason.message : String(reason)\n }`\n );\n });\n }\n}\n","import { copyFileSync, existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// 在 ESM 中,需要从 import.meta.url 获取当前文件目录\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// 默认连接配置\nconst DEFAULT_CONNECTION_CONFIG: Required<ConnectionConfig> = {\n heartbeatInterval: 30000, // 30秒心跳间隔\n heartbeatTimeout: 10000, // 10秒心跳超时\n reconnectInterval: 5000, // 5秒重连间隔\n};\n\n// 配置文件接口定义\n// 本地 MCP 服务配置\nexport interface LocalMCPServerConfig {\n command: string;\n args: string[];\n env?: Record<string, string>;\n}\n\n// ModelScope SSE MCP 服务配置\nexport interface SSEMCPServerConfig {\n type: \"sse\";\n url: string;\n}\n\n// 统一的 MCP 服务配置\nexport type MCPServerConfig = LocalMCPServerConfig | SSEMCPServerConfig;\n\nexport interface MCPToolConfig {\n description?: string;\n enable: boolean;\n}\n\nexport interface MCPServerToolsConfig {\n tools: Record<string, MCPToolConfig>;\n}\n\nexport interface ConnectionConfig {\n heartbeatInterval?: number; // 心跳检测间隔(毫秒),默认30000\n heartbeatTimeout?: number; // 心跳超时时间(毫秒),默认10000\n reconnectInterval?: number; // 重连间隔(毫秒),默认5000\n}\n\nexport interface ModelScopeConfig {\n apiKey?: string; // ModelScope API 密钥\n}\n\nexport interface WebUIConfig {\n port?: number; // Web UI 端口号,默认 9999\n}\n\nexport interface AppConfig {\n mcpEndpoint: string | string[];\n mcpServers: Record<string, MCPServerConfig>;\n mcpServerConfig?: Record<string, MCPServerToolsConfig>;\n connection?: ConnectionConfig; // 连接配置(可选,用于向后兼容)\n modelscope?: ModelScopeConfig; // ModelScope 配置(可选)\n webUI?: WebUIConfig; // Web UI 配置(可选)\n}\n\n/**\n * 配置管理类\n * 负责管理应用配置,提供只读访问和安全的配置更新功能\n */\nexport class ConfigManager {\n private static instance: ConfigManager;\n private defaultConfigPath: string;\n private config: AppConfig | null = null;\n\n private constructor() {\n this.defaultConfigPath = resolve(__dirname, \"xiaozhi.config.default.json\");\n }\n\n /**\n * 获取配置文件路径(动态计算)\n */\n private getConfigFilePath(): string {\n // 配置文件路径 - 优先使用环境变量指定的目录,否则使用当前工作目录\n const configDir = process.env.XIAOZHI_CONFIG_DIR || process.cwd();\n return resolve(configDir, \"xiaozhi.config.json\");\n }\n\n /**\n * 获取配置管理器单例实例\n */\n public static getInstance(): ConfigManager {\n if (!ConfigManager.instance) {\n ConfigManager.instance = new ConfigManager();\n }\n return ConfigManager.instance;\n }\n\n /**\n * 检查配置文件是否存在\n */\n public configExists(): boolean {\n const configPath = this.getConfigFilePath();\n return existsSync(configPath);\n }\n\n /**\n * 初始化配置文件\n * 从 config.default.json 复制到 config.json\n */\n public initConfig(): void {\n if (!existsSync(this.defaultConfigPath)) {\n throw new Error(\"默认配置文件 xiaozhi.config.default.json 不存在\");\n }\n\n if (this.configExists()) {\n throw new Error(\"配置文件 xiaozhi.config.json 已存在,无需重复初始化\");\n }\n\n const configPath = this.getConfigFilePath();\n copyFileSync(this.defaultConfigPath, configPath);\n this.config = null; // 重置缓存\n }\n\n /**\n * 加载配置文件\n */\n private loadConfig(): AppConfig {\n if (!this.configExists()) {\n throw new Error(\n \"配置文件 xiaozhi.config.json 不存在,请先运行 xiaozhi init 初始化配置\"\n );\n }\n\n try {\n const configPath = this.getConfigFilePath();\n const configData = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(configData) as AppConfig;\n\n // 验证配置结构\n this.validateConfig(config);\n\n return config;\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(`配置文件格式错误: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * 验证配置文件结构\n */\n private validateConfig(config: unknown): void {\n if (!config || typeof config !== \"object\") {\n throw new Error(\"配置文件格式错误:根对象无效\");\n }\n\n const configObj = config as Record<string, unknown>;\n\n if (configObj.mcpEndpoint === undefined || configObj.mcpEndpoint === null) {\n throw new Error(\"配置文件格式错误:mcpEndpoint 字段无效\");\n }\n\n // 验证 mcpEndpoint 类型(字符串或字符串数组)\n if (typeof configObj.mcpEndpoint === \"string\") {\n // 空字符串是允许的,getMcpEndpoints 会返回空数组\n } else if (Array.isArray(configObj.mcpEndpoint)) {\n if (configObj.mcpEndpoint.length === 0) {\n throw new Error(\"配置文件格式错误:mcpEndpoint 数组不能为空\");\n }\n for (const endpoint of configObj.mcpEndpoint) {\n if (typeof endpoint !== \"string\" || endpoint.trim() === \"\") {\n throw new Error(\n \"配置文件格式错误:mcpEndpoint 数组中的每个元素必须是非空字符串\"\n );\n }\n }\n } else {\n throw new Error(\"配置文件格式错误:mcpEndpoint 必须是字符串或字符串数组\");\n }\n\n if (!configObj.mcpServers || typeof configObj.mcpServers !== \"object\") {\n throw new Error(\"配置文件格式错误:mcpServers 字段无效\");\n }\n\n // 验证每个 MCP 服务配置\n for (const [serverName, serverConfig] of Object.entries(\n configObj.mcpServers as Record<string, unknown>\n )) {\n if (!serverConfig || typeof serverConfig !== \"object\") {\n throw new Error(`配置文件格式错误:mcpServers.${serverName} 无效`);\n }\n\n const sc = serverConfig as Record<string, unknown>;\n\n // 检查是否是 SSE 类型\n if (sc.type === \"sse\") {\n // SSE 类型的验证\n if (!sc.url || typeof sc.url !== \"string\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.url 无效`\n );\n }\n } else {\n // 本地类型的验证\n if (!sc.command || typeof sc.command !== \"string\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.command 无效`\n );\n }\n\n if (!Array.isArray(sc.args)) {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.args 必须是数组`\n );\n }\n\n if (sc.env && typeof sc.env !== \"object\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.env 必须是对象`\n );\n }\n }\n }\n }\n\n /**\n * 获取配置(只读)\n */\n public getConfig(): Readonly<AppConfig> {\n if (!this.config) {\n this.config = this.loadConfig();\n }\n\n // 返回深度只读副本\n return JSON.parse(JSON.stringify(this.config));\n }\n\n /**\n * 获取 MCP 端点(向后兼容)\n * @deprecated 使用 getMcpEndpoints() 获取所有端点\n */\n public getMcpEndpoint(): string {\n const config = this.getConfig();\n if (Array.isArray(config.mcpEndpoint)) {\n return config.mcpEndpoint[0] || \"\";\n }\n return config.mcpEndpoint;\n }\n\n /**\n * 获取所有 MCP 端点\n */\n public getMcpEndpoints(): string[] {\n const config = this.getConfig();\n if (Array.isArray(config.mcpEndpoint)) {\n return [...config.mcpEndpoint];\n }\n return config.mcpEndpoint ? [config.mcpEndpoint] : [];\n }\n\n /**\n * 获取 MCP 服务配置\n */\n public getMcpServers(): Readonly<Record<string, MCPServerConfig>> {\n const config = this.getConfig();\n return config.mcpServers;\n }\n\n /**\n * 获取 MCP 服务工具配置\n */\n public getMcpServerConfig(): Readonly<Record<string, MCPServerToolsConfig>> {\n const config = this.getConfig();\n return config.mcpServerConfig || {};\n }\n\n /**\n * 获取指定服务的工具配置\n */\n public getServerToolsConfig(\n serverName: string\n ): Readonly<Record<string, MCPToolConfig>> {\n const serverConfig = this.getMcpServerConfig();\n return serverConfig[serverName]?.tools || {};\n }\n\n /**\n * 检查工具是否启用\n */\n public isToolEnabled(serverName: string, toolName: string): boolean {\n const toolsConfig = this.getServerToolsConfig(serverName);\n const toolConfig = toolsConfig[toolName];\n return toolConfig?.enable !== false; // 默认启用\n }\n\n /**\n * 更新 MCP 端点(支持字符串或数组)\n */\n public updateMcpEndpoint(endpoint: string | string[]): void {\n if (Array.isArray(endpoint)) {\n if (endpoint.length === 0) {\n throw new Error(\"MCP 端点数组不能为空\");\n }\n for (const ep of endpoint) {\n if (!ep || typeof ep !== \"string\") {\n throw new Error(\"MCP 端点数组中的每个元素必须是非空字符串\");\n }\n }\n } else {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n }\n\n const config = this.getConfig();\n const newConfig = { ...config, mcpEndpoint: endpoint };\n this.saveConfig(newConfig);\n }\n\n /**\n * 添加 MCP 端点\n */\n public addMcpEndpoint(endpoint: string): void {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n\n const config = this.getConfig();\n const currentEndpoints = this.getMcpEndpoints();\n\n // 检查是否已存在\n if (currentEndpoints.includes(endpoint)) {\n throw new Error(`MCP 端点 ${endpoint} 已存在`);\n }\n\n const newEndpoints = [...currentEndpoints, endpoint];\n const newConfig = { ...config, mcpEndpoint: newEndpoints };\n this.saveConfig(newConfig);\n }\n\n /**\n * 移除 MCP 端点\n */\n public removeMcpEndpoint(endpoint: string): void {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n\n const config = this.getConfig();\n const currentEndpoints = this.getMcpEndpoints();\n\n // 检查是否存在\n const index = currentEndpoints.indexOf(endpoint);\n if (index === -1) {\n throw new Error(`MCP 端点 ${endpoint} 不存在`);\n }\n\n // 不允许删除最后一个端点\n if (currentEndpoints.length === 1) {\n throw new Error(\"不能删除最后一个 MCP 端点\");\n }\n\n const newEndpoints = currentEndpoints.filter((ep) => ep !== endpoint);\n const newConfig = { ...config, mcpEndpoint: newEndpoints };\n this.saveConfig(newConfig);\n }\n\n /**\n * 更新 MCP 服务配置\n */\n public updateMcpServer(\n serverName: string,\n serverConfig: MCPServerConfig\n ): void {\n if (!serverName || typeof serverName !== \"string\") {\n throw new Error(\"服务名称必须是非空字符串\");\n }\n\n // 验证服务配置\n if (\"type\" in serverConfig && serverConfig.type === \"sse\") {\n // SSE 类型的验证\n if (!serverConfig.url || typeof serverConfig.url !== \"string\") {\n throw new Error(\"SSE 服务配置的 url 字段必须是非空字符串\");\n }\n } else {\n // 本地类型的验证\n const localConfig = serverConfig as LocalMCPServerConfig;\n if (!localConfig.command || typeof localConfig.command !== \"string\") {\n throw new Error(\"服务配置的 command 字段必须是非空字符串\");\n }\n\n if (!Array.isArray(localConfig.args)) {\n throw new Error(\"服务配置的 args 字段必须是数组\");\n }\n\n if (localConfig.env && typeof localConfig.env !== \"object\") {\n throw new Error(\"服务配置的 env 字段必须是对象\");\n }\n }\n\n const config = this.getConfig();\n const newConfig = {\n ...config,\n mcpServers: {\n ...config.mcpServers,\n [serverName]: serverConfig,\n },\n };\n this.saveConfig(newConfig);\n }\n\n /**\n * 删除 MCP 服务配置\n */\n public removeMcpServer(serverName: string): void {\n if (!serverName || typeof serverName !== \"string\") {\n throw new Error(\"服务名称必须是非空字符串\");\n }\n\n const config = this.getConfig();\n if (!config.mcpServers[serverName]) {\n throw new Error(`服务 ${serverName} 不存在`);\n }\n\n const newMcpServers = { ...config.mcpServers };\n delete newMcpServers[serverName];\n\n const newConfig = {\n ...config,\n mcpServers: newMcpServers,\n };\n this.saveConfig(newConfig);\n }\n\n /**\n * 更新服务工具配置\n */\n public updateServerToolsConfig(\n serverName: string,\n toolsConfig: Record<string, MCPToolConfig>\n ): void {\n const config = this.getConfig();\n const newConfig = { ...config };\n\n // 确保 mcpServerConfig 存在\n if (!newConfig.mcpServerConfig) {\n newConfig.mcpServerConfig = {};\n }\n\n // 更新指定服务的工具配置\n newConfig.mcpServerConfig[serverName] = {\n tools: toolsConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置工具启用状态\n */\n public setToolEnabled(\n serverName: string,\n toolName: string,\n enabled: boolean,\n description?: string\n ): void {\n const config = this.getConfig();\n const newConfig = { ...config };\n\n // 确保 mcpServerConfig 存在\n if (!newConfig.mcpServerConfig) {\n newConfig.mcpServerConfig = {};\n }\n\n // 确保服务配置存在\n if (!newConfig.mcpServerConfig[serverName]) {\n newConfig.mcpServerConfig[serverName] = { tools: {} };\n }\n\n // 更新工具配置\n newConfig.mcpServerConfig[serverName].tools[toolName] = {\n enable: enabled,\n ...(description && { description }),\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 保存配置到文件\n */\n private saveConfig(config: AppConfig): void {\n try {\n // 验证配置\n this.validateConfig(config);\n\n // 格式化 JSON 并保存\n const configPath = this.getConfigFilePath();\n const configJson = JSON.stringify(config, null, 2);\n writeFileSync(configPath, configJson, \"utf8\");\n\n // 更新缓存\n this.config = config;\n } catch (error) {\n throw new Error(\n `保存配置失败: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * 重新加载配置(清除缓存)\n */\n public reloadConfig(): void {\n this.config = null;\n }\n\n /**\n * 获取配置文件路径\n */\n public getConfigPath(): string {\n return this.getConfigFilePath();\n }\n\n /**\n * 获取默认配置文件路径\n */\n public getDefaultConfigPath(): string {\n return this.defaultConfigPath;\n }\n\n /**\n * 获取连接配置(包含默认值)\n */\n public getConnectionConfig(): Required<ConnectionConfig> {\n const config = this.getConfig();\n const connectionConfig = config.connection || {};\n\n return {\n heartbeatInterval:\n connectionConfig.heartbeatInterval ??\n DEFAULT_CONNECTION_CONFIG.heartbeatInterval,\n heartbeatTimeout:\n connectionConfig.heartbeatTimeout ??\n DEFAULT_CONNECTION_CONFIG.heartbeatTimeout,\n reconnectInterval:\n connectionConfig.reconnectInterval ??\n DEFAULT_CONNECTION_CONFIG.reconnectInterval,\n };\n }\n\n /**\n * 获取心跳检测间隔(毫秒)\n */\n public getHeartbeatInterval(): number {\n return this.getConnectionConfig().heartbeatInterval;\n }\n\n /**\n * 获取心跳超时时间(毫秒)\n */\n public getHeartbeatTimeout(): number {\n return this.getConnectionConfig().heartbeatTimeout;\n }\n\n /**\n * 获取重连间隔(毫秒)\n */\n public getReconnectInterval(): number {\n return this.getConnectionConfig().reconnectInterval;\n }\n\n /**\n * 更新连接配置\n */\n public updateConnectionConfig(\n connectionConfig: Partial<ConnectionConfig>\n ): void {\n const config = this.getConfig();\n const currentConnectionConfig = config.connection || {};\n\n const newConnectionConfig = {\n ...currentConnectionConfig,\n ...connectionConfig,\n };\n\n const newConfig = {\n ...config,\n connection: newConnectionConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置心跳检测间隔\n */\n public setHeartbeatInterval(interval: number): void {\n if (interval <= 0) {\n throw new Error(\"心跳检测间隔必须大于0\");\n }\n this.updateConnectionConfig({ heartbeatInterval: interval });\n }\n\n /**\n * 设置心跳超时时间\n */\n public setHeartbeatTimeout(timeout: number): void {\n if (timeout <= 0) {\n throw new Error(\"心跳超时时间必须大于0\");\n }\n this.updateConnectionConfig({ heartbeatTimeout: timeout });\n }\n\n /**\n * 设置重连间隔\n */\n public setReconnectInterval(interval: number): void {\n if (interval <= 0) {\n throw new Error(\"重连间隔必须大于0\");\n }\n this.updateConnectionConfig({ reconnectInterval: interval });\n }\n\n /**\n * 获取 ModelScope 配置\n */\n public getModelScopeConfig(): Readonly<ModelScopeConfig> {\n const config = this.getConfig();\n return config.modelscope || {};\n }\n\n /**\n * 获取 ModelScope API Key\n * 优先从配置文件读取,其次从环境变量读取\n */\n public getModelScopeApiKey(): string | undefined {\n const modelScopeConfig = this.getModelScopeConfig();\n return modelScopeConfig.apiKey || process.env.MODELSCOPE_API_TOKEN;\n }\n\n /**\n * 更新 ModelScope 配置\n */\n public updateModelScopeConfig(\n modelScopeConfig: Partial<ModelScopeConfig>\n ): void {\n const config = this.getConfig();\n const currentModelScopeConfig = config.modelscope || {};\n\n const newModelScopeConfig = {\n ...currentModelScopeConfig,\n ...modelScopeConfig,\n };\n\n const newConfig = {\n ...config,\n modelscope: newModelScopeConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置 ModelScope API Key\n */\n public setModelScopeApiKey(apiKey: string): void {\n if (!apiKey || typeof apiKey !== \"string\") {\n throw new Error(\"API Key 必须是非空字符串\");\n }\n this.updateModelScopeConfig({ apiKey });\n }\n\n /**\n * 获取 Web UI 配置\n */\n public getWebUIConfig(): Readonly<WebUIConfig> {\n const config = this.getConfig();\n return config.webUI || {};\n }\n\n /**\n * 获取 Web UI 端口号\n */\n public getWebUIPort(): number {\n const webUIConfig = this.getWebUIConfig();\n return webUIConfig.port ?? 9999; // 默认端口 9999\n }\n\n /**\n * 更新 Web UI 配置\n */\n public updateWebUIConfig(webUIConfig: Partial<WebUIConfig>): void {\n const config = this.getConfig();\n const currentWebUIConfig = config.webUI || {};\n\n const newWebUIConfig = {\n ...currentWebUIConfig,\n ...webUIConfig,\n };\n\n const newConfig = {\n ...config,\n webUI: newWebUIConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置 Web UI 端口号\n */\n public setWebUIPort(port: number): void {\n if (!Number.isInteger(port) || port <= 0 || port > 65535) {\n throw new Error(\"端口号必须是 1-65535 之间的整数\");\n }\n this.updateWebUIConfig({ port });\n }\n}\n\n// 导出单例实例\nexport const configManager = ConfigManager.getInstance();\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport chalk from \"chalk\";\nimport { type consola, createConsola } from \"consola\";\n\nfunction formatDateTime(date: Date) {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n const day = String(date.getDate()).padStart(2, \"0\");\n const hours = String(date.getHours()).padStart(2, \"0\");\n const minutes = String(date.getMinutes()).padStart(2, \"0\");\n const seconds = String(date.getSeconds()).padStart(2, \"0\");\n\n return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;\n}\n\nexport class Logger {\n private logFilePath: string | null = null;\n private writeStream: fs.WriteStream | null = null;\n private consolaInstance: typeof consola;\n private isDaemonMode: boolean;\n\n constructor() {\n // 检查是否为守护进程模式\n this.isDaemonMode = process.env.XIAOZHI_DAEMON === \"true\";\n // 创建自定义的 consola 实例,禁用图标并自定义格式\n this.consolaInstance = createConsola({\n formatOptions: {\n date: false,\n colors: true,\n compact: true,\n },\n fancy: false,\n });\n\n // 保存对当前实例的引用,以便在闭包中访问\n const isDaemonMode = this.isDaemonMode;\n\n // 自定义格式化器\n this.consolaInstance.setReporters([\n {\n log: (logObj) => {\n const levelMap: Record<string, string> = {\n info: \"INFO\",\n success: \"SUCCESS\",\n warn: \"WARN\",\n error: \"ERROR\",\n debug: \"DEBUG\",\n log: \"LOG\",\n };\n\n const colorMap: Record<string, (text: string) => string> = {\n info: chalk.blue,\n success: chalk.green,\n warn: chalk.yellow,\n error: chalk.red,\n debug: chalk.gray,\n log: (text: string) => text,\n };\n\n const level = levelMap[logObj.type] || logObj.type.toUpperCase();\n const colorFn = colorMap[logObj.type] || ((text: string) => text);\n const timestamp = formatDateTime(new Date());\n\n // 为级别添加颜色\n const coloredLevel = colorFn(`[${level}]`);\n const message = `[${timestamp}] ${coloredLevel} ${logObj.args.join(\n \" \"\n )}`;\n\n // 守护进程模式下不输出到控制台,只写入文件\n if (!isDaemonMode) {\n // 输出到 stderr(与原来保持一致)\n try {\n console.error(message);\n } catch (error) {\n // 忽略 EPIPE 错误\n if (error instanceof Error && error.message?.includes(\"EPIPE\")) {\n return;\n }\n throw error;\n }\n }\n },\n },\n ]);\n }\n\n /**\n * 初始化日志文件\n * @param projectDir 项目目录\n */\n initLogFile(projectDir: string): void {\n this.logFilePath = path.join(projectDir, \"xiaozhi.log\");\n\n // 确保日志文件存在\n if (!fs.existsSync(this.logFilePath)) {\n fs.writeFileSync(this.logFilePath, \"\");\n }\n\n // 创建写入流,追加模式\n this.writeStream = fs.createWriteStream(this.logFilePath, {\n flags: \"a\",\n encoding: \"utf8\",\n });\n }\n\n /**\n * 记录日志到文件\n * @param level 日志级别\n * @param message 日志消息\n * @param args 额外参数\n */\n private logToFile(level: string, message: string, ...args: any[]): void {\n if (this.writeStream) {\n const timestamp = new Date().toISOString();\n const formattedMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;\n const fullMessage =\n args.length > 0\n ? `${formattedMessage} ${args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \")}`\n : formattedMessage;\n\n this.writeStream.write(`${fullMessage}\\n`);\n }\n }\n\n /**\n * 设置是否启用文件日志\n * @param enable 是否启用\n */\n enableFileLogging(enable: boolean): void {\n if (enable && !this.writeStream && this.logFilePath) {\n this.writeStream = fs.createWriteStream(this.logFilePath, {\n flags: \"a\",\n encoding: \"utf8\",\n });\n } else if (!enable && this.writeStream) {\n this.writeStream.end();\n this.writeStream = null;\n }\n }\n\n /**\n * 日志方法\n */\n info(message: string, ...args: any[]): void {\n this.consolaInstance.info(message, ...args);\n this.logToFile(\"info\", message, ...args);\n }\n\n success(message: string, ...args: any[]): void {\n this.consolaInstance.success(message, ...args);\n this.logToFile(\"success\", message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.consolaInstance.warn(message, ...args);\n this.logToFile(\"warn\", message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.consolaInstance.error(message, ...args);\n this.logToFile(\"error\", message, ...args);\n }\n\n debug(message: string, ...args: any[]): void {\n this.consolaInstance.debug(message, ...args);\n this.logToFile(\"debug\", message, ...args);\n }\n\n log(message: string, ...args: any[]): void {\n this.consolaInstance.log(message, ...args);\n this.logToFile(\"log\", message, ...args);\n }\n\n /**\n * 创建一个带标签的日志实例(已废弃,直接返回原实例)\n * @param tag 标签(不再使用)\n * @deprecated 标签功能已移除\n */\n withTag(tag: string): Logger {\n // 不再添加标签,直接返回共享实例\n return this;\n }\n\n /**\n * 关闭日志文件流\n */\n close(): void {\n if (this.writeStream) {\n this.writeStream.end();\n this.writeStream = null;\n }\n }\n}\n\n// 导出单例实例\nexport const logger = new Logger();\n"],"mappings":";+EAOA,OAA4B,SAAAA,MAAa,gBACzC,OAAOC,MAAa,UACpB,OAAOC,MAAe,KCTtB,OAAS,gBAAAC,EAAc,cAAAC,EAAY,gBAAAC,EAAc,iBAAAC,MAAqB,KACtE,OAAS,WAAAC,EAAS,WAAAC,MAAe,OACjC,OAAS,iBAAAC,MAAqB,MAG9B,IAAMC,EAAYC,EAAQC,EAAc,YAAY,GAAG,CAAC,EAGlDC,EAAwD,CAC5D,kBAAmB,IACnB,iBAAkB,IAClB,kBAAmB,GACrB,EAuDaC,EAAN,MAAMC,CAAc,CAnE3B,MAmE2B,CAAAC,EAAA,sBACzB,OAAe,SACP,kBACA,OAA2B,KAE3B,aAAc,CACpB,KAAK,kBAAoBC,EAAQP,EAAW,6BAA6B,CAC3E,CAKQ,mBAA4B,CAElC,IAAMQ,EAAY,QAAQ,IAAI,oBAAsB,QAAQ,IAAI,EAChE,OAAOD,EAAQC,EAAW,qBAAqB,CACjD,CAKA,OAAc,aAA6B,CACzC,OAAKH,EAAc,WACjBA,EAAc,SAAW,IAAIA,GAExBA,EAAc,QACvB,CAKO,cAAwB,CAC7B,IAAMI,EAAa,KAAK,kBAAkB,EAC1C,OAAOC,EAAWD,CAAU,CAC9B,CAMO,YAAmB,CACxB,GAAI,CAACC,EAAW,KAAK,iBAAiB,EACpC,MAAM,IAAI,MAAM,qFAAwC,EAG1D,GAAI,KAAK,aAAa,EACpB,MAAM,IAAI,MAAM,iHAAsC,EAGxD,IAAMD,EAAa,KAAK,kBAAkB,EAC1CE,EAAa,KAAK,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,EAAQ,GAAG,qBAAsB,CAACiB,EAAQY,IAAY,CACpD9B,EAAO,MACL,kDACEkB,aAAkB,MAAQA,EAAO,QAAU,OAAOA,CAAM,CAC1D,EACF,CACF,CAAC,EAEL,CAtCgBf,EAAAwB,EAAA","names":["spawn","process","WebSocket","copyFileSync","existsSync","readFileSync","writeFileSync","dirname","resolve","fileURLToPath","__dirname","dirname","fileURLToPath","DEFAULT_CONNECTION_CONFIG","ConfigManager","_ConfigManager","__name","resolve","configDir","configPath","existsSync","copyFileSync","configData","readFileSync","config","error","configObj","endpoint","serverName","serverConfig","sc","toolName","ep","newConfig","currentEndpoints","newEndpoints","localConfig","newMcpServers","toolsConfig","enabled","description","configJson","writeFileSync","connectionConfig","newConnectionConfig","interval","timeout","modelScopeConfig","newModelScopeConfig","apiKey","webUIConfig","newWebUIConfig","port","configManager","fs","path","chalk","createConsola","formatDateTime","date","year","month","day","hours","minutes","seconds","__name","Logger","createConsola","isDaemonMode","logObj","levelMap","colorMap","chalk","text","level","colorFn","timestamp","coloredLevel","message","error","projectDir","path","fs","args","formattedMessage","fullMessage","arg","enable","tag","logger","logger","process","MultiEndpointMCPPipe","__name","mcpScript","endpointUrls","url","configManager","error","resolve","connectionPromises","endpoint","endpointUrl","ws","WebSocket","data","message","code","reason","spawn","lines","line","signal","port","statusWs","endpointStatuses","status","setupSignalHandlers","mcpPipe","isDaemon","promise"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var x=Object.defineProperty;var d=(c,t)=>x(c,"name",{value:t,configurable:!0});import{spawn as M}from"child_process";import{
|
|
2
|
-
`)}}enableFileLogging(t){t&&!this.writeStream&&this.logFilePath?this.writeStream=g.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"}):!t&&this.writeStream&&(this.writeStream.end(),this.writeStream=null)}info(t,...e){this.consolaInstance.info(t,...e),this.logToFile("info",t,...e)}success(t,...e){this.consolaInstance.success(t,...e),this.logToFile("success",t,...e)}warn(t,...e){this.consolaInstance.warn(t,...e),this.logToFile("warn",t,...e)}error(t,...e){this.consolaInstance.error(t,...e),this.logToFile("error",t,...e)}debug(t,...e){this.consolaInstance.debug(t,...e),this.logToFile("debug",t,...e)}log(t,...e){this.consolaInstance.log(t,...e),this.logToFile("log",t,...e)}withTag(t){return this}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null)}},P=new f;var E=v(import.meta.url),U=u.dirname(E),i=P.withTag("mcp-server"),S=class extends
|
|
1
|
+
var x=Object.defineProperty;var d=(c,t)=>x(c,"name",{value:t,configurable:!0});import{spawn as M}from"child_process";import{randomUUID as $}from"crypto";import{EventEmitter as T}from"events";import u from"path";import{fileURLToPath as v}from"url";import y from"express";import g from"fs";import w from"path";import m from"chalk";import{createConsola as C}from"consola";function I(c){let t=c.getFullYear(),e=String(c.getMonth()+1).padStart(2,"0"),o=String(c.getDate()).padStart(2,"0"),r=String(c.getHours()).padStart(2,"0"),s=String(c.getMinutes()).padStart(2,"0"),n=String(c.getSeconds()).padStart(2,"0");return`${t}-${e}-${o} ${r}:${s}:${n}`}d(I,"formatDateTime");var f=class{static{d(this,"Logger")}logFilePath=null;writeStream=null;consolaInstance;isDaemonMode;constructor(){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.consolaInstance=C({formatOptions:{date:!1,colors:!0,compact:!0},fancy:!1});let t=this.isDaemonMode;this.consolaInstance.setReporters([{log:d(e=>{let o={info:"INFO",success:"SUCCESS",warn:"WARN",error:"ERROR",debug:"DEBUG",log:"LOG"},r={info:m.blue,success:m.green,warn:m.yellow,error:m.red,debug:m.gray,log:d(h=>h,"log")},s=o[e.type]||e.type.toUpperCase(),n=r[e.type]||(h=>h),a=I(new Date),l=n(`[${s}]`),p=`[${a}] ${l} ${e.args.join(" ")}`;if(!t)try{console.error(p)}catch(h){if(h instanceof Error&&h.message?.includes("EPIPE"))return;throw h}},"log")}])}initLogFile(t){this.logFilePath=w.join(t,"xiaozhi.log"),g.existsSync(this.logFilePath)||g.writeFileSync(this.logFilePath,""),this.writeStream=g.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"})}logToFile(t,e,...o){if(this.writeStream){let s=`[${new Date().toISOString()}] [${t.toUpperCase()}] ${e}`,n=o.length>0?`${s} ${o.map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" ")}`:s;this.writeStream.write(`${n}
|
|
2
|
+
`)}}enableFileLogging(t){t&&!this.writeStream&&this.logFilePath?this.writeStream=g.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"}):!t&&this.writeStream&&(this.writeStream.end(),this.writeStream=null)}info(t,...e){this.consolaInstance.info(t,...e),this.logToFile("info",t,...e)}success(t,...e){this.consolaInstance.success(t,...e),this.logToFile("success",t,...e)}warn(t,...e){this.consolaInstance.warn(t,...e),this.logToFile("warn",t,...e)}error(t,...e){this.consolaInstance.error(t,...e),this.logToFile("error",t,...e)}debug(t,...e){this.consolaInstance.debug(t,...e),this.logToFile("debug",t,...e)}log(t,...e){this.consolaInstance.log(t,...e),this.logToFile("log",t,...e)}withTag(t){return this}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null)}},P=new f;var E=v(import.meta.url),U=u.dirname(E),i=P.withTag("mcp-server"),S=class extends T{static{d(this,"MCPServer")}app;server=null;clients=new Map;mcpProxy=null;port;constructor(t=3e3){super(),this.port=t,this.app=y(),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){this.app.use(y.json()),this.app.use(y.urlencoded({extended:!0})),this.app.use((t,e,o)=>{e.header("Access-Control-Allow-Origin","*"),e.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.header("Access-Control-Allow-Headers","Content-Type, Accept"),e.header("Cache-Control","no-cache"),o()})}setupRoutes(){this.app.get("/sse",(t,e)=>{let o=Date.now().toString(),r=$();e.setHeader("Content-Type","text/event-stream"),e.setHeader("Cache-Control","no-cache, no-transform"),e.setHeader("Connection","keep-alive"),e.setHeader("X-Accel-Buffering","no"),this.clients.set(r,{id:o,sessionId:r,response:e}),i.info(`MCP client connected: ${o} (session: ${r})`),e.write(`event: endpoint
|
|
3
3
|
data: /messages?sessionId=${r}
|
|
4
4
|
|
|
5
5
|
`),t.on("close",()=>{this.clients.delete(r),i.info(`MCP client disconnected: ${o} (session: ${r})`)})}),this.app.post("/messages",async(t,e)=>{try{let o=t.query.sessionId,r=t.body;if(i.info(`Received message via SSE transport (session: ${o}):`,JSON.stringify(r)),!o||!this.clients.has(o)){e.status(400).json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid or missing sessionId"},id:r.id});return}if(!this.mcpProxy){e.status(503).json({jsonrpc:"2.0",error:{code:-32603,message:"MCP proxy not running"},id:r.id});return}if(r.id===void 0)i.info(`Forwarding notification: ${r.method}`),this.mcpProxy.stdin.write(`${JSON.stringify(r)}
|
|
6
6
|
`),e.status(202).send();else{let s=await this.forwardToProxy(r),n=this.clients.get(o);n&&this.sendToClient(n,s),e.status(202).send()}}catch(o){i.error("SSE message error:",o),e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:o instanceof Error?o.message:"Internal error"},id:t.body.id})}}),this.app.post("/rpc",async(t,e)=>{try{let o=t.body;if(i.debug("Received RPC message:",o),!this.mcpProxy){e.status(503).json({jsonrpc:"2.0",error:{code:-32603,message:"MCP proxy not running"},id:o.id});return}let r=await this.forwardToProxy(o);e.json(r)}catch(o){i.error("RPC error:",o),e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:o instanceof Error?o.message:"Internal error"},id:t.body.id})}}),this.app.get("/health",(t,e)=>{e.json({status:"ok",mode:"mcp-server",proxy:this.mcpProxy?"running":"stopped",clients:this.clients.size})})}async forwardToProxy(t){return new Promise((e,o)=>{if(!this.mcpProxy||!this.mcpProxy.stdin||!this.mcpProxy.stdout){o(new Error("MCP proxy not available"));return}let r,s=d(n=>{try{let a=n.toString().split(`
|
|
7
|
-
`).filter(l=>l.trim());for(let l of a)try{let p=JSON.parse(l);if(i.debug(`Received response from proxy: ${l}`),p.id===t.id||t.method==="notifications/initialized"&&!p.id){clearTimeout(r),this.mcpProxy?.stdout?.removeListener("data",s),e(p);return}}catch{i.debug(`Non-JSON line from proxy: ${l}`)}}catch(a){clearTimeout(r),o(a)}},"messageHandler");this.mcpProxy.stdout.on("data",s),i.info(`Forwarding message to proxy: ${JSON.stringify(t)}`),this.mcpProxy.stdin.write(`${JSON.stringify(t)}
|
|
7
|
+
`).filter(l=>l.trim());for(let l of a)try{let p=JSON.parse(l);if(i.debug(`Received response from proxy: ${l}`),p.id===t.id||t.method==="notifications/initialized"&&!p.id){r&&clearTimeout(r),this.mcpProxy?.stdout?.removeListener("data",s),e(p);return}}catch{i.debug(`Non-JSON line from proxy: ${l}`)}}catch(a){r&&clearTimeout(r),o(a)}},"messageHandler");this.mcpProxy.stdout.on("data",s),i.info(`Forwarding message to proxy: ${JSON.stringify(t)}`),this.mcpProxy.stdin.write(`${JSON.stringify(t)}
|
|
8
8
|
`),r=setTimeout(()=>{this.mcpProxy?.stdout?.removeListener("data",s),i.warn(`Request timeout for message id: ${t.id}, method: ${t.method} - This may be normal if the response was already sent via SSE`),e({jsonrpc:"2.0",id:t.id,result:{_timeout:!0,message:"Response may have been sent via SSE"}})},3e4)})}sendToClient(t,e){try{let o=`event: message
|
|
9
9
|
data: ${JSON.stringify(e)}
|
|
10
10
|
|