modify config file

This commit is contained in:
锦恢 2025-06-04 21:25:37 +08:00
parent cf5720c541
commit e3e2ed99f8
11 changed files with 116 additions and 36 deletions

31
package-lock.json generated
View File

@ -539,6 +539,16 @@
"w3c-keyname": "^2.2.4" "w3c-keyname": "^2.2.4"
} }
}, },
"node_modules/@colors/colors": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
"integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=0.1.90"
}
},
"node_modules/@ctrl/tinycolor": { "node_modules/@ctrl/tinycolor": {
"version": "3.6.1", "version": "3.6.1",
"license": "MIT", "license": "MIT",
@ -1759,7 +1769,6 @@
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@ -2085,6 +2094,21 @@
"node": ">=6.0" "node": ">=6.0"
} }
}, },
"node_modules/cli-table3": {
"version": "0.6.5",
"resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz",
"integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==",
"license": "MIT",
"dependencies": {
"string-width": "^4.2.0"
},
"engines": {
"node": "10.* || >= 12.*"
},
"optionalDependencies": {
"@colors/colors": "1.5.0"
}
},
"node_modules/cliui": { "node_modules/cliui": {
"version": "8.0.1", "version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
@ -2456,7 +2480,6 @@
"version": "8.0.0", "version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/emojis-list": { "node_modules/emojis-list": {
@ -3519,7 +3542,6 @@
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@ -5603,7 +5625,6 @@
"version": "4.2.3", "version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"emoji-regex": "^8.0.0", "emoji-regex": "^8.0.0",
@ -5618,7 +5639,6 @@
"version": "6.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ansi-regex": "^5.0.1" "ansi-regex": "^5.0.1"
@ -6820,6 +6840,7 @@
"@modelcontextprotocol/sdk": "^1.12.1", "@modelcontextprotocol/sdk": "^1.12.1",
"@seald-io/nedb": "^4.1.1", "@seald-io/nedb": "^4.1.1",
"axios": "^1.9.0", "axios": "^1.9.0",
"cli-table3": "^0.6.5",
"https-proxy-agent": "^7.0.6", "https-proxy-agent": "^7.0.6",
"open": "^10.1.2", "open": "^10.1.2",
"openai": "^5.0.1", "openai": "^5.0.1",

View File

@ -63,8 +63,6 @@ export class TaskLoop {
// 根据当前环境决定是否要开启 messageBridge // 根据当前环境决定是否要开启 messageBridge
const platform = getPlatform(); const platform = getPlatform();
console.log('current platform is', platform);
if (platform === 'nodejs') { if (platform === 'nodejs') {
const adapter = taskOptions.adapter; const adapter = taskOptions.adapter;
@ -73,7 +71,6 @@ export class TaskLoop {
} }
createMessageBridge(adapter.emitter); createMessageBridge(adapter.emitter);
console.log('mcpClientAdapter launch');
this.nodejsStatus.connectionFut = mcpClientAdapter.launch(); this.nodejsStatus.connectionFut = mcpClientAdapter.launch();
} }
@ -143,8 +140,6 @@ export class TaskLoop {
// data.code 一定为 200否则不会走这个 route // data.code 一定为 200否则不会走这个 route
const { chunk } = data.msg as { chunk: ChatCompletionChunk }; const { chunk } = data.msg as { chunk: ChatCompletionChunk };
console.log(chunk);
// 处理增量的 content 和 tool_calls // 处理增量的 content 和 tool_calls
this.handleChunkDeltaContent(chunk); this.handleChunkDeltaContent(chunk);
this.handleChunkDeltaToolCalls(chunk, toolcallIndexAdapter); this.handleChunkDeltaToolCalls(chunk, toolcallIndexAdapter);
@ -185,6 +180,10 @@ export class TaskLoop {
}); });
} }
public setProxyServer(proxyServer: string) {
mcpSetting.proxyServer = proxyServer;
}
public makeChatData(tabStorage: ChatStorage): ChatCompletionCreateParamsBase | undefined { public makeChatData(tabStorage: ChatStorage): ChatCompletionCreateParamsBase | undefined {
const baseURL = this.getLlmConfig().baseUrl; const baseURL = this.getLlmConfig().baseUrl;
const apiKey = this.getLlmConfig().userToken || ''; const apiKey = this.getLlmConfig().userToken || '';
@ -332,15 +331,19 @@ export class TaskLoop {
await this.nodejsStatus.connectionFut; await this.nodejsStatus.connectionFut;
} }
const allTools = {} as Record<string, ToolItem[]>; const allTools = [] as ToolItem[];
for (const client of mcpClientAdapter.clients) { for (const client of mcpClientAdapter.clients) {
if (!client.connected) { if (!client.connected) {
continue; continue;
} }
const tools = await client.getTools(); const tools = await client.getTools();
const clientName = client.connectionResult.name as string; allTools.push(...Array.from(tools.values()).map(
allTools[clientName] = Array.from(tools.values()); item => ({
...item,
enabled: true
})
));
} }
return allTools; return allTools;
@ -395,9 +398,6 @@ export class TaskLoop {
// 发送请求 // 发送请求
const doConverationResult = await this.doConversation(chatData, toolcallIndexAdapter); const doConverationResult = await this.doConversation(chatData, toolcallIndexAdapter);
console.log('[doConverationResult] Response');
console.log(doConverationResult);
// 如果存在需要调度的工具 // 如果存在需要调度的工具
if (this.streamingToolCalls.value.length > 0) { if (this.streamingToolCalls.value.length > 0) {

View File

@ -200,7 +200,6 @@ export class McpClient {
this.tools = new Map<string, ToolItem>(); this.tools = new Map<string, ToolItem>();
msg.tools.forEach(tool => { msg.tools.forEach(tool => {
const standardSchema = _processSchemaNode(tool.inputSchema, tool.inputSchema.$defs || {}); const standardSchema = _processSchemaNode(tool.inputSchema, tool.inputSchema.$defs || {});
console.log(standardSchema);
tool.inputSchema = standardSchema; tool.inputSchema = standardSchema;
@ -530,7 +529,6 @@ class McpClientAdapter {
} }
const launchSignature = await this.getLaunchSignature(); const launchSignature = await this.getLaunchSignature();
console.log('launchSignature', launchSignature);
let allOk = true; let allOk = true;

View File

@ -35,6 +35,7 @@
"uuid": "^11.1.0", "uuid": "^11.1.0",
"open": "^10.1.2", "open": "^10.1.2",
"ws": "^8.18.1", "ws": "^8.18.1",
"cli-table3": "^0.6.5",
"https-proxy-agent": "^7.0.6" "https-proxy-agent": "^7.0.6"
} }
} }

View File

@ -29,6 +29,7 @@ export interface ToolItem {
name: string; name: string;
description: string; description: string;
inputSchema: InputSchema; inputSchema: InputSchema;
enabled: boolean;
anyOf?: any; anyOf?: any;
} }
@ -160,10 +161,16 @@ export class TaskLoop {
bindStreaming(content: Ref<string>, toolCalls: Ref<ToolCall[]>): void; bindStreaming(content: Ref<string>, toolCalls: Ref<ToolCall[]>): void;
connectToService(): Promise<void>; connectToService(): Promise<void>;
/**
* @description
* @param proxyServer
*/
setProxyServer(proxyServer: string): void;
/** /**
* @description * @description
*/ */
listTools(): Promise<Record<string, ToolItem[]>>; listTools(): Promise<ToolItem[]>;
/** /**
* @description DOM * @description DOM

View File

@ -39,6 +39,7 @@
"@modelcontextprotocol/sdk": "^1.12.1", "@modelcontextprotocol/sdk": "^1.12.1",
"@seald-io/nedb": "^4.1.1", "@seald-io/nedb": "^4.1.1",
"axios": "^1.9.0", "axios": "^1.9.0",
"cli-table3": "^0.6.5",
"https-proxy-agent": "^7.0.6", "https-proxy-agent": "^7.0.6",
"open": "^10.1.2", "open": "^10.1.2",
"openai": "^5.0.1", "openai": "^5.0.1",

View File

@ -30,7 +30,7 @@ export async function routeMessage(command: string, data: any, webview: PostMess
webview.postMessage({ command, data: res }); webview.postMessage({ command, data: res });
} }
} catch (error) { } catch (error) {
console.error(error); // console.error(error);
webview.postMessage({ webview.postMessage({
command, data: { command, data: {
code: 500, code: 500,

View File

@ -1,7 +1,7 @@
import { WebSocket } from 'ws'; import { WebSocket } from 'ws';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { routeMessage } from '../common/router.js'; import { routeMessage } from '../common/router.js';
import { McpOptions } from '../mcp/client.dto.js'; import { ConnectionType, McpOptions } from '../mcp/client.dto.js';
import { clientMap, connectService } from '../mcp/connect.service.js'; import { clientMap, connectService } from '../mcp/connect.service.js';
// WebSocket 消息格式 // WebSocket 消息格式
@ -21,6 +21,14 @@ export interface PostMessageble {
postMessage(message: any): void; postMessage(message: any): void;
} }
export interface IConnectionArgs {
connectionType: ConnectionType;
commandString?: string;
cwd?: string;
url?: string;
oauth?: string;
}
// 监听器回调类型 // 监听器回调类型
export type MessageHandler = (message: any) => void; export type MessageHandler = (message: any) => void;
@ -72,7 +80,7 @@ export class VSCodeWebViewLike {
export class TaskLoopAdapter { export class TaskLoopAdapter {
public emitter: EventEmitter; public emitter: EventEmitter;
private messageHandlers: Set<MessageHandler>; private messageHandlers: Set<MessageHandler>;
private connectionOptions: McpOptions[] = []; private connectionOptions: IConnectionArgs[] = [];
constructor(option?: any) { constructor(option?: any) {
this.emitter = new EventEmitter(option); this.emitter = new EventEmitter(option);
@ -133,7 +141,7 @@ export class TaskLoopAdapter {
* @description mcp * @description mcp
* @param mcpOption * @param mcpOption
*/ */
public addMcp(mcpOption: McpOptions) { public addMcp(mcpOption: IConnectionArgs) {
// 0.1.4 新版本开始,此处修改为懒加载连接 // 0.1.4 新版本开始,此处修改为懒加载连接
// 实际的连接移交给前端 mcpAdapter 中进行统一的调度 // 实际的连接移交给前端 mcpAdapter 中进行统一的调度

View File

@ -6,6 +6,7 @@ import { ocrDB } from "../hook/db.js";
import type { ToolCallContent } from "../mcp/client.dto.js"; import type { ToolCallContent } from "../mcp/client.dto.js";
import { ocrWorkerStorage } from "../mcp/ocr.service.js"; import { ocrWorkerStorage } from "../mcp/ocr.service.js";
import { axiosFetch } from "../hook/axios-fetch.js"; import { axiosFetch } from "../hook/axios-fetch.js";
import Table from 'cli-table3';
export let currentStream: AsyncIterable<any> | null = null; export let currentStream: AsyncIterable<any> | null = null;
@ -24,13 +25,22 @@ export async function streamingChatCompletion(
proxyServer = '' proxyServer = ''
} = data; } = data;
// 创建请求参数表格
const requestTable = new Table({
head: ['Parameter', 'Value'],
colWidths: [20, 40],
style: {
head: ['cyan'],
border: ['grey']
}
});
const client = new OpenAI({ const client = new OpenAI({
baseURL, baseURL,
apiKey, apiKey,
fetch: async (input: string | URL | Request, init?: RequestInit) => { fetch: async (input: string | URL | Request, init?: RequestInit) => {
console.log('openai fetch begin, proxyServer:', proxyServer);
if (model.startsWith('gemini') && init) { if (model.startsWith('gemini') && init) {
// 该死的 google // 该死的 google
init.headers = { init.headers = {
@ -49,8 +59,18 @@ export async function streamingChatCompletion(
await postProcessMessages(messages); await postProcessMessages(messages);
console.log('seriableTools', seriableTools); // 使用表格渲染请求参数
console.log('seriableParallelToolCalls', seriableParallelToolCalls); requestTable.push(
['Model', model],
['Base URL', baseURL || 'Default'],
['Temperature', temperature],
['Tools Count', tools.length],
['Parallel Tool Calls', parallelToolCalls],
['Proxy Server', proxyServer || 'No Proxy']
);
console.log('\nOpenAI Request Parameters:');
console.log(requestTable.toString());
const stream = await client.chat.completions.create({ const stream = await client.chat.completions.create({
model, model,

View File

@ -87,9 +87,9 @@ export class McpClient {
// 建立连接 // 建立连接
if (this.transport) { if (this.transport) {
try { try {
console.log(`🔌 Connecting to MCP server via ${this.options.connectionType}...`); // console.log(`🔌 Connecting to MCP server via ${this.options.connectionType}...`);
await this.client.connect(this.transport); await this.client.connect(this.transport);
console.log(`Connected to MCP server via ${this.options.connectionType}`); // console.log(`✅ Connected to MCP server via ${this.options.connectionType}`);
} catch (error) { } catch (error) {
if (error instanceof UnauthorizedError) { if (error instanceof UnauthorizedError) {
if (!(this.transport instanceof StreamableHTTPClientTransport) && !(this.transport instanceof SSEClientTransport)) { if (!(this.transport instanceof StreamableHTTPClientTransport) && !(this.transport instanceof SSEClientTransport)) {
@ -125,7 +125,6 @@ export class McpClient {
// 断开连接 // 断开连接
public async disconnect(): Promise<void> { public async disconnect(): Promise<void> {
await this.client.close(); await this.client.close();
console.log('Disconnected from MCP server'); console.log('Disconnected from MCP server');
} }

View File

@ -8,6 +8,7 @@ import path from 'node:path';
import fs from 'node:fs'; import fs from 'node:fs';
import * as os from 'os'; import * as os from 'os';
import { PostMessageble } from '../hook/adapter.js'; import { PostMessageble } from '../hook/adapter.js';
import Table from 'cli-table3';
export const clientMap: Map<string, RequestClientType> = new Map(); export const clientMap: Map<string, RequestClientType> = new Map();
export function getClient(clientId?: string): RequestClientType | undefined { export function getClient(clientId?: string): RequestClientType | undefined {
@ -103,6 +104,10 @@ async function preprocessCommand(option: McpOptions, webview?: PostMessageble) {
}); });
} }
if (option.cwd && option.cwd.startsWith('~/')) {
option.cwd = option.cwd.replace('~', process.env.HOME || '');
}
if (option.connectionType === 'SSE' || option.connectionType === 'STREAMABLE_HTTP') { if (option.connectionType === 'SSE' || option.connectionType === 'STREAMABLE_HTTP') {
return; return;
} }
@ -240,9 +245,29 @@ export async function connectService(
webview?: PostMessageble webview?: PostMessageble
): Promise<RestfulResponse> { ): Promise<RestfulResponse> {
try { try {
const { env, ...others } = option; // 使用cli-table3创建美观的表格
console.log('ready to connect', others); const table = new Table({
head: ['Property', 'Value'],
colWidths: [20, 60],
style: {
head: ['green'],
border: ['grey']
}
});
table.push(
['Connection Type', option.connectionType],
['Command', option.command || 'N/A'],
['Arguments', option.args?.join(' ') || 'N/A'],
['Working Directory', option.cwd || 'N/A'],
['URL', option.url || 'N/A']
);
console.log(table.toString());
// 预处理字符串
await preprocessCommand(option, webview); await preprocessCommand(option, webview);
// 通过 option 字符串进行 hash得到唯一的 uuid // 通过 option 字符串进行 hash得到唯一的 uuid