-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpGatewayAutoDiscoveryChatClient.cs
More file actions
264 lines (220 loc) · 9.46 KB
/
McpGatewayAutoDiscoveryChatClient.cs
File metadata and controls
264 lines (220 loc) · 9.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
using System.Text.Json;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ManagedCode.MCPGateway;
public sealed class McpGatewayAutoDiscoveryChatClient : IChatClient
{
private readonly IChatClient _innerClient;
private readonly ILoggerFactory _loggerFactory;
private readonly IServiceProvider _functionInvocationServices;
private readonly McpGatewayToolSet _toolSet;
private readonly McpGatewayAutoDiscoveryOptions _options;
public McpGatewayAutoDiscoveryChatClient(
IChatClient innerClient,
McpGatewayToolSet toolSet,
ILoggerFactory? loggerFactory = null,
IServiceProvider? functionInvocationServices = null,
McpGatewayAutoDiscoveryOptions? options = null)
{
ArgumentNullException.ThrowIfNull(innerClient);
ArgumentNullException.ThrowIfNull(toolSet);
_innerClient = innerClient;
_toolSet = toolSet;
_loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
_functionInvocationServices = functionInvocationServices ?? EmptyServiceProvider.Instance;
_options = options?.Clone() ?? new McpGatewayAutoDiscoveryOptions();
}
public async Task<ChatResponse> GetResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options = null,
CancellationToken cancellationToken = default)
{
using var functionInvokingChatClient = CreateFunctionInvokingChatClient();
return await functionInvokingChatClient.GetResponseAsync(messages, options, cancellationToken);
}
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options = null,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
{
using var functionInvokingChatClient = CreateFunctionInvokingChatClient();
await foreach (var update in functionInvokingChatClient.GetStreamingResponseAsync(messages, options, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
yield return update;
}
}
public object? GetService(Type serviceType, object? serviceKey = null)
{
ArgumentNullException.ThrowIfNull(serviceType);
if (serviceKey is null && serviceType.IsInstanceOfType(this))
{
return this;
}
return _innerClient.GetService(serviceType, serviceKey);
}
public void Dispose() => _innerClient.Dispose();
private FunctionInvokingChatClient CreateFunctionInvokingChatClient()
{
FunctionInvokingChatClient? functionInvokingChatClient = null;
void UpdateAdditionalTools(IReadOnlyList<AITool> gatewayTools)
{
var invokingChatClient = functionInvokingChatClient;
if (invokingChatClient is null)
{
return;
}
invokingChatClient.AdditionalTools = gatewayTools.ToList();
}
var requestClient = new AutoDiscoveryRequestChatClient(
_innerClient,
_toolSet,
_options,
UpdateAdditionalTools);
functionInvokingChatClient = new FunctionInvokingChatClient(
requestClient,
_loggerFactory,
_functionInvocationServices);
return functionInvokingChatClient;
}
private sealed class AutoDiscoveryRequestChatClient(
IChatClient innerClient,
McpGatewayToolSet toolSet,
McpGatewayAutoDiscoveryOptions options,
Action<IReadOnlyList<AITool>> updateAdditionalTools) : IChatClient
{
private readonly IChatClient _innerClient = innerClient;
private readonly McpGatewayToolSet _toolSet = toolSet;
private readonly McpGatewayAutoDiscoveryOptions _options = options;
private readonly Action<IReadOnlyList<AITool>> _updateAdditionalTools = updateAdditionalTools;
public Task<ChatResponse> GetResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options = null,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var messageList = messages as IReadOnlyList<ChatMessage> ?? messages.ToList();
var gatewayTools = CreateGatewayTools(messageList);
_updateAdditionalTools(gatewayTools);
return _innerClient.GetResponseAsync(
messageList,
CreateOptions(options, gatewayTools),
cancellationToken);
}
public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options = null,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var messageList = messages as IReadOnlyList<ChatMessage> ?? messages.ToList();
var gatewayTools = CreateGatewayTools(messageList);
_updateAdditionalTools(gatewayTools);
return _innerClient.GetStreamingResponseAsync(
messageList,
CreateOptions(options, gatewayTools),
cancellationToken);
}
public object? GetService(Type serviceType, object? serviceKey = null)
{
ArgumentNullException.ThrowIfNull(serviceType);
return _innerClient.GetService(serviceType, serviceKey);
}
public void Dispose()
{
}
private IReadOnlyList<AITool> CreateGatewayTools(IReadOnlyList<ChatMessage> messages)
{
var gatewayTools = _toolSet
.CreateTools(_options.SearchToolName, _options.InvokeToolName)
.ToList();
var latestSearchResult = FindLatestSearchResult(messages);
if (latestSearchResult?.Matches.Count is not > 0)
{
return gatewayTools;
}
var reservedToolNames = new HashSet<string>(
gatewayTools.Select(static tool => tool.Name),
StringComparer.OrdinalIgnoreCase);
foreach (var discoveredTool in _toolSet.CreateDiscoveredTools(
latestSearchResult.Matches,
reservedToolNames,
Math.Max(0, _options.MaxDiscoveredTools)))
{
gatewayTools.Add(discoveredTool);
}
return gatewayTools;
}
private static ChatOptions CreateOptions(ChatOptions? options, IReadOnlyList<AITool> gatewayTools)
{
var effectiveOptions = options?.Clone() ?? new ChatOptions();
var effectiveTools = effectiveOptions.Tools is { Count: > 0 }
? effectiveOptions.Tools.ToList()
: [];
foreach (var gatewayTool in gatewayTools)
{
if (effectiveTools.Any(existingTool =>
string.Equals(existingTool.Name, gatewayTool.Name, StringComparison.OrdinalIgnoreCase)))
{
continue;
}
effectiveTools.Add(gatewayTool);
}
effectiveOptions.Tools = effectiveTools;
return effectiveOptions;
}
private McpGatewaySearchResult? FindLatestSearchResult(IReadOnlyList<ChatMessage> messages)
{
var functionNamesByCallId = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
McpGatewaySearchResult? latestSearchResult = null;
foreach (var message in messages)
{
foreach (var content in message.Contents)
{
switch (content)
{
case FunctionCallContent functionCall:
functionNamesByCallId[functionCall.CallId] = functionCall.Name;
break;
case FunctionResultContent functionResult
when functionNamesByCallId.TryGetValue(functionResult.CallId, out var functionName) &&
string.Equals(functionName, _options.SearchToolName, StringComparison.OrdinalIgnoreCase):
latestSearchResult = ReadSearchResult(functionResult.Result);
break;
}
}
}
return latestSearchResult;
}
private static McpGatewaySearchResult? ReadSearchResult(object? result)
{
if (result is McpGatewaySearchResult searchResult)
{
return searchResult;
}
var serialized = McpGatewayJsonSerializer.TrySerializeToElement(result);
if (serialized is not JsonElement { ValueKind: JsonValueKind.Object } jsonElement)
{
return null;
}
try
{
return jsonElement.Deserialize<McpGatewaySearchResult>(McpGatewayJsonSerializer.Options);
}
catch (JsonException)
{
return null;
}
}
}
private sealed class EmptyServiceProvider : IServiceProvider
{
public static EmptyServiceProvider Instance { get; } = new();
public object? GetService(Type serviceType)
{
ArgumentNullException.ThrowIfNull(serviceType);
return null;
}
}
}