1- using MarketAssistant . Agents . Plugins ;
2- using MarketAssistant . Applications . Settings ;
1+ using MarketAssistant . Services . Mcp ;
32using Microsoft . Extensions . AI ;
43using Microsoft . Extensions . Logging ;
5- using ModelContextProtocol . Client ;
64
75namespace MarketAssistant . Agents ;
86
97/// <summary>
10- /// 市场对话代理,专门处理用户与AI的对话交互
11- /// 使用 Microsoft Agent Framework API
8+ /// 市场对话会话管理器,处理用户与AI的对话交互
9+ /// 管理对话历史、上下文和工具集成
1210/// </summary>
13- public class MarketChatAgent : IDisposable
11+ public class MarketChatSession : IDisposable
1412{
1513 #region 常量定义
1614
@@ -34,7 +32,7 @@ public class MarketChatAgent : IDisposable
3432 #region 私有字段
3533
3634 private readonly IChatClient _chatClient ;
37- private readonly ILogger < MarketChatAgent > _logger ;
35+ private readonly ILogger < MarketChatSession > _logger ;
3836
3937 /// <summary>
4038 /// 对话历史记录
@@ -47,9 +45,9 @@ public class MarketChatAgent : IDisposable
4745 private readonly List < AITool > _mcpTools = new ( ) ;
4846
4947 /// <summary>
50- /// MCP 客户端列表
48+ /// MCP 服务
5149 /// </summary>
52- private readonly List < IMcpClient > _mcpClients = new ( ) ;
50+ private readonly McpService _mcpService ;
5351
5452 /// <summary>
5553 /// 当前股票代码
@@ -71,16 +69,19 @@ public class MarketChatAgent : IDisposable
7169 #region 构造函数
7270
7371 /// <summary>
74- /// 创建市场对话代理
72+ /// 创建市场对话会话
7573 /// </summary>
7674 /// <param name="chatClient">聊天客户端</param>
7775 /// <param name="logger">日志记录器</param>
78- public MarketChatAgent (
76+ /// <param name="mcpService">MCP 服务</param>
77+ public MarketChatSession (
7978 IChatClient chatClient ,
80- ILogger < MarketChatAgent > logger )
79+ ILogger < MarketChatSession > logger ,
80+ McpService mcpService )
8181 {
8282 _chatClient = chatClient ?? throw new ArgumentNullException ( nameof ( chatClient ) ) ;
8383 _logger = logger ?? throw new ArgumentNullException ( nameof ( logger ) ) ;
84+ _mcpService = mcpService ?? throw new ArgumentNullException ( nameof ( mcpService ) ) ;
8485
8586 // 初始化系统消息
8687 InitializeSystemContext ( ) ;
@@ -98,8 +99,6 @@ public MarketChatAgent(
9899 /// </summary>
99100 public event EventHandler < StreamingResponseEventArgs > ? StreamingResponse ;
100101
101-
102-
103102 #endregion
104103
105104 #region 公共属性
@@ -155,13 +154,13 @@ public async Task<ChatMessage> SendMessageAsync(string userMessage, Cancellation
155154 } ;
156155
157156 // 调用AI服务获取回复
158- var chatCompletion = await _chatClient . CompleteAsync (
157+ var chatCompletion = await _chatClient . GetResponseAsync (
159158 _conversationHistory ,
160159 chatOptions ,
161160 cts . Token ) ;
162161
163162 // 从响应中获取助手消息(假设返回类型有 Choices 或 Message 属性)
164- var assistantMessage = new ChatMessage ( ChatRole . Assistant , chatCompletion . Message . Text ?? string . Empty ) ;
163+ var assistantMessage = new ChatMessage ( ChatRole . Assistant , chatCompletion . Text ?? string . Empty ) ;
165164
166165 // 添加AI回复到历史
167166 _conversationHistory . Add ( assistantMessage ) ;
@@ -234,7 +233,7 @@ public async IAsyncEnumerable<StreamingChatUpdate> SendMessageStreamAsync(
234233 cts . Token ) )
235234 {
236235 var content = update . Text ?? string . Empty ;
237-
236+
238237 // 累积完整响应
239238 if ( ! string . IsNullOrEmpty ( content ) )
240239 {
@@ -303,7 +302,7 @@ public async Task UpdateStockContextAsync(string stockCode)
303302 // 更新系统上下文
304303 await UpdateSystemContextAsync ( ) ;
305304
306- // 只在有实际对话历史时才添加切换提示,避免空对话时的冗余消息
305+ // 只在有实际对话历史时才添加切换提示,避免空对话时的冗余消息
307306 var hasUserMessages = _conversationHistory . Any ( m => m . Role == ChatRole . User ) ;
308307
309308 if ( hasUserMessages && ! string . IsNullOrEmpty ( stockCode ) )
@@ -331,9 +330,9 @@ public void ClearHistory()
331330 /// 添加系统消息
332331 /// </summary>
333332 /// <param name="message">系统消息内容</param>
334- public void AddSystemMessage ( string message )
333+ public void AddAssistantMessage ( string message )
335334 {
336- _conversationHistory . Add ( new ChatMessage ( ChatRole . System , message ) ) ;
335+ _conversationHistory . Add ( new ChatMessage ( ChatRole . Assistant , message ) ) ;
337336 }
338337
339338 /// <summary>
@@ -347,19 +346,15 @@ public void Dispose()
347346 _currentCancellationTokenSource ? . Cancel ( ) ;
348347 _currentCancellationTokenSource ? . Dispose ( ) ;
349348
350- foreach ( var mcpClient in _mcpClients )
349+ try
351350 {
352- try
353- {
354- mcpClient . DisposeAsync ( ) . AsTask ( ) . Wait ( TimeSpan . FromSeconds ( 5 ) ) ;
355- }
356- catch ( Exception ex )
357- {
358- _logger . LogWarning ( ex , "释放 MCP 客户端时发生错误" ) ;
359- }
351+ _mcpService . DisposeAsync ( ) . AsTask ( ) . Wait ( TimeSpan . FromSeconds ( 5 ) ) ;
352+ }
353+ catch ( Exception ex )
354+ {
355+ _logger . LogWarning ( ex , "释放 MCP 服务时发生错误" ) ;
360356 }
361357
362- _mcpClients . Clear ( ) ;
363358 _mcpTools . Clear ( ) ;
364359
365360 _disposed = true ;
@@ -388,70 +383,25 @@ private async Task InitializeMcpServicesAsync()
388383 {
389384 _logger . LogInformation ( "开始初始化MCP服务" ) ;
390385
391- var configService = MCPServerConfigService . Instance ;
392- var enabledConfigs = configService . ServerConfigs . Where ( c => c . IsEnabled ) . ToList ( ) ;
393-
394- foreach ( var config in enabledConfigs )
395- {
396- try
397- {
398- IClientTransport clientTransport = config . TransportType . ToLower ( ) switch
399- {
400- "stdio" => CreateStdioTransport ( config ) ,
401- "sse" => McpPlugin . CreateSseTransport ( config ) ,
402- "streamablehttp" => McpPlugin . CreateStreamableHttpTransport ( config ) ,
403- _ => throw new NotSupportedException ( $ "不支持的传输类型: { config . TransportType } ")
404- } ;
405-
406- var options = new McpClientOptions
407- {
408- ClientInfo = new ( ) { Name = config . Name , Version = "1.0.0" }
409- } ;
410-
411- var mcpClient = await McpClientFactory . CreateAsync ( clientTransport , options ) ;
412- _mcpClients . Add ( mcpClient ) ;
413-
414- var tools = await mcpClient . ListToolsAsync ( ) ;
415- _mcpTools . AddRange ( tools . Cast < AITool > ( ) ) ;
416-
417- _logger . LogInformation ( "成功连接到 MCP 服务器 {Name},加载 {Count} 个工具" ,
418- config . Name , tools . Count ) ;
419- }
420- catch ( Exception ex )
421- {
422- _logger . LogWarning ( ex , "连接到 MCP 服务器 {Name} 失败" , config . Name ) ;
423- }
424- }
386+ var enabledConfigs = McpService . GetEnabledConfigs ( ) ;
387+ var tools = await _mcpService . GetAIToolsAsync ( enabledConfigs , manageClientLifetime : true ) ;
388+ _mcpTools . AddRange ( tools ) ;
425389
426390 if ( _mcpTools . Count == 0 )
427391 {
428392 _logger . LogInformation ( "未加载任何 MCP 工具" ) ;
429393 }
394+ else
395+ {
396+ _logger . LogInformation ( "成功加载 {Count} 个 MCP 工具" , _mcpTools . Count ) ;
397+ }
430398 }
431399 catch ( Exception ex )
432400 {
433401 _logger . LogError ( ex , "初始化 MCP 服务失败" ) ;
434402 }
435403 }
436404
437- /// <summary>
438- /// 创建 Stdio 传输
439- /// </summary>
440- private static IClientTransport CreateStdioTransport ( MCPServerConfig config )
441- {
442- var arguments = string . IsNullOrEmpty ( config . Arguments )
443- ? Array . Empty < string > ( )
444- : config . Arguments . Split ( ' ' , StringSplitOptions . RemoveEmptyEntries ) ;
445-
446- return new StdioClientTransport ( new ( )
447- {
448- Name = config . Name ,
449- Command = config . Command ,
450- Arguments = arguments ,
451- EnvironmentVariables = config . EnvironmentVariables
452- } ) ;
453- }
454-
455405 /// <summary>
456406 /// 更新系统上下文
457407 /// </summary>
@@ -673,8 +623,8 @@ private async Task<string> CreateCompressionSummaryAsync(IEnumerable<ChatMessage
673623 new ( ChatRole . User , combinedText )
674624 } ;
675625
676- var chatCompletion = await _chatClient . CompleteAsync ( compressionHistory , cancellationToken : CancellationToken . None ) ;
677- return chatCompletion . Message . Text ? . Trim ( ) ?? string . Empty ;
626+ var chatCompletion = await _chatClient . GetResponseAsync ( compressionHistory , cancellationToken : CancellationToken . None ) ;
627+ return chatCompletion . Text ? . Trim ( ) ?? string . Empty ;
678628 }
679629 catch ( Exception ex )
680630 {
0 commit comments