xiaozhi-client 1.5.0 → 1.5.1

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.
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- var A=Object.defineProperty;var c=(a,e)=>A(a,"name",{value:e,configurable:!0});import{spawn as Z}from"child_process";import{readFileSync as z}from"fs";import{dirname as Y,resolve as Q}from"path";import f from"process";import{fileURLToPath as N}from"url";import{copyFileSync as _,existsSync as O,readFileSync as q,writeFileSync as F}from"fs";import{dirname as J,resolve as R}from"path";import{fileURLToPath as D}from"url";var U=J(D(import.meta.url)),P={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},T=class a{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;constructor(){this.defaultConfigPath=R(U,"xiaozhi.config.default.json")}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return R(e,"xiaozhi.config.json")}static getInstance(){return a.instance||(a.instance=new a),a.instance}configExists(){let e=this.getConfigFilePath();return O(e)}initConfig(){if(!O(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();_(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=q(e,"utf8"),o=JSON.parse(t);return this.validateConfig(o),o}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 o of t.mcpEndpoint)if(typeof o!="string"||o.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[o,i]of Object.entries(t.mcpServers)){if(!i||typeof i!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o} \u65E0\u6548`);let n=i;if(n.url&&typeof n.url=="string"){if(n.type&&n.type!=="sse"&&n.type!=="streamable-http")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.type \u5FC5\u987B\u662F "sse" \u6216 "streamable-http"`)}else{if(!n.command||typeof n.command!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.command \u65E0\u6548`);if(!Array.isArray(n.args))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.args \u5FC5\u987B\u662F\u6570\u7EC4`);if(n.env&&typeof n.env!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.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 i of e)if(!i||typeof i!="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 o={...this.getConfig(),mcpEndpoint:e};this.saveConfig(o)}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(),o=this.getMcpEndpoints();if(o.includes(e))throw new Error(`MCP \u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728`);let i=[...o,e],n={...t,mcpEndpoint:i};this.saveConfig(n)}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(),o=this.getMcpEndpoints();if(o.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(o.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let n=o.filter(l=>l!==e),s={...t,mcpEndpoint:n};this.saveConfig(s)}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 n=t;if(!n.command||typeof n.command!="string")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 command \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(n.args))throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4");if(n.env&&typeof n.env!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61")}let o=this.getConfig(),i={...o,mcpServers:{...o.mcpServers,[e]:t}};this.saveConfig(i)}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 o={...t.mcpServers};delete o[e];let i={...t,mcpServers:o};this.saveConfig(i)}updateServerToolsConfig(e,t){let i={...this.getConfig()};i.mcpServerConfig||(i.mcpServerConfig={}),i.mcpServerConfig[e]={tools:t},this.saveConfig(i)}setToolEnabled(e,t,o,i){let s={...this.getConfig()};s.mcpServerConfig||(s.mcpServerConfig={}),s.mcpServerConfig[e]||(s.mcpServerConfig[e]={tools:{}}),s.mcpServerConfig[e].tools[t]={enable:o,...i&&{description:i}},this.saveConfig(s)}saveConfig(e){try{this.validateConfig(e);let t=this.getConfigFilePath(),o=JSON.stringify(e,null,2);F(t,o,"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??P.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??P.heartbeatTimeout,reconnectInterval:t.reconnectInterval??P.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(e){let t=this.getConfig(),i={...t.connection||{},...e},n={...t,connection:i};this.saveConfig(n)}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(),i={...t.modelscope||{},...e},n={...t,modelscope:i};this.saveConfig(n)}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(),i={...t.webUI||{},...e},n={...t,webUI:i};this.saveConfig(n)}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})}},g=T.getInstance();import v from"fs";import k from"path";import S from"chalk";import{createConsola as L}from"consola";function W(a){let e=a.getFullYear(),t=String(a.getMonth()+1).padStart(2,"0"),o=String(a.getDate()).padStart(2,"0"),i=String(a.getHours()).padStart(2,"0"),n=String(a.getMinutes()).padStart(2,"0"),s=String(a.getSeconds()).padStart(2,"0");return`${e}-${t}-${o} ${i}:${n}:${s}`}c(W,"formatDateTime");var E=class{static{c(this,"Logger")}logFilePath=null;writeStream=null;consolaInstance;isDaemonMode;constructor(){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.consolaInstance=L({formatOptions:{date:!1,colors:!0,compact:!0},fancy:!1});let e=this.isDaemonMode;this.consolaInstance.setReporters([{log:c(t=>{let o={info:"INFO",success:"SUCCESS",warn:"WARN",error:"ERROR",debug:"DEBUG",log:"LOG"},i={info:S.blue,success:S.green,warn:S.yellow,error:S.red,debug:S.gray,log:c(C=>C,"log")},n=o[t.type]||t.type.toUpperCase(),s=i[t.type]||(C=>C),l=W(new Date),d=s(`[${n}]`),b=`[${l}] ${d} ${t.args.join(" ")}`;if(!e)try{console.error(b)}catch(C){if(C instanceof Error&&C.message?.includes("EPIPE"))return;throw C}},"log")}])}initLogFile(e){this.logFilePath=k.join(e,"xiaozhi.log"),v.existsSync(this.logFilePath)||v.writeFileSync(this.logFilePath,""),this.writeStream=v.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"})}logToFile(e,t,...o){if(this.writeStream){let n=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${t}`,s=o.length>0?`${n} ${o.map(l=>typeof l=="object"?JSON.stringify(l):String(l)).join(" ")}`:n;this.writeStream.write(`${s}
3
- `)}}enableFileLogging(e){e&&!this.writeStream&&this.logFilePath?this.writeStream=v.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 E;import{Client as H}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as B}from"@modelcontextprotocol/sdk/client/sse.js";import{EventSource as G}from"eventsource";global.EventSource=G;var h=u.withTag("ModelScopeMCP"),w=class{static{c(this,"ModelScopeMCPClient")}name;config;client=null;transport=null;initialized=!1;tools=[];originalTools=[];constructor(e,t){this.name=e,this.config=t}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async start(){h.info(`\u6B63\u5728\u542F\u52A8 ModelScope MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{let e=g.getModelScopeApiKey();if(!e||e==="")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 t={eventSourceInit:{fetch:c(async(o,i)=>{let n={...i?.headers,Authorization:`Bearer ${e}`};return fetch(o,{...i,headers:n})},"fetch")},requestInit:{headers:{Authorization:`Bearer ${e}`}}};this.transport=new B(new URL(this.config.url),t),this.client=new H({name:"xiaozhi-modelscope-client",version:"1.0.0"},{capabilities:{}}),h.info(`\u6B63\u5728\u8FDE\u63A5\u5230 ${this.config.url}`),await this.client.connect(this.transport),h.info(`\u6210\u529F\u8FDE\u63A5\u5230 ModelScope MCP \u670D\u52A1\u5668\uFF1A${this.name}`),await this.refreshTools(),this.initialized=!0,h.info(`${this.name} ModelScope \u5BA2\u6237\u7AEF\u5DF2\u5C31\u7EEA\uFF0C\u5171 ${this.tools.length} \u4E2A\u5DE5\u5177`)}catch(e){throw h.error(`\u542F\u52A8 ModelScope MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let e=await this.client.listTools();this.originalTools=e.tools||[];let t=this.originalTools.map(o=>({...o,name:this.generatePrefixedToolName(o.name)}));this.tools=this.filterEnabledTools(t),await this.updateToolsConfig(),h.info(`${this.name} \u52A0\u8F7D\u4E86 ${this.originalTools.length} \u4E2A\u5DE5\u5177\uFF1A${this.originalTools.map(o=>o.name).join(", ")}`),h.info(`${this.name} \u542F\u7528\u4E86 ${this.tools.length} \u4E2A\u5DE5\u5177\uFF1A${this.tools.map(o=>o.name).join(", ")}`)}catch(e){h.error(`\u4ECE ${this.name} \u83B7\u53D6\u5DE5\u5177\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),this.tools=[],this.originalTools=[]}}filterEnabledTools(e){return e.filter(t=>{let o=this.getOriginalToolName(t.name);return o?g.isToolEnabled(this.name,o):!0})}async updateToolsConfig(){try{let e=g.getServerToolsConfig(this.name),t={};for(let i of this.originalTools){let n=e[i.name];t[i.name]={description:i.description||"",enable:n?.enable!==!1}}(Object.keys(t).some(i=>{let n=e[i],s=t[i];return!n||n.enable!==s.enable||n.description!==s.description})||Object.keys(e).length===0)&&(g.updateServerToolsConfig(this.name,t),h.info(`${this.name} \u5DF2\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E`))}catch(e){h.error(`\u66F4\u65B0 ${this.name} \u7684\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async callTool(e,t){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let o=this.getOriginalToolName(e);if(!o)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);h.info(`\u8C03\u7528 ModelScope \u5DE5\u5177 ${o}\uFF0C\u53C2\u6570\uFF1A${JSON.stringify(t)}`);let i=await this.client.callTool({name:o,arguments:t});return h.info(`ModelScope \u5DE5\u5177\u8C03\u7528\u8FD4\u56DE: ${JSON.stringify(i).substring(0,500)}...`),i}catch(o){throw h.error(`\u5728 ${this.name} \u4E0A\u8C03\u7528\u5DE5\u5177 ${e} \u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),o}}async stop(){if(this.client){h.info(`\u6B63\u5728\u505C\u6B62 ${this.name} ModelScope \u5BA2\u6237\u7AEF`);try{await this.client.close()}catch(e){h.error(`\u5173\u95ED\u5BA2\u6237\u7AEF\u65F6\u51FA\u9519\uFF1A${e instanceof Error?e.message:String(e)}`)}this.client=null,this.transport=null}this.initialized=!1}};import{Client as K}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as V}from"@modelcontextprotocol/sdk/client/sse.js";import{EventSource as X}from"eventsource";global.EventSource=X;var p=u.withTag("SSEMCP"),y=class{static{c(this,"SSEMCPClient")}name;config;client=null;transport=null;initialized=!1;tools=[];originalTools=[];constructor(e,t){this.name=e,this.config=t}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}filterEnabledTools(e){return e.filter(t=>{let o=this.getOriginalToolName(t.name);return o?g.isToolEnabled(this.name,o):!1})}async updateToolsConfig(){try{let e=g.getServerToolsConfig(this.name),t={};for(let o of this.originalTools){let i=e[o.name];t[o.name]={description:o.description||i?.description||"",enable:i?.enable!==!1}}for(let[o,i]of Object.entries(e))t[o]||(t[o]=i);g.updateServerToolsConfig(this.name,t)}catch(e){p.debug(`\u66F4\u65B0 ${this.name} \u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async start(){p.info(`\u6B63\u5728\u542F\u52A8 SSE MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{this.transport=new V(new URL(this.config.url)),this.client=new K({name:"xiaozhi-sse-client",version:"1.0.0"},{capabilities:{}}),p.info(`\u6B63\u5728\u8FDE\u63A5\u5230 ${this.config.url}`),await this.client.connect(this.transport),p.info(`\u6210\u529F\u8FDE\u63A5\u5230 SSE MCP \u670D\u52A1\u5668\uFF1A${this.name}`),await this.refreshTools(),this.initialized=!0,p.info(`${this.name} SSE \u5BA2\u6237\u7AEF\u5DF2\u5C31\u7EEA\uFF0C\u5171 ${this.tools.length} \u4E2A\u5DE5\u5177`)}catch(e){throw p.error(`\u542F\u52A8 SSE MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let e=await this.client.listTools();this.originalTools=e.tools||[];let t=this.originalTools.map(o=>({...o,name:this.generatePrefixedToolName(o.name)}));this.tools=this.filterEnabledTools(t),await this.updateToolsConfig(),p.info(`${this.name} \u52A0\u8F7D\u4E86 ${this.originalTools.length} \u4E2A\u5DE5\u5177\uFF1A${this.originalTools.map(o=>o.name).join(", ")}`),p.info(`${this.name} \u542F\u7528\u4E86 ${this.tools.length} \u4E2A\u5DE5\u5177\uFF1A${this.tools.map(o=>o.name).join(", ")}`)}catch(e){throw p.error(`\u5237\u65B0 ${this.name} \u5DE5\u5177\u5217\u8868\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async callTool(e,t){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let o=this.getOriginalToolName(e);if(!o)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);p.info(`\u8C03\u7528 SSE \u5DE5\u5177 ${o}\uFF0C\u53C2\u6570\uFF1A${JSON.stringify(t)}`);let i=await this.client.callTool({name:o,arguments:t});return p.info(`SSE \u5DE5\u5177\u8C03\u7528\u8FD4\u56DE: ${JSON.stringify(i).substring(0,500)}...`),i}catch(o){throw p.error(`\u5728 ${this.name} \u4E0A\u8C03\u7528\u5DE5\u5177 ${e} \u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),o}}async stop(){p.info(`\u6B63\u5728\u505C\u6B62 SSE MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{this.client&&(await this.client.close(),this.client=null),this.transport&&(this.transport=null),p.info(`SSE MCP \u5BA2\u6237\u7AEF ${this.name} \u5DF2\u505C\u6B62`)}catch(e){p.error(`\u505C\u6B62 SSE MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}finally{this.initialized=!1}}};var m=u.withTag("StreamableHTTPMCP"),$=class{static{c(this,"StreamableHTTPMCPClient")}name;config;requestId=1;initialized=!1;tools=[];originalTools=[];constructor(e,t){this.name=e,this.config=t}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async sendRequest(e,t){let o={jsonrpc:"2.0",method:e,params:t,id:this.requestId++};m.debug(`\u53D1\u9001\u8BF7\u6C42\u5230 ${this.name}: ${JSON.stringify(o)}`);try{let i=(await import("node-fetch")).default,n=await i(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify(o)});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);let s=await n.json();if(s.error)throw new Error(`JSON-RPC error: ${s.error.message} (code: ${s.error.code})`);return s.result}catch(i){throw m.error(`\u8BF7\u6C42\u5931\u8D25 (${e}): ${i instanceof Error?i.message:String(i)}`),i}}async sendNotification(e,t){let o={jsonrpc:"2.0",method:e,params:t};m.debug(`\u53D1\u9001\u901A\u77E5\u5230 ${this.name}: ${JSON.stringify(o)}`);try{let i=(await import("node-fetch")).default,n=await i(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify(o)});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);m.debug(`\u901A\u77E5 ${e} \u53D1\u9001\u6210\u529F`)}catch(i){throw m.debug(`\u901A\u77E5\u53D1\u9001\u5931\u8D25 (${e}): ${i instanceof Error?i.message:String(i)}`),i}}async start(){m.info(`\u6B63\u5728\u542F\u52A8 Streamable HTTP MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{tools:{}},clientInfo:{name:"xiaozhi-streamable-http-client",version:"1.0.0"}});try{await this.sendNotification("notifications/initialized")}catch(t){m.debug(`${this.name} \u4E0D\u652F\u6301 notifications/initialized: ${t}`)}let e=await this.sendRequest("tools/list");e?.tools&&(this.originalTools=e.tools,await this.updateToolsConfig(),this.tools=this.originalTools.filter(t=>g.isToolEnabled(this.name,t.name)).map(t=>({...t,name:this.generatePrefixedToolName(t.name)})),m.info(`Streamable HTTP MCP \u5BA2\u6237\u7AEF ${this.name} \u5DF2\u521D\u59CB\u5316\uFF0C\u5305\u542B ${this.tools.length}/${this.originalTools.length} \u4E2A\u5DF2\u542F\u7528\u7684\u5DE5\u5177`)),this.initialized=!0}catch(e){throw m.error(`\u542F\u52A8 Streamable HTTP MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{let e=await this.sendRequest("tools/list");e?.tools&&(this.originalTools=e.tools,await this.updateToolsConfig(),this.tools=this.originalTools.filter(t=>g.isToolEnabled(this.name,t.name)).map(t=>({...t,name:this.generatePrefixedToolName(t.name)})),m.info(`\u5DF2\u5237\u65B0 ${this.name} \u7684\u5DE5\u5177\u5217\u8868\uFF0C\u5305\u542B ${this.tools.length}/${this.originalTools.length} \u4E2A\u5DF2\u542F\u7528\u7684\u5DE5\u5177`))}catch(e){m.error(`\u5237\u65B0 ${this.name} \u7684\u5DE5\u5177\u5217\u8868\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async callTool(e,t){try{let o=this.getOriginalToolName(e);if(!o)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);return await this.sendRequest("tools/call",{name:o,arguments:t})}catch(o){throw m.error(`\u5728 ${this.name} \u4E0A\u8C03\u7528\u5DE5\u5177 ${e} \u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),o}}async updateToolsConfig(){try{let e=g.getServerToolsConfig(this.name),t={};for(let i of this.originalTools){let n=e[i.name];t[i.name]={description:i.description||"",enable:n?.enable!==!1}}(Object.keys(t).some(i=>{let n=e[i],s=t[i];return!n||n.enable!==s.enable||n.description!==s.description})||Object.keys(e).length===0)&&(g.updateServerToolsConfig(this.name,t),m.info(`${this.name} \u5DF2\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E`))}catch(e){m.error(`\u66F4\u65B0 ${this.name} \u7684\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async stop(){m.info(`\u6B63\u5728\u505C\u6B62 ${this.name} \u5BA2\u6237\u7AEF`),this.initialized=!1}};var ee=Y(N(import.meta.url)),r=u.withTag("MCPProxy"),j=f.env.XIAOZHI_CONFIG_DIR||f.cwd();u.initLogFile(j);u.enableFileLogging(!0);r.info(`\u65E5\u5FD7\u6587\u4EF6\u5DF2\u521D\u59CB\u5316: ${j}/xiaozhi.log`);var M=class{static{c(this,"MCPClient")}name;config;process;initialized;tools;originalTools;requestId;pendingRequests;messageBuffer;constructor(e,t){this.name=e,this.config=t,this.process=null,this.initialized=!1,this.tools=[],this.originalTools=[],this.requestId=1,this.pendingRequests=new Map,this.messageBuffer=""}resolveCommand(e,t){if(f.platform==="win32"){if(e==="npm"||e==="npx")return{resolvedCommand:`${e}.cmd`,resolvedArgs:t};if(e==="uvx")return{resolvedCommand:"uvx.bat",resolvedArgs:t}}return{resolvedCommand:e,resolvedArgs:t}}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async start(){r.info(`\u6B63\u5728\u542F\u52A8 MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);let{command:e,args:t,env:o}=this.config,{resolvedCommand:i,resolvedArgs:n}=this.resolveCommand(e,t),s={stdio:["pipe","pipe","pipe"]},l=f.env.XIAOZHI_CONFIG_DIR||f.cwd();s.cwd=l,o?s.env={...f.env,...o}:s.env={...f.env},f.platform==="win32"&&(e==="npm"||e==="npx"||e==="uvx")&&(s.shell=!0),r.debug(`${this.name} \u6B63\u5728\u751F\u6210\u8FDB\u7A0B\uFF1A${i} ${n.join(" ")} \u5DE5\u4F5C\u76EE\u5F55\uFF1A${s.cwd}`),r.debug(`${this.name} \u5E73\u53F0\uFF1A${f.platform}\uFF0Cshell \u6A21\u5F0F\uFF1A${s.shell||!1}`),this.process=Z(i,n,s),this.process.stdout?.on("data",d=>{this.handleStdoutData(d.toString())}),this.process.stderr?.on("data",d=>{r.debug(`${this.name} \u6807\u51C6\u9519\u8BEF\u8F93\u51FA\uFF1A${d.toString().trim()}`)}),this.process.on("exit",(d,b)=>{r.error(`${this.name} \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u9000\u51FA\u7801\uFF1A${d}\uFF0C\u4FE1\u53F7\uFF1A${b}`),this.initialized=!1}),this.process.on("error",d=>{r.error(`${this.name} \u8FDB\u7A0B\u9519\u8BEF\uFF1A${d.message}`),this.initialized=!1}),await this.initialize()}handleStdoutData(e){this.messageBuffer=`${this.messageBuffer}${e}`;let t=this.messageBuffer.split(`
2
+ var A=Object.defineProperty;var g=(a,e)=>A(a,"name",{value:e,configurable:!0});import{spawn as Z}from"child_process";import{readFileSync as z}from"fs";import{dirname as Y,resolve as Q}from"path";import f from"process";import{fileURLToPath as N}from"url";import{copyFileSync as _,existsSync as x,readFileSync as q,writeFileSync as F}from"fs";import{dirname as J,resolve as R}from"path";import{fileURLToPath as D}from"url";var k=J(D(import.meta.url)),T={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},P=class a{static{g(this,"ConfigManager")}static instance;defaultConfigPath;config=null;constructor(){this.defaultConfigPath=R(k,"xiaozhi.config.default.json")}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return R(e,"xiaozhi.config.json")}static getInstance(){return a.instance||(a.instance=new a),a.instance}configExists(){let e=this.getConfigFilePath();return x(e)}initConfig(){if(!x(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();_(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=q(e,"utf8"),o=JSON.parse(t);return this.validateConfig(o),o}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 o of t.mcpEndpoint)if(typeof o!="string"||o.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[o,i]of Object.entries(t.mcpServers)){if(!i||typeof i!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o} \u65E0\u6548`);let n=i;if(n.url&&typeof n.url=="string"){if(n.type&&n.type!=="sse"&&n.type!=="streamable-http")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.type \u5FC5\u987B\u662F "sse" \u6216 "streamable-http"`)}else{if(!n.command||typeof n.command!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.command \u65E0\u6548`);if(!Array.isArray(n.args))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.args \u5FC5\u987B\u662F\u6570\u7EC4`);if(n.env&&typeof n.env!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${o}.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 i of e)if(!i||typeof i!="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 o={...this.getConfig(),mcpEndpoint:e};this.saveConfig(o)}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(),o=this.getMcpEndpoints();if(o.includes(e))throw new Error(`MCP \u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728`);let i=[...o,e],n={...t,mcpEndpoint:i};this.saveConfig(n)}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(),o=this.getMcpEndpoints();if(o.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(o.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let n=o.filter(l=>l!==e),s={...t,mcpEndpoint:n};this.saveConfig(s)}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 n=t;if(!n.command||typeof n.command!="string")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 command \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(n.args))throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4");if(n.env&&typeof n.env!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61")}let o=this.getConfig(),i={...o,mcpServers:{...o.mcpServers,[e]:t}};this.saveConfig(i)}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 o={...t.mcpServers};delete o[e];let i={...t,mcpServers:o};this.saveConfig(i)}updateServerToolsConfig(e,t){let i={...this.getConfig()};i.mcpServerConfig||(i.mcpServerConfig={}),Object.keys(t).length===0?delete i.mcpServerConfig[e]:i.mcpServerConfig[e]={tools:t},this.saveConfig(i)}removeServerToolsConfig(e){let o={...this.getConfig()};o.mcpServerConfig&&(delete o.mcpServerConfig[e],this.saveConfig(o))}setToolEnabled(e,t,o,i){let s={...this.getConfig()};s.mcpServerConfig||(s.mcpServerConfig={}),s.mcpServerConfig[e]||(s.mcpServerConfig[e]={tools:{}}),s.mcpServerConfig[e].tools[t]={enable:o,...i&&{description:i}},this.saveConfig(s)}saveConfig(e){try{this.validateConfig(e);let t=this.getConfigFilePath(),o=JSON.stringify(e,null,2);F(t,o,"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??T.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??T.heartbeatTimeout,reconnectInterval:t.reconnectInterval??T.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(e){let t=this.getConfig(),i={...t.connection||{},...e},n={...t,connection:i};this.saveConfig(n)}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(),i={...t.modelscope||{},...e},n={...t,modelscope:i};this.saveConfig(n)}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(),i={...t.webUI||{},...e},n={...t,webUI:i};this.saveConfig(n)}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})}},c=P.getInstance();import v from"fs";import U from"path";import S from"chalk";import{createConsola as L}from"consola";function W(a){let e=a.getFullYear(),t=String(a.getMonth()+1).padStart(2,"0"),o=String(a.getDate()).padStart(2,"0"),i=String(a.getHours()).padStart(2,"0"),n=String(a.getMinutes()).padStart(2,"0"),s=String(a.getSeconds()).padStart(2,"0");return`${e}-${t}-${o} ${i}:${n}:${s}`}g(W,"formatDateTime");var E=class{static{g(this,"Logger")}logFilePath=null;writeStream=null;consolaInstance;isDaemonMode;constructor(){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.consolaInstance=L({formatOptions:{date:!1,colors:!0,compact:!0},fancy:!1});let e=this.isDaemonMode;this.consolaInstance.setReporters([{log:g(t=>{let o={info:"INFO",success:"SUCCESS",warn:"WARN",error:"ERROR",debug:"DEBUG",log:"LOG"},i={info:S.blue,success:S.green,warn:S.yellow,error:S.red,debug:S.gray,log:g(C=>C,"log")},n=o[t.type]||t.type.toUpperCase(),s=i[t.type]||(C=>C),l=W(new Date),d=s(`[${n}]`),b=`[${l}] ${d} ${t.args.join(" ")}`;if(!e)try{console.error(b)}catch(C){if(C instanceof Error&&C.message?.includes("EPIPE"))return;throw C}},"log")}])}initLogFile(e){this.logFilePath=U.join(e,"xiaozhi.log"),v.existsSync(this.logFilePath)||v.writeFileSync(this.logFilePath,""),this.writeStream=v.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"})}logToFile(e,t,...o){if(this.writeStream){let n=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${t}`,s=o.length>0?`${n} ${o.map(l=>typeof l=="object"?JSON.stringify(l):String(l)).join(" ")}`:n;this.writeStream.write(`${s}
3
+ `)}}enableFileLogging(e){e&&!this.writeStream&&this.logFilePath?this.writeStream=v.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 E;import{Client as H}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as B}from"@modelcontextprotocol/sdk/client/sse.js";import{EventSource as G}from"eventsource";global.EventSource=G;var h=u.withTag("ModelScopeMCP"),y=class{static{g(this,"ModelScopeMCPClient")}name;config;client=null;transport=null;initialized=!1;tools=[];originalTools=[];constructor(e,t){this.name=e,this.config=t}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async start(){h.info(`\u6B63\u5728\u542F\u52A8 ModelScope MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{let e=c.getModelScopeApiKey();if(!e||e==="")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 t={eventSourceInit:{fetch:g(async(o,i)=>{let n={...i?.headers,Authorization:`Bearer ${e}`};return fetch(o,{...i,headers:n})},"fetch")},requestInit:{headers:{Authorization:`Bearer ${e}`}}};this.transport=new B(new URL(this.config.url),t),this.client=new H({name:"xiaozhi-modelscope-client",version:"1.0.0"},{capabilities:{}}),h.info(`\u6B63\u5728\u8FDE\u63A5\u5230 ${this.config.url}`),await this.client.connect(this.transport),h.info(`\u6210\u529F\u8FDE\u63A5\u5230 ModelScope MCP \u670D\u52A1\u5668\uFF1A${this.name}`),await this.refreshTools(),this.initialized=!0,h.info(`${this.name} ModelScope \u5BA2\u6237\u7AEF\u5DF2\u5C31\u7EEA\uFF0C\u5171 ${this.tools.length} \u4E2A\u5DE5\u5177`)}catch(e){throw h.error(`\u542F\u52A8 ModelScope MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let e=await this.client.listTools();this.originalTools=e.tools||[];let t=this.originalTools.map(o=>({...o,name:this.generatePrefixedToolName(o.name)}));this.tools=this.filterEnabledTools(t),await this.updateToolsConfig(),h.info(`${this.name} \u52A0\u8F7D\u4E86 ${this.originalTools.length} \u4E2A\u5DE5\u5177\uFF1A${this.originalTools.map(o=>o.name).join(", ")}`),h.info(`${this.name} \u542F\u7528\u4E86 ${this.tools.length} \u4E2A\u5DE5\u5177\uFF1A${this.tools.map(o=>o.name).join(", ")}`)}catch(e){h.error(`\u4ECE ${this.name} \u83B7\u53D6\u5DE5\u5177\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),this.tools=[],this.originalTools=[]}}filterEnabledTools(e){return e.filter(t=>{let o=this.getOriginalToolName(t.name);return o?c.isToolEnabled(this.name,o):!0})}async updateToolsConfig(){try{let e=c.getServerToolsConfig(this.name),t={};for(let i of this.originalTools){let n=e[i.name];t[i.name]={description:i.description||"",enable:n?.enable!==!1}}(Object.keys(t).some(i=>{let n=e[i],s=t[i];return!n||n.enable!==s.enable||n.description!==s.description})||Object.keys(e).length===0)&&(c.updateServerToolsConfig(this.name,t),h.info(`${this.name} \u5DF2\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E`))}catch(e){h.error(`\u66F4\u65B0 ${this.name} \u7684\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async callTool(e,t){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let o=this.getOriginalToolName(e);if(!o)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);h.info(`\u8C03\u7528 ModelScope \u5DE5\u5177 ${o}\uFF0C\u53C2\u6570\uFF1A${JSON.stringify(t)}`);let i=await this.client.callTool({name:o,arguments:t});return h.info(`ModelScope \u5DE5\u5177\u8C03\u7528\u8FD4\u56DE: ${JSON.stringify(i).substring(0,500)}...`),i}catch(o){throw h.error(`\u5728 ${this.name} \u4E0A\u8C03\u7528\u5DE5\u5177 ${e} \u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),o}}async stop(){if(this.client){h.info(`\u6B63\u5728\u505C\u6B62 ${this.name} ModelScope \u5BA2\u6237\u7AEF`);try{await this.client.close()}catch(e){h.error(`\u5173\u95ED\u5BA2\u6237\u7AEF\u65F6\u51FA\u9519\uFF1A${e instanceof Error?e.message:String(e)}`)}this.client=null,this.transport=null}this.initialized=!1}};import{Client as K}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as V}from"@modelcontextprotocol/sdk/client/sse.js";import{EventSource as X}from"eventsource";global.EventSource=X;var p=u.withTag("SSEMCP"),w=class{static{g(this,"SSEMCPClient")}name;config;client=null;transport=null;initialized=!1;tools=[];originalTools=[];constructor(e,t){this.name=e,this.config=t}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}filterEnabledTools(e){return e.filter(t=>{let o=this.getOriginalToolName(t.name);return o?c.isToolEnabled(this.name,o):!1})}async updateToolsConfig(){try{let e=c.getServerToolsConfig(this.name),t={};for(let o of this.originalTools){let i=e[o.name];t[o.name]={description:o.description||i?.description||"",enable:i?.enable!==!1}}for(let[o,i]of Object.entries(e))t[o]||(t[o]=i);c.updateServerToolsConfig(this.name,t)}catch(e){p.debug(`\u66F4\u65B0 ${this.name} \u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async start(){p.info(`\u6B63\u5728\u542F\u52A8 SSE MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{this.transport=new V(new URL(this.config.url)),this.client=new K({name:"xiaozhi-sse-client",version:"1.0.0"},{capabilities:{}}),p.info(`\u6B63\u5728\u8FDE\u63A5\u5230 ${this.config.url}`),await this.client.connect(this.transport),p.info(`\u6210\u529F\u8FDE\u63A5\u5230 SSE MCP \u670D\u52A1\u5668\uFF1A${this.name}`),await this.refreshTools(),this.initialized=!0,p.info(`${this.name} SSE \u5BA2\u6237\u7AEF\u5DF2\u5C31\u7EEA\uFF0C\u5171 ${this.tools.length} \u4E2A\u5DE5\u5177`)}catch(e){throw p.error(`\u542F\u52A8 SSE MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let e=await this.client.listTools();this.originalTools=e.tools||[];let t=this.originalTools.map(o=>({...o,name:this.generatePrefixedToolName(o.name)}));this.tools=this.filterEnabledTools(t),await this.updateToolsConfig(),p.info(`${this.name} \u52A0\u8F7D\u4E86 ${this.originalTools.length} \u4E2A\u5DE5\u5177\uFF1A${this.originalTools.map(o=>o.name).join(", ")}`),p.info(`${this.name} \u542F\u7528\u4E86 ${this.tools.length} \u4E2A\u5DE5\u5177\uFF1A${this.tools.map(o=>o.name).join(", ")}`)}catch(e){throw p.error(`\u5237\u65B0 ${this.name} \u5DE5\u5177\u5217\u8868\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async callTool(e,t){try{if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");let o=this.getOriginalToolName(e);if(!o)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);p.info(`\u8C03\u7528 SSE \u5DE5\u5177 ${o}\uFF0C\u53C2\u6570\uFF1A${JSON.stringify(t)}`);let i=await this.client.callTool({name:o,arguments:t});return p.info(`SSE \u5DE5\u5177\u8C03\u7528\u8FD4\u56DE: ${JSON.stringify(i).substring(0,500)}...`),i}catch(o){throw p.error(`\u5728 ${this.name} \u4E0A\u8C03\u7528\u5DE5\u5177 ${e} \u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),o}}async stop(){p.info(`\u6B63\u5728\u505C\u6B62 SSE MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{this.client&&(await this.client.close(),this.client=null),this.transport&&(this.transport=null),p.info(`SSE MCP \u5BA2\u6237\u7AEF ${this.name} \u5DF2\u505C\u6B62`)}catch(e){p.error(`\u505C\u6B62 SSE MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}finally{this.initialized=!1}}};var m=u.withTag("StreamableHTTPMCP"),$=class{static{g(this,"StreamableHTTPMCPClient")}name;config;requestId=1;initialized=!1;tools=[];originalTools=[];constructor(e,t){this.name=e,this.config=t}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async sendRequest(e,t){let o={jsonrpc:"2.0",method:e,params:t,id:this.requestId++};m.debug(`\u53D1\u9001\u8BF7\u6C42\u5230 ${this.name}: ${JSON.stringify(o)}`);try{let i=(await import("node-fetch")).default,n=await i(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify(o)});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);let s=await n.json();if(s.error)throw new Error(`JSON-RPC error: ${s.error.message} (code: ${s.error.code})`);return s.result}catch(i){throw m.error(`\u8BF7\u6C42\u5931\u8D25 (${e}): ${i instanceof Error?i.message:String(i)}`),i}}async sendNotification(e,t){let o={jsonrpc:"2.0",method:e,params:t};m.debug(`\u53D1\u9001\u901A\u77E5\u5230 ${this.name}: ${JSON.stringify(o)}`);try{let i=(await import("node-fetch")).default,n=await i(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify(o)});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);m.debug(`\u901A\u77E5 ${e} \u53D1\u9001\u6210\u529F`)}catch(i){throw m.debug(`\u901A\u77E5\u53D1\u9001\u5931\u8D25 (${e}): ${i instanceof Error?i.message:String(i)}`),i}}async start(){m.info(`\u6B63\u5728\u542F\u52A8 Streamable HTTP MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);try{await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{tools:{}},clientInfo:{name:"xiaozhi-streamable-http-client",version:"1.0.0"}});try{await this.sendNotification("notifications/initialized")}catch(t){m.debug(`${this.name} \u4E0D\u652F\u6301 notifications/initialized: ${t}`)}let e=await this.sendRequest("tools/list");e?.tools&&(this.originalTools=e.tools,await this.updateToolsConfig(),this.tools=this.originalTools.filter(t=>c.isToolEnabled(this.name,t.name)).map(t=>({...t,name:this.generatePrefixedToolName(t.name)})),m.info(`Streamable HTTP MCP \u5BA2\u6237\u7AEF ${this.name} \u5DF2\u521D\u59CB\u5316\uFF0C\u5305\u542B ${this.tools.length}/${this.originalTools.length} \u4E2A\u5DF2\u542F\u7528\u7684\u5DE5\u5177`)),this.initialized=!0}catch(e){throw m.error(`\u542F\u52A8 Streamable HTTP MCP \u5BA2\u6237\u7AEF ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{let e=await this.sendRequest("tools/list");e?.tools&&(this.originalTools=e.tools,await this.updateToolsConfig(),this.tools=this.originalTools.filter(t=>c.isToolEnabled(this.name,t.name)).map(t=>({...t,name:this.generatePrefixedToolName(t.name)})),m.info(`\u5DF2\u5237\u65B0 ${this.name} \u7684\u5DE5\u5177\u5217\u8868\uFF0C\u5305\u542B ${this.tools.length}/${this.originalTools.length} \u4E2A\u5DF2\u542F\u7528\u7684\u5DE5\u5177`))}catch(e){m.error(`\u5237\u65B0 ${this.name} \u7684\u5DE5\u5177\u5217\u8868\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async callTool(e,t){try{let o=this.getOriginalToolName(e);if(!o)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);return await this.sendRequest("tools/call",{name:o,arguments:t})}catch(o){throw m.error(`\u5728 ${this.name} \u4E0A\u8C03\u7528\u5DE5\u5177 ${e} \u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),o}}async updateToolsConfig(){try{let e=c.getServerToolsConfig(this.name),t={};for(let i of this.originalTools){let n=e[i.name];t[i.name]={description:i.description||"",enable:n?.enable!==!1}}(Object.keys(t).some(i=>{let n=e[i],s=t[i];return!n||n.enable!==s.enable||n.description!==s.description})||Object.keys(e).length===0)&&(c.updateServerToolsConfig(this.name,t),m.info(`${this.name} \u5DF2\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E`))}catch(e){m.error(`\u66F4\u65B0 ${this.name} \u7684\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async stop(){m.info(`\u6B63\u5728\u505C\u6B62 ${this.name} \u5BA2\u6237\u7AEF`),this.initialized=!1}};var ee=Y(N(import.meta.url)),r=u.withTag("MCPProxy"),j=f.env.XIAOZHI_CONFIG_DIR||f.cwd();u.initLogFile(j);u.enableFileLogging(!0);r.info(`\u65E5\u5FD7\u6587\u4EF6\u5DF2\u521D\u59CB\u5316: ${j}/xiaozhi.log`);var M=class{static{g(this,"MCPClient")}name;config;process;initialized;tools;originalTools;requestId;pendingRequests;messageBuffer;constructor(e,t){this.name=e,this.config=t,this.process=null,this.initialized=!1,this.tools=[],this.originalTools=[],this.requestId=1,this.pendingRequests=new Map,this.messageBuffer=""}resolveCommand(e,t){if(f.platform==="win32"){if(e==="npm"||e==="npx")return{resolvedCommand:`${e}.cmd`,resolvedArgs:t};if(e==="uvx")return{resolvedCommand:"uvx.bat",resolvedArgs:t}}return{resolvedCommand:e,resolvedArgs:t}}generatePrefixedToolName(e){return`${this.name.replace(/-/g,"_")}_xzcli_${e}`}getOriginalToolName(e){let o=`${this.name.replace(/-/g,"_")}_xzcli_`;return e.startsWith(o)?e.substring(o.length):null}async start(){r.info(`\u6B63\u5728\u542F\u52A8 MCP \u5BA2\u6237\u7AEF\uFF1A${this.name}`);let{command:e,args:t,env:o}=this.config,{resolvedCommand:i,resolvedArgs:n}=this.resolveCommand(e,t),s={stdio:["pipe","pipe","pipe"]},l=f.env.XIAOZHI_CONFIG_DIR||f.cwd();s.cwd=l,o?s.env={...f.env,...o}:s.env={...f.env},f.platform==="win32"&&(e==="npm"||e==="npx"||e==="uvx")&&(s.shell=!0),r.debug(`${this.name} \u6B63\u5728\u751F\u6210\u8FDB\u7A0B\uFF1A${i} ${n.join(" ")} \u5DE5\u4F5C\u76EE\u5F55\uFF1A${s.cwd}`),r.debug(`${this.name} \u5E73\u53F0\uFF1A${f.platform}\uFF0Cshell \u6A21\u5F0F\uFF1A${s.shell||!1}`),this.process=Z(i,n,s),this.process.stdout?.on("data",d=>{this.handleStdoutData(d.toString())}),this.process.stderr?.on("data",d=>{r.debug(`${this.name} \u6807\u51C6\u9519\u8BEF\u8F93\u51FA\uFF1A${d.toString().trim()}`)}),this.process.on("exit",(d,b)=>{r.error(`${this.name} \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u9000\u51FA\u7801\uFF1A${d}\uFF0C\u4FE1\u53F7\uFF1A${b}`),this.initialized=!1}),this.process.on("error",d=>{r.error(`${this.name} \u8FDB\u7A0B\u9519\u8BEF\uFF1A${d.message}`),this.initialized=!1}),await this.initialize()}handleStdoutData(e){this.messageBuffer=`${this.messageBuffer}${e}`;let t=this.messageBuffer.split(`
4
4
  `);this.messageBuffer=t.pop()||"";for(let o of t)if(o.trim())try{let i=JSON.parse(o.trim());this.handleMessage(i)}catch{r.error(`${this.name} \u89E3\u6790\u6D88\u606F\u5931\u8D25\uFF1A${o.trim()}`)}}handleMessage(e){if(r.debug(`${this.name} \u6536\u5230\u6D88\u606F\uFF1A${JSON.stringify(e).substring(0,200)}...`),e.id&&this.pendingRequests.has(e.id)){let t=this.pendingRequests.get(e.id);if(t){let{resolve:o,reject:i}=t;this.pendingRequests.delete(e.id),e.error?e.error.code===-32601&&t.method==="notifications/initialized"?(r.debug(`${this.name} \u670D\u52A1\u5668\u4E0D\u652F\u6301 notifications/initialized \u901A\u77E5\uFF0C\u8FD9\u662F\u6B63\u5E38\u7684`),o(null)):i(new Error(`${e.error.message} (code: ${e.error.code})`)):o(e.result)}}}async sendRequest(e,t={}){if(!this.process||!this.process.stdin)throw new Error(`${this.name} \u8FDB\u7A0B\u4E0D\u53EF\u7528`);let o=this.requestId++,i={jsonrpc:"2.0",id:o,method:e,params:t};return new Promise((n,s)=>{this.pendingRequests.set(o,{resolve:n,reject:s,method:e}),setTimeout(()=>{this.pendingRequests.has(o)&&(this.pendingRequests.delete(o),s(new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF1A${e}`)))},3e4);let l=`${JSON.stringify(i)}
5
5
  `;r.debug(`${this.name} \u6B63\u5728\u53D1\u9001\uFF1A${l.trim()}`),this.process?.stdin?.write(l)})}async initialize(){try{let e=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCPProxy",version:"0.3.0"}});r.info(`${this.name} \u5DF2\u521D\u59CB\u5316\uFF0C\u80FD\u529B\uFF1A${JSON.stringify(e.capabilities)}`);try{let t={jsonrpc:"2.0",method:"notifications/initialized"};this.process?.stdin?.write(`${JSON.stringify(t)}
6
- `)}catch(t){r.debug(`${this.name} notifications/initialized \u53D1\u9001\u5931\u8D25\uFF08\u67D0\u4E9B\u670D\u52A1\u5668\u4E0D\u652F\u6301\u6B64\u901A\u77E5\uFF09\uFF1A${t instanceof Error?t.message:String(t)}`)}await this.refreshTools(),this.initialized=!0,r.info(`${this.name} \u5BA2\u6237\u7AEF\u5DF2\u5C31\u7EEA\uFF0C\u5171 ${this.tools.length} \u4E2A\u5DE5\u5177`)}catch(e){throw r.error(`\u521D\u59CB\u5316 ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{let e=await this.sendRequest("tools/list");this.originalTools=e.tools||[];let t=this.originalTools.map(o=>({...o,name:this.generatePrefixedToolName(o.name)}));this.tools=this.filterEnabledTools(t),await this.updateToolsConfig(),r.info(`${this.name} \u52A0\u8F7D\u4E86 ${this.originalTools.length} \u4E2A\u5DE5\u5177\uFF1A${this.originalTools.map(o=>o.name).join(", ")}`),r.info(`${this.name} \u542F\u7528\u4E86 ${this.tools.length} \u4E2A\u5DE5\u5177\uFF1A${this.tools.map(o=>o.name).join(", ")}`)}catch(e){r.error(`\u4ECE ${this.name} \u83B7\u53D6\u5DE5\u5177\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),this.tools=[],this.originalTools=[]}}filterEnabledTools(e){return e.filter(t=>{let o=this.getOriginalToolName(t.name);return o?g.isToolEnabled(this.name,o):!0})}async updateToolsConfig(){try{let e=g.getServerToolsConfig(this.name),t={};for(let i of this.originalTools){let n=e[i.name];t[i.name]={description:i.description||"",enable:n?.enable!==!1}}(Object.keys(t).some(i=>{let n=e[i],s=t[i];return!n||n.enable!==s.enable||n.description!==s.description})||Object.keys(e).length===0)&&(g.updateServerToolsConfig(this.name,t),r.info(`${this.name} \u5DF2\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E`))}catch(e){r.error(`\u66F4\u65B0 ${this.name} \u7684\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async callTool(e,t){let o=Date.now();try{let i=this.getOriginalToolName(e);if(!i)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u8C03\u7528\u5F00\u59CB`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u540D\u79F0: ${i} (\u524D\u7F00: ${e})`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u8BF7\u6C42\u53C2\u6570: ${JSON.stringify(t,null,2)}`);let n=await this.sendRequest("tools/call",{name:i,arguments:t}),s=Date.now()-o;return r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u8C03\u7528\u6210\u529F`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u540D\u79F0: ${i}`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u6267\u884C\u8017\u65F6: ${s}ms`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5B8C\u6574\u7ED3\u679C: ${JSON.stringify(n,null,2)}`),n}catch(i){let n=Date.now()-o;throw r.error(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u8C03\u7528\u5931\u8D25\u5DE5\u5177: ${e} -> ${this.getOriginalToolName(e)||"\u672A\u77E5"}\u8017\u65F6: ${n}ms\u9519\u8BEF: ${i instanceof Error?i.message:String(i)}`),r.error(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u9519\u8BEF\u5806\u6808: ${i instanceof Error?i.stack:"\u65E0\u5806\u6808\u4FE1\u606F"}`),i}}stop(){this.process&&(r.info(`\u6B63\u5728\u505C\u6B62 ${this.name} \u5BA2\u6237\u7AEF`),this.process.kill("SIGTERM"),this.process=null),this.initialized=!1}};function te(){try{if(g.configExists()){let e=g.getMcpServers();return r.info(`\u4ECE\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D\u4E86 ${Object.keys(e).length} \u4E2A MCP \u670D\u52A1`),e}let a=Q(ee,"mcp_server.json");if(z)try{let e=z(a,"utf8"),t=JSON.parse(e);if(!t.mcpServers||typeof t.mcpServers!="object")throw new Error("\u65E0\u6548\u7684\u914D\u7F6E\uFF1AmcpServers \u90E8\u5206\u672A\u627E\u5230\u6216\u65E0\u6548");return r.info(`\u4ECE\u65E7\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D\u4E86 ${Object.keys(t.mcpServers).length} \u4E2A MCP \u670D\u52A1\uFF08\u5EFA\u8BAE\u8FC1\u79FB\u5230\u65B0\u914D\u7F6E\u683C\u5F0F\uFF09`),t.mcpServers}catch{throw r.error('\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E'),new Error('\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E')}throw new Error('\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E')}catch(a){throw r.error(`\u52A0\u8F7D MCP \u914D\u7F6E\u5931\u8D25\uFF1A${a instanceof Error?a.message:String(a)}`),a}}c(te,"loadMCPConfig");var I=class{static{c(this,"MCPServerProxy")}clients;toolMap;initialized;config;constructor(){this.clients=new Map,this.toolMap=new Map,this.initialized=!1,this.config=null}async start(){r.info("\u6B63\u5728\u542F\u52A8 MCP \u670D\u52A1\u4EE3\u7406"),this.config=te();let e=[];for(let[t,o]of Object.entries(this.config)){r.info(`\u6B63\u5728\u521D\u59CB\u5316 MCP \u5BA2\u6237\u7AEF\uFF1A${t}`);let i;if("url"in o){let n=o.url;"type"in o&&o.type==="sse"||(()=>{try{return new URL(n).pathname.endsWith("/sse")}catch{return n.includes("/sse")}})()||n.includes("modelscope.net")?n.includes("modelscope.net")?i=new w(t,o):i=new y(t,o):i=new $(t,o)}else i=new M(t,o);this.clients.set(t,i),e.push(i.start())}try{let t=await Promise.allSettled(e),o=0;for(let i=0;i<t.length;i++){let n=t[i],s=Object.keys(this.config)[i];n.status==="fulfilled"?(o++,r.info(`\u6210\u529F\u542F\u52A8 MCP \u5BA2\u6237\u7AEF\uFF1A${s}`)):(r.error(`\u542F\u52A8 MCP \u5BA2\u6237\u7AEF ${s} \u5931\u8D25\uFF1A${n.reason.message}`),this.clients.delete(s))}if(o===0)throw new Error("\u6CA1\u6709\u6210\u529F\u542F\u52A8\u4EFB\u4F55 MCP \u5BA2\u6237\u7AEF");this.buildToolMap(),this.initialized=!0,r.info(`MCP \u670D\u52A1\u4EE3\u7406\u521D\u59CB\u5316\u6210\u529F\uFF0C\u542F\u52A8\u4E86 ${o}/${Object.keys(this.config).length} \u4E2A\u5BA2\u6237\u7AEF`)}catch(t){throw r.error(`\u542F\u52A8 MCP \u5BA2\u6237\u7AEF\u5931\u8D25\uFF1A${t instanceof Error?t.message:String(t)}`),t}}buildToolMap(){this.toolMap.clear();for(let[e,t]of this.clients)for(let o of t.tools)this.toolMap.has(o.name)?r.error(`\u91CD\u590D\u7684\u5DE5\u5177\u540D\u79F0\uFF1A${o.name} (\u6765\u81EA ${e} \u548C ${this.toolMap.get(o.name)})`):this.toolMap.set(o.name,e);r.info(`\u5DF2\u6784\u5EFA\u5DE5\u5177\u6620\u5C04\uFF0C\u5171 ${this.toolMap.size} \u4E2A\u5DE5\u5177`),r.debug(`\u5DE5\u5177\u6620\u5C04\uFF1A${Array.from(this.toolMap.keys()).join(", ")}`)}getAllTools(){let e=[];for(let t of this.clients.values())e.push(...t.tools);return e}getAllServers(){let e=[];for(let[t,o]of this.clients)e.push({name:t,toolCount:o.originalTools.length,enabledToolCount:o.tools.length});return e}getServerTools(e){let t=this.clients.get(e);if(!t)throw new Error(`\u672A\u627E\u5230\u670D\u52A1\u5668 ${e}`);return t.originalTools.map(o=>({name:o.name,description:o.description||"",enabled:g.isToolEnabled(e,o.name)}))}async refreshServerTools(e){let t=this.clients.get(e);if(!t)throw new Error(`\u672A\u627E\u5230\u670D\u52A1\u5668 ${e}`);await t.refreshTools(),this.buildToolMap()}async refreshAllTools(){let e=Array.from(this.clients.values()).map(t=>t.refreshTools());await Promise.allSettled(e),this.buildToolMap()}async callTool(e,t){let o=Date.now(),i=this.toolMap.get(e);if(!i)throw new Error(`\u672A\u77E5\u7684\u5DE5\u5177\uFF1A${e}`);let n=this.clients.get(i);if(!n||!n.initialized)throw new Error(`\u5BA2\u6237\u7AEF ${i} \u4E0D\u53EF\u7528`);r.info("[\u4EE3\u7406\u5C42] \u5DE5\u5177\u8C03\u7528\u5F00\u59CB"),r.info(`[\u4EE3\u7406\u5C42] \u5DE5\u5177\u540D\u79F0: ${e}`),r.info(`[\u4EE3\u7406\u5C42] \u6240\u5C5E\u5BA2\u6237\u7AEF: ${i}`),r.info(`[\u4EE3\u7406\u5C42] \u8BF7\u6C42\u53C2\u6570: ${JSON.stringify(t,null,2)}`);try{let s=await n.callTool(e,t),l=Date.now()-o;return r.info("[\u4EE3\u7406\u5C42] \u5DE5\u5177\u8C03\u7528\u6210\u529F"),r.info(`[\u4EE3\u7406\u5C42] \u5DE5\u5177\u540D\u79F0: ${e}`),r.info(`[\u4EE3\u7406\u5C42] \u6240\u5C5E\u5BA2\u6237\u7AEF: ${i}`),r.info(`[\u4EE3\u7406\u5C42] \u6267\u884C\u8017\u65F6: ${l}ms`),r.info(`[\u4EE3\u7406\u5C42] \u5B8C\u6574\u7ED3\u679C: ${JSON.stringify(s,null,2)}`),s}catch(s){let l=Date.now()-o;throw r.error("[\u4EE3\u7406\u5C42] \u5DE5\u5177\u8C03\u7528\u5931\u8D25"),r.error(`[\u4EE3\u7406\u5C42] \u5DE5\u5177\u540D\u79F0: ${e}`),r.error(`[\u4EE3\u7406\u5C42] \u6240\u5C5E\u5BA2\u6237\u7AEF: ${i}`),r.error(`[\u4EE3\u7406\u5C42] \u6267\u884C\u8017\u65F6: ${l}ms`),r.error(`[\u4EE3\u7406\u5C42] \u9519\u8BEF\u4FE1\u606F: ${s instanceof Error?s.message:String(s)}`),s}}stop(){r.info("\u6B63\u5728\u505C\u6B62 MCP \u670D\u52A1\u4EE3\u7406");for(let e of this.clients.values())e.stop();this.initialized=!1}},x=class{static{c(this,"JSONRPCServer")}proxy;requestId;constructor(e){this.proxy=e,this.requestId=1}async handleMessage(e){try{let t=JSON.parse(e);if(r.debug(`\u6536\u5230\u8BF7\u6C42\uFF1A${JSON.stringify(t).substring(0,200)}...`),t.method){if(t.id!==void 0){let o=await this.handleRequest(t);return JSON.stringify(o)}return await this.handleNotification(t),null}throw new Error("\u65E0\u6548\u7684 JSON-RPC \u6D88\u606F")}catch(t){return r.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519\uFF1A${t instanceof Error?t.message:String(t)}`),JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"\u89E3\u6790\u9519\u8BEF"}})}}async handleRequest(e){let{id:t,method:o,params:i={}}=e;try{let n;switch(o){case"initialize":n=await this.handleInitialize(i);break;case"tools/list":n=await this.handleToolsList(i);break;case"tools/call":n=await this.handleToolsCall(i);break;case"ping":n=await this.handlePing(i);break;default:throw new Error(`\u672A\u77E5\u7684\u65B9\u6CD5\uFF1A${o}`)}return{jsonrpc:"2.0",id:t,result:n}}catch(n){return r.error(`\u5904\u7406\u8BF7\u6C42 ${o} \u65F6\u51FA\u9519\uFF1A${n instanceof Error?n.message:String(n)}`),{jsonrpc:"2.0",id:t,error:{code:-32603,message:n instanceof Error?n.message:String(n)}}}}async handleNotification(e){let{method:t}=e;switch(t){case"notifications/initialized":r.info("\u5BA2\u6237\u7AEF\u53D1\u9001\u4E86\u521D\u59CB\u5316\u901A\u77E5");break;default:r.debug(`\u6536\u5230\u901A\u77E5\uFF1A${t}`);break}}async handleInitialize(e){return r.info(`\u6536\u5230\u5BA2\u6237\u7AEF\u7684\u521D\u59CB\u5316\u8BF7\u6C42\uFF1A${JSON.stringify(e.clientInfo)}`),{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"MCPServerProxy",version:"0.3.0"}}}async handleToolsList(e){if(!this.proxy.initialized)throw new Error("\u4EE3\u7406\u672A\u521D\u59CB\u5316");let t=this.proxy.getAllTools();return r.info(`\u8FD4\u56DE ${t.length} \u4E2A\u5DE5\u5177`),{tools:t}}async handleToolsCall(e){let{name:t,arguments:o}=e,i=Date.now();if(!t)throw new Error("\u5DE5\u5177\u540D\u79F0\u662F\u5FC5\u9700\u7684");r.info("=== \u5DE5\u5177\u8C03\u7528\u5F00\u59CB ==="),r.info(`\u5DE5\u5177\u540D\u79F0: ${t}`),r.info(`\u8BF7\u6C42\u53C2\u6570: ${JSON.stringify(o,null,2)}`),r.info(`\u8C03\u7528\u65F6\u95F4: ${new Date().toISOString()}`);try{let n=await this.proxy.callTool(t,o||{}),s=Date.now()-i;return r.info("=== \u5DE5\u5177\u8C03\u7528\u6210\u529F ==="),r.info(`\u5DE5\u5177\u540D\u79F0: ${t}`),r.info(`\u6267\u884C\u8017\u65F6: ${s}ms`),r.info(`\u5B8C\u6574\u7ED3\u679C: ${JSON.stringify(n,null,2)}`),r.info(`\u7ED3\u679C\u7C7B\u578B: ${typeof n}`),n&&typeof n=="object"&&r.info(`\u7ED3\u679C\u957F\u5EA6: ${Array.isArray(n)?n.length:Object.keys(n).length} \u9879`),n}catch(n){let s=Date.now()-i;throw r.error("=== \u5DE5\u5177\u8C03\u7528\u5931\u8D25 ==="),r.error(`\u5DE5\u5177\u540D\u79F0: ${t}`),r.error(`\u6267\u884C\u8017\u65F6: ${s}ms`),r.error(`\u9519\u8BEF\u4FE1\u606F: ${n instanceof Error?n.message:String(n)}`),r.error(`\u9519\u8BEF\u5806\u6808: ${n instanceof Error?n.stack:"\u65E0\u5806\u6808\u4FE1\u606F"}`),n}}async handlePing(e){return r.debug("\u6536\u5230 ping \u8BF7\u6C42"),{}}};function oe(){return f.env.MCP_SERVER_MODE==="true"}c(oe,"isMCPServerMode");async function ie(){r.info("\u6B63\u5728\u542F\u52A8 MCP \u670D\u52A1\u4EE3\u7406");let a=new I,e=new x(a),t=c(()=>{r.info("\u6B63\u5728\u5173\u95ED MCP \u670D\u52A1\u4EE3\u7406"),a.stop(),f.exit(0)},"cleanup");f.on("SIGINT",t),f.on("SIGTERM",t);try{await a.start(),oe()&&(r.info("MCP proxy ready in server mode"),console.log("MCP proxy ready")),f.stdin.setEncoding("utf8");let o="";f.stdin.on("data",async i=>{o=`${o}${i}`;let n=o.split(`
6
+ `)}catch(t){r.debug(`${this.name} notifications/initialized \u53D1\u9001\u5931\u8D25\uFF08\u67D0\u4E9B\u670D\u52A1\u5668\u4E0D\u652F\u6301\u6B64\u901A\u77E5\uFF09\uFF1A${t instanceof Error?t.message:String(t)}`)}await this.refreshTools(),this.initialized=!0,r.info(`${this.name} \u5BA2\u6237\u7AEF\u5DF2\u5C31\u7EEA\uFF0C\u5171 ${this.tools.length} \u4E2A\u5DE5\u5177`)}catch(e){throw r.error(`\u521D\u59CB\u5316 ${this.name} \u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),e}}async refreshTools(){try{let e=await this.sendRequest("tools/list");this.originalTools=e.tools||[];let t=this.originalTools.map(o=>({...o,name:this.generatePrefixedToolName(o.name)}));this.tools=this.filterEnabledTools(t),await this.updateToolsConfig(),r.info(`${this.name} \u52A0\u8F7D\u4E86 ${this.originalTools.length} \u4E2A\u5DE5\u5177\uFF1A${this.originalTools.map(o=>o.name).join(", ")}`),r.info(`${this.name} \u542F\u7528\u4E86 ${this.tools.length} \u4E2A\u5DE5\u5177\uFF1A${this.tools.map(o=>o.name).join(", ")}`)}catch(e){r.error(`\u4ECE ${this.name} \u83B7\u53D6\u5DE5\u5177\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`),this.tools=[],this.originalTools=[]}}filterEnabledTools(e){return e.filter(t=>{let o=this.getOriginalToolName(t.name);return o?c.isToolEnabled(this.name,o):!0})}async updateToolsConfig(){try{let e=c.getServerToolsConfig(this.name),t={};for(let i of this.originalTools){let n=e[i.name];t[i.name]={description:i.description||"",enable:n?.enable!==!1}}(Object.keys(t).some(i=>{let n=e[i],s=t[i];return!n||n.enable!==s.enable||n.description!==s.description})||Object.keys(e).length===0)&&(c.updateServerToolsConfig(this.name,t),r.info(`${this.name} \u5DF2\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E`))}catch(e){r.error(`\u66F4\u65B0 ${this.name} \u7684\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${e instanceof Error?e.message:String(e)}`)}}async callTool(e,t){let o=Date.now();try{let i=this.getOriginalToolName(e);if(!i)throw new Error(`\u65E0\u6548\u7684\u5DE5\u5177\u540D\u79F0\u683C\u5F0F\uFF1A${e}`);r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u8C03\u7528\u5F00\u59CB`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u540D\u79F0: ${i} (\u524D\u7F00: ${e})`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u8BF7\u6C42\u53C2\u6570: ${JSON.stringify(t,null,2)}`);let n=await this.sendRequest("tools/call",{name:i,arguments:t}),s=Date.now()-o;return r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u8C03\u7528\u6210\u529F`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u540D\u79F0: ${i}`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u6267\u884C\u8017\u65F6: ${s}ms`),r.info(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5B8C\u6574\u7ED3\u679C: ${JSON.stringify(n,null,2)}`),n}catch(i){let n=Date.now()-o;throw r.error(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u5DE5\u5177\u8C03\u7528\u5931\u8D25\u5DE5\u5177: ${e} -> ${this.getOriginalToolName(e)||"\u672A\u77E5"}\u8017\u65F6: ${n}ms\u9519\u8BEF: ${i instanceof Error?i.message:String(i)}`),r.error(`[MCP\u5BA2\u6237\u7AEF ${this.name}] \u9519\u8BEF\u5806\u6808: ${i instanceof Error?i.stack:"\u65E0\u5806\u6808\u4FE1\u606F"}`),i}}stop(){this.process&&(r.info(`\u6B63\u5728\u505C\u6B62 ${this.name} \u5BA2\u6237\u7AEF`),this.process.kill("SIGTERM"),this.process=null),this.initialized=!1}};function te(){try{if(c.configExists()){let e=c.getMcpServers();return r.info(`\u4ECE\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D\u4E86 ${Object.keys(e).length} \u4E2A MCP \u670D\u52A1`),e}let a=Q(ee,"mcp_server.json");if(z)try{let e=z(a,"utf8"),t=JSON.parse(e);if(!t.mcpServers||typeof t.mcpServers!="object")throw new Error("\u65E0\u6548\u7684\u914D\u7F6E\uFF1AmcpServers \u90E8\u5206\u672A\u627E\u5230\u6216\u65E0\u6548");return r.info(`\u4ECE\u65E7\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D\u4E86 ${Object.keys(t.mcpServers).length} \u4E2A MCP \u670D\u52A1\uFF08\u5EFA\u8BAE\u8FC1\u79FB\u5230\u65B0\u914D\u7F6E\u683C\u5F0F\uFF09`),t.mcpServers}catch{throw r.error('\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E'),new Error('\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E')}throw new Error('\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E')}catch(a){throw r.error(`\u52A0\u8F7D MCP \u914D\u7F6E\u5931\u8D25\uFF1A${a instanceof Error?a.message:String(a)}`),a}}g(te,"loadMCPConfig");var I=class{static{g(this,"MCPServerProxy")}clients;toolMap;initialized;config;constructor(){this.clients=new Map,this.toolMap=new Map,this.initialized=!1,this.config=null}async cleanupRemovedServers(){try{let e=Object.keys(this.config||{}),t=c.getMcpServerConfig();if(!t||typeof t!="object"){r.debug("mcpServerConfig \u4E3A\u7A7A\u6216\u4E0D\u662F\u5BF9\u8C61\uFF0C\u65E0\u9700\u6E05\u7406");return}let i=Object.keys(t).filter(n=>!e.includes(n));if(i.length>0){r.info(`\u6B63\u5728\u6E05\u7406\u5DF2\u5220\u9664\u7684\u670D\u52A1\u914D\u7F6E: ${i.join(", ")}`);for(let n of i)try{c.removeServerToolsConfig(n),r.info(`\u5DF2\u6E05\u7406\u670D\u52A1 "${n}" \u7684\u5DE5\u5177\u914D\u7F6E`)}catch(s){r.error(`\u6E05\u7406\u670D\u52A1 "${n}" \u7684\u5DE5\u5177\u914D\u7F6E\u65F6\u51FA\u9519: ${s}`)}}}catch(e){r.error(`\u6E05\u7406\u5DF2\u5220\u9664\u670D\u52A1\u65F6\u51FA\u9519: ${e}`)}}async start(){r.info("\u6B63\u5728\u542F\u52A8 MCP \u670D\u52A1\u4EE3\u7406"),this.config=te(),await this.cleanupRemovedServers();let e=[];for(let[t,o]of Object.entries(this.config)){r.info(`\u6B63\u5728\u521D\u59CB\u5316 MCP \u5BA2\u6237\u7AEF\uFF1A${t}`);let i;if("url"in o){let n=o.url;"type"in o&&o.type==="sse"||(()=>{try{return new URL(n).pathname.endsWith("/sse")}catch{return n.includes("/sse")}})()||n.includes("modelscope.net")?n.includes("modelscope.net")?i=new y(t,o):i=new w(t,o):i=new $(t,o)}else i=new M(t,o);this.clients.set(t,i),e.push(i.start())}try{let t=await Promise.allSettled(e),o=0;for(let i=0;i<t.length;i++){let n=t[i],s=Object.keys(this.config)[i];n.status==="fulfilled"?(o++,r.info(`\u6210\u529F\u542F\u52A8 MCP \u5BA2\u6237\u7AEF\uFF1A${s}`)):(r.error(`\u542F\u52A8 MCP \u5BA2\u6237\u7AEF ${s} \u5931\u8D25\uFF1A${n.reason.message}`),this.clients.delete(s))}if(o===0)throw new Error("\u6CA1\u6709\u6210\u529F\u542F\u52A8\u4EFB\u4F55 MCP \u5BA2\u6237\u7AEF");this.buildToolMap(),this.initialized=!0,r.info(`MCP \u670D\u52A1\u4EE3\u7406\u521D\u59CB\u5316\u6210\u529F\uFF0C\u542F\u52A8\u4E86 ${o}/${Object.keys(this.config).length} \u4E2A\u5BA2\u6237\u7AEF`)}catch(t){throw r.error(`\u542F\u52A8 MCP \u5BA2\u6237\u7AEF\u5931\u8D25\uFF1A${t instanceof Error?t.message:String(t)}`),t}}buildToolMap(){this.toolMap.clear();for(let[e,t]of this.clients)for(let o of t.tools)this.toolMap.has(o.name)?r.error(`\u91CD\u590D\u7684\u5DE5\u5177\u540D\u79F0\uFF1A${o.name} (\u6765\u81EA ${e} \u548C ${this.toolMap.get(o.name)})`):this.toolMap.set(o.name,e);r.info(`\u5DF2\u6784\u5EFA\u5DE5\u5177\u6620\u5C04\uFF0C\u5171 ${this.toolMap.size} \u4E2A\u5DE5\u5177`),r.debug(`\u5DE5\u5177\u6620\u5C04\uFF1A${Array.from(this.toolMap.keys()).join(", ")}`)}getAllTools(){let e=[];for(let t of this.clients.values())e.push(...t.tools);return e}getAllServers(){let e=[];for(let[t,o]of this.clients)e.push({name:t,toolCount:o.originalTools.length,enabledToolCount:o.tools.length});return e}getServerTools(e){let t=this.clients.get(e);if(!t)throw new Error(`\u672A\u627E\u5230\u670D\u52A1\u5668 ${e}`);return t.originalTools.map(o=>({name:o.name,description:o.description||"",enabled:c.isToolEnabled(e,o.name)}))}async refreshServerTools(e){let t=this.clients.get(e);if(!t)throw new Error(`\u672A\u627E\u5230\u670D\u52A1\u5668 ${e}`);await t.refreshTools(),this.buildToolMap()}async refreshAllTools(){let e=Array.from(this.clients.values()).map(t=>t.refreshTools());await Promise.allSettled(e),this.buildToolMap()}async callTool(e,t){let o=Date.now(),i=this.toolMap.get(e);if(!i)throw new Error(`\u672A\u77E5\u7684\u5DE5\u5177\uFF1A${e}`);let n=this.clients.get(i);if(!n||!n.initialized)throw new Error(`\u5BA2\u6237\u7AEF ${i} \u4E0D\u53EF\u7528`);r.info("[\u4EE3\u7406\u5C42] \u5DE5\u5177\u8C03\u7528\u5F00\u59CB"),r.info(`[\u4EE3\u7406\u5C42] \u5DE5\u5177\u540D\u79F0: ${e}`),r.info(`[\u4EE3\u7406\u5C42] \u6240\u5C5E\u5BA2\u6237\u7AEF: ${i}`),r.info(`[\u4EE3\u7406\u5C42] \u8BF7\u6C42\u53C2\u6570: ${JSON.stringify(t,null,2)}`);try{let s=await n.callTool(e,t),l=Date.now()-o;return r.info("[\u4EE3\u7406\u5C42] \u5DE5\u5177\u8C03\u7528\u6210\u529F"),r.info(`[\u4EE3\u7406\u5C42] \u5DE5\u5177\u540D\u79F0: ${e}`),r.info(`[\u4EE3\u7406\u5C42] \u6240\u5C5E\u5BA2\u6237\u7AEF: ${i}`),r.info(`[\u4EE3\u7406\u5C42] \u6267\u884C\u8017\u65F6: ${l}ms`),r.info(`[\u4EE3\u7406\u5C42] \u5B8C\u6574\u7ED3\u679C: ${JSON.stringify(s,null,2)}`),s}catch(s){let l=Date.now()-o;throw r.error("[\u4EE3\u7406\u5C42] \u5DE5\u5177\u8C03\u7528\u5931\u8D25"),r.error(`[\u4EE3\u7406\u5C42] \u5DE5\u5177\u540D\u79F0: ${e}`),r.error(`[\u4EE3\u7406\u5C42] \u6240\u5C5E\u5BA2\u6237\u7AEF: ${i}`),r.error(`[\u4EE3\u7406\u5C42] \u6267\u884C\u8017\u65F6: ${l}ms`),r.error(`[\u4EE3\u7406\u5C42] \u9519\u8BEF\u4FE1\u606F: ${s instanceof Error?s.message:String(s)}`),s}}stop(){r.info("\u6B63\u5728\u505C\u6B62 MCP \u670D\u52A1\u4EE3\u7406");for(let e of this.clients.values())e.stop();this.initialized=!1}},O=class{static{g(this,"JSONRPCServer")}proxy;requestId;constructor(e){this.proxy=e,this.requestId=1}async handleMessage(e){try{let t=JSON.parse(e);if(r.debug(`\u6536\u5230\u8BF7\u6C42\uFF1A${JSON.stringify(t).substring(0,200)}...`),t.method){if(t.id!==void 0){let o=await this.handleRequest(t);return JSON.stringify(o)}return await this.handleNotification(t),null}throw new Error("\u65E0\u6548\u7684 JSON-RPC \u6D88\u606F")}catch(t){return r.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519\uFF1A${t instanceof Error?t.message:String(t)}`),JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"\u89E3\u6790\u9519\u8BEF"}})}}async handleRequest(e){let{id:t,method:o,params:i={}}=e;try{let n;switch(o){case"initialize":n=await this.handleInitialize(i);break;case"tools/list":n=await this.handleToolsList(i);break;case"tools/call":n=await this.handleToolsCall(i);break;case"ping":n=await this.handlePing(i);break;default:throw new Error(`\u672A\u77E5\u7684\u65B9\u6CD5\uFF1A${o}`)}return{jsonrpc:"2.0",id:t,result:n}}catch(n){return r.error(`\u5904\u7406\u8BF7\u6C42 ${o} \u65F6\u51FA\u9519\uFF1A${n instanceof Error?n.message:String(n)}`),{jsonrpc:"2.0",id:t,error:{code:-32603,message:n instanceof Error?n.message:String(n)}}}}async handleNotification(e){let{method:t}=e;switch(t){case"notifications/initialized":r.info("\u5BA2\u6237\u7AEF\u53D1\u9001\u4E86\u521D\u59CB\u5316\u901A\u77E5");break;default:r.debug(`\u6536\u5230\u901A\u77E5\uFF1A${t}`);break}}async handleInitialize(e){return r.info(`\u6536\u5230\u5BA2\u6237\u7AEF\u7684\u521D\u59CB\u5316\u8BF7\u6C42\uFF1A${JSON.stringify(e.clientInfo)}`),{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"MCPServerProxy",version:"0.3.0"}}}async handleToolsList(e){if(!this.proxy.initialized)throw new Error("\u4EE3\u7406\u672A\u521D\u59CB\u5316");let t=this.proxy.getAllTools();return r.info(`\u8FD4\u56DE ${t.length} \u4E2A\u5DE5\u5177`),{tools:t}}async handleToolsCall(e){let{name:t,arguments:o}=e,i=Date.now();if(!t)throw new Error("\u5DE5\u5177\u540D\u79F0\u662F\u5FC5\u9700\u7684");r.info("=== \u5DE5\u5177\u8C03\u7528\u5F00\u59CB ==="),r.info(`\u5DE5\u5177\u540D\u79F0: ${t}`),r.info(`\u8BF7\u6C42\u53C2\u6570: ${JSON.stringify(o,null,2)}`),r.info(`\u8C03\u7528\u65F6\u95F4: ${new Date().toISOString()}`);try{let n=await this.proxy.callTool(t,o||{}),s=Date.now()-i;return r.info("=== \u5DE5\u5177\u8C03\u7528\u6210\u529F ==="),r.info(`\u5DE5\u5177\u540D\u79F0: ${t}`),r.info(`\u6267\u884C\u8017\u65F6: ${s}ms`),r.info(`\u5B8C\u6574\u7ED3\u679C: ${JSON.stringify(n,null,2)}`),r.info(`\u7ED3\u679C\u7C7B\u578B: ${typeof n}`),n&&typeof n=="object"&&r.info(`\u7ED3\u679C\u957F\u5EA6: ${Array.isArray(n)?n.length:Object.keys(n).length} \u9879`),n}catch(n){let s=Date.now()-i;throw r.error("=== \u5DE5\u5177\u8C03\u7528\u5931\u8D25 ==="),r.error(`\u5DE5\u5177\u540D\u79F0: ${t}`),r.error(`\u6267\u884C\u8017\u65F6: ${s}ms`),r.error(`\u9519\u8BEF\u4FE1\u606F: ${n instanceof Error?n.message:String(n)}`),r.error(`\u9519\u8BEF\u5806\u6808: ${n instanceof Error?n.stack:"\u65E0\u5806\u6808\u4FE1\u606F"}`),n}}async handlePing(e){return r.debug("\u6536\u5230 ping \u8BF7\u6C42"),{}}};function oe(){return f.env.MCP_SERVER_MODE==="true"}g(oe,"isMCPServerMode");async function ie(){r.info("\u6B63\u5728\u542F\u52A8 MCP \u670D\u52A1\u4EE3\u7406");let a=new I,e=new O(a),t=g(()=>{r.info("\u6B63\u5728\u5173\u95ED MCP \u670D\u52A1\u4EE3\u7406"),a.stop(),f.exit(0)},"cleanup");f.on("SIGINT",t),f.on("SIGTERM",t);try{await a.start(),oe()&&(r.info("MCP proxy ready in server mode"),console.log("MCP proxy ready")),f.stdin.setEncoding("utf8");let o="";f.stdin.on("data",async i=>{o=`${o}${i}`;let n=o.split(`
7
7
  `);o=n.pop()||"";for(let s of n)if(s.trim())try{let l=await e.handleMessage(s.trim());l&&f.stdout.write(`${l}
8
- `)}catch(l){r.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519\uFF1A${l instanceof Error?l.message:String(l)}`)}}),f.stdin.on("end",()=>{r.info("\u6807\u51C6\u8F93\u5165\u5DF2\u5173\u95ED\uFF0C\u6B63\u5728\u5173\u95ED"),t()}),r.info("MCP \u670D\u52A1\u4EE3\u7406\u6B63\u5728\u901A\u8FC7 stdio \u8FD0\u884C")}catch(o){r.error(`\u542F\u52A8 MCP \u670D\u52A1\u4EE3\u7406\u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),f.exit(1)}}c(ie,"main");var ne=import.meta.url,re=N(ne),se=f.argv[1];re===se&&ie().catch(a=>{r.error(`\u672A\u5904\u7406\u7684\u9519\u8BEF\uFF1A${a instanceof Error?a.message:String(a)}`),f.exit(1)});export{x as JSONRPCServer,M as MCPClient,I as MCPServerProxy,te as loadMCPConfig};
8
+ `)}catch(l){r.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519\uFF1A${l instanceof Error?l.message:String(l)}`)}}),f.stdin.on("end",()=>{r.info("\u6807\u51C6\u8F93\u5165\u5DF2\u5173\u95ED\uFF0C\u6B63\u5728\u5173\u95ED"),t()}),r.info("MCP \u670D\u52A1\u4EE3\u7406\u6B63\u5728\u901A\u8FC7 stdio \u8FD0\u884C")}catch(o){r.error(`\u542F\u52A8 MCP \u670D\u52A1\u4EE3\u7406\u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`),f.exit(1)}}g(ie,"main");var ne=import.meta.url,re=N(ne),se=f.argv[1];re===se&&ie().catch(a=>{r.error(`\u672A\u5904\u7406\u7684\u9519\u8BEF\uFF1A${a instanceof Error?a.message:String(a)}`),f.exit(1)});export{O as JSONRPCServer,M as MCPClient,I as MCPServerProxy,te as loadMCPConfig};
9
9
  //# sourceMappingURL=mcpServerProxy.js.map