-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpGatewayToolSet.cs
More file actions
362 lines (323 loc) · 13.4 KB
/
Copy pathMcpGatewayToolSet.cs
File metadata and controls
362 lines (323 loc) · 13.4 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
using ManagedCode.MCPGateway.Abstractions;
using Microsoft.Extensions.AI;
namespace ManagedCode.MCPGateway;
public sealed class McpGatewayToolSet
{
public const string DefaultSearchToolName = "gateway_tools_search";
public const string DefaultRouteToolName = "gateway_tools_route";
public const string DefaultInvokeToolName = "gateway_tool_invoke";
public const string DefaultGraphSearchToolName = "gateway_graph_schema_search";
public const string DefaultGraphFederatedSearchToolName = "gateway_graph_federated_search";
public const string DefaultGraphExportToolName = "gateway_graph_export";
public const string DefaultGraphSchemaToolName = "gateway_graph_schema_describe";
public const string DefaultToolIndexBuildToolName = "gateway_tool_index_build";
public const string DiscoveredToolIdPropertyName = "ManagedCode.MCPGateway.ToolId";
public const string DiscoveredToolSourceIdPropertyName = "ManagedCode.MCPGateway.SourceId";
public const string DiscoveredToolKindPropertyName = "ManagedCode.MCPGateway.Kind";
public const string SearchToolDescription =
"Search the gateway catalog and return the best matching tools for a user task.";
public const string RouteToolDescription =
"Route a task into the best tool categories first, then return the strongest tools per category.";
public const string InvokeToolDescription =
"Invoke a gateway tool by tool id. Search first when the correct tool is unknown.";
public const string GraphSearchToolDescription =
"Run schema-aware Markdown-LD graph search and return graph matches, evidence, generated SPARQL, and mapped gateway tools.";
public const string GraphFederatedSearchToolDescription =
"Run explicit allowlisted federated Markdown-LD graph search across the gateway graph and configured SPARQL services.";
public const string GraphExportToolDescription =
"Export the current Markdown-LD gateway graph as JSON-LD, Turtle, Mermaid, and DOT artifacts.";
public const string GraphSchemaToolDescription =
"Describe the schema-aware Markdown-LD graph profile used to compile SPARQL and validate the current tool graph.";
public const string ToolIndexBuildToolDescription =
"Build or rebuild the gateway tool index and return graph, vector, and diagnostic state.";
private const string GatewayToolSourceId = "gateway";
private const string DiscoveredToolKindValue = "gateway_discovered_tool";
private readonly IMcpGateway _gateway;
private readonly McpGatewayGraphToolFactory _graphTools;
public McpGatewayToolSet(IMcpGateway gateway)
{
ArgumentNullException.ThrowIfNull(gateway);
_gateway = gateway;
_graphTools = new McpGatewayGraphToolFactory(gateway, gateway as IMcpGatewayGraphSearch);
}
public McpGatewayToolSet(IMcpGateway gateway, IMcpGatewayGraphSearch graphSearch)
{
ArgumentNullException.ThrowIfNull(gateway);
ArgumentNullException.ThrowIfNull(graphSearch);
_gateway = gateway;
_graphTools = new McpGatewayGraphToolFactory(gateway, graphSearch);
}
public IReadOnlyList<AITool> CreateTools(
string searchToolName = DefaultSearchToolName,
string routeToolName = DefaultRouteToolName,
string invokeToolName = DefaultInvokeToolName
)
{
var reservedNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var searchName = CreateToolName(searchToolName, DefaultSearchToolName, reservedNames);
var routeName = CreateToolName(routeToolName, DefaultRouteToolName, reservedNames);
var invokeName = CreateToolName(invokeToolName, DefaultInvokeToolName, reservedNames);
var searchTool = AIFunctionFactory.Create(
SearchAsync,
new AIFunctionFactoryOptions
{
Name = searchName,
Description = SearchToolDescription,
}
);
var routeTool = AIFunctionFactory.Create(
RouteAsync,
new AIFunctionFactoryOptions
{
Name = routeName,
Description = RouteToolDescription,
}
);
var invokeTool = AIFunctionFactory.Create(
InvokeAsync,
new AIFunctionFactoryOptions
{
Name = invokeName,
Description = InvokeToolDescription,
}
);
return [searchTool, routeTool, invokeTool];
}
public IReadOnlyList<AITool> CreateGraphTools(
string graphSearchToolName = DefaultGraphSearchToolName,
string graphFederatedSearchToolName = DefaultGraphFederatedSearchToolName,
string graphExportToolName = DefaultGraphExportToolName,
string graphSchemaToolName = DefaultGraphSchemaToolName,
string toolIndexBuildToolName = DefaultToolIndexBuildToolName
) =>
_graphTools.CreateGraphTools(
graphSearchToolName,
graphFederatedSearchToolName,
graphExportToolName,
graphSchemaToolName,
toolIndexBuildToolName
);
public IList<AITool> AddTools(
IList<AITool> tools,
string searchToolName = DefaultSearchToolName,
string routeToolName = DefaultRouteToolName,
string invokeToolName = DefaultInvokeToolName
)
{
ArgumentNullException.ThrowIfNull(tools);
var targetTools = new List<AITool>(tools);
var toolNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var tool in targetTools)
{
toolNames.Add(tool.Name);
toolNames.Add(NormalizeToolName(tool.Name, DefaultInvokeToolName));
}
foreach (var tool in CreateTools(searchToolName, routeToolName, invokeToolName))
{
if (toolNames.Add(tool.Name))
{
targetTools.Add(tool);
}
}
return targetTools;
}
public IList<AITool> AddGraphTools(
IList<AITool> tools,
string graphSearchToolName = DefaultGraphSearchToolName,
string graphFederatedSearchToolName = DefaultGraphFederatedSearchToolName,
string graphExportToolName = DefaultGraphExportToolName,
string graphSchemaToolName = DefaultGraphSchemaToolName,
string toolIndexBuildToolName = DefaultToolIndexBuildToolName
) =>
_graphTools.AddGraphTools(
tools,
graphSearchToolName,
graphFederatedSearchToolName,
graphExportToolName,
graphSchemaToolName,
toolIndexBuildToolName
);
public IReadOnlyList<AITool> CreateDiscoveredTools(
IEnumerable<McpGatewaySearchMatch> matches,
IReadOnlyCollection<string>? reservedToolNames = null,
int? maxTools = null
)
{
ArgumentNullException.ThrowIfNull(matches);
var toolLimit = maxTools.GetValueOrDefault(int.MaxValue);
if (toolLimit <= 0)
{
return [];
}
var discoveredTools = new List<AITool>();
var reservedNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (reservedToolNames is not null)
{
foreach (var reservedToolName in reservedToolNames)
{
if (!string.IsNullOrWhiteSpace(reservedToolName))
{
reservedNames.Add(reservedToolName);
reservedNames.Add(NormalizeToolName(reservedToolName, DefaultInvokeToolName));
}
}
}
foreach (var match in matches)
{
if (discoveredTools.Count == toolLimit)
{
break;
}
var functionName = McpGatewayDiscoveredToolNaming.CreateName(match, reservedNames);
discoveredTools.Add(CreateDiscoveredTool(match, functionName));
}
return discoveredTools;
}
public Task<McpGatewaySearchResult> SearchAsync(
string query,
int? maxResults = null,
Dictionary<string, object?>? context = null,
string? contextSummary = null,
CancellationToken cancellationToken = default
) =>
_gateway.SearchAsync(
new McpGatewaySearchRequest(
Query: query,
MaxResults: maxResults,
Context: context,
ContextSummary: contextSummary
),
cancellationToken
);
public Task<McpGatewayInvokeResult> InvokeAsync(
string toolId,
Dictionary<string, object?>? arguments = null,
string? query = null,
Dictionary<string, object?>? context = null,
string? contextSummary = null,
CancellationToken cancellationToken = default
) =>
_gateway.InvokeAsync(
new McpGatewayInvokeRequest(
ToolId: toolId,
Arguments: arguments,
Query: query,
Context: context,
ContextSummary: contextSummary
),
cancellationToken
);
public Task<McpGatewayGraphSchemaResult> DescribeGraphSchemaAsync(
CancellationToken cancellationToken = default
) => _graphTools.DescribeGraphSchemaAsync(cancellationToken);
public Task<McpGatewayIndexBuildResult> BuildToolIndexAsync(
CancellationToken cancellationToken = default
) => _graphTools.BuildToolIndexAsync(cancellationToken);
public Task<McpGatewayGraphSearchResult> SchemaGraphSearchAsync(
string query,
int? maxResults = null,
CancellationToken cancellationToken = default
) => _graphTools.SchemaGraphSearchAsync(query, maxResults, cancellationToken);
public Task<McpGatewayGraphSearchResult> FederatedGraphSearchAsync(
string query,
int? maxResults = null,
IReadOnlyList<string>? serviceEndpoints = null,
bool includeLocalGatewayGraph = true,
CancellationToken cancellationToken = default
) =>
_graphTools.FederatedGraphSearchAsync(
query,
maxResults,
serviceEndpoints,
includeLocalGatewayGraph,
cancellationToken
);
public Task<McpGatewayMarkdownLdGraphExport> ExportGraphAsync(
CancellationToken cancellationToken = default
) => _graphTools.ExportGraphAsync(cancellationToken);
public Task<McpGatewayToolRouteResult> RouteAsync(
string query,
int? maxCategories = null,
int? maxToolsPerCategory = null,
Dictionary<string, object?>? context = null,
string? contextSummary = null,
bool? preferReadOnly = null,
bool includeDisabledTools = false,
CancellationToken cancellationToken = default
) =>
_gateway.RouteToolsAsync(
new McpGatewayToolRouteRequest(
Query: query,
MaxCategories: maxCategories,
MaxToolsPerCategory: maxToolsPerCategory,
Context: context,
ContextSummary: contextSummary,
PreferReadOnly: preferReadOnly,
IncludeDisabledTools: includeDisabledTools
),
cancellationToken
);
private AITool CreateDiscoveredTool(McpGatewaySearchMatch match, string functionName)
{
Task<McpGatewayInvokeResult> InvokeDiscoveredToolAsync(
Dictionary<string, object?>? arguments = null,
string? query = null,
Dictionary<string, object?>? context = null,
string? contextSummary = null,
CancellationToken cancellationToken = default
) =>
_gateway.InvokeAsync(
new McpGatewayInvokeRequest(
ToolId: match.ToolId,
Arguments: arguments,
Query: query,
Context: context,
ContextSummary: contextSummary
),
cancellationToken
);
return AIFunctionFactory.Create(
(Func<
Dictionary<string, object?>?,
string?,
Dictionary<string, object?>?,
string?,
CancellationToken,
Task<McpGatewayInvokeResult>
>)
InvokeDiscoveredToolAsync,
new AIFunctionFactoryOptions
{
Name = functionName,
Description = McpGatewayDiscoveredToolNaming.BuildDescription(match),
AdditionalProperties = new Dictionary<string, object?>
{
[DiscoveredToolIdPropertyName] = match.ToolId,
[DiscoveredToolSourceIdPropertyName] = match.SourceId,
[DiscoveredToolKindPropertyName] = DiscoveredToolKindValue,
},
}
);
}
internal static string CreateToolName(
string toolName,
string fallback,
ISet<string> reservedNames
)
{
ArgumentNullException.ThrowIfNull(reservedNames);
var normalizedName = NormalizeToolName(toolName, fallback);
if (reservedNames.Add(normalizedName))
{
return normalizedName;
}
return McpGatewayProtocolName.CreateToolId(
GatewayToolSourceId,
normalizedName,
reservedNames,
requireSourcePrefix: true
);
}
internal static string NormalizeToolName(string toolName, string fallback) =>
McpGatewayProtocolName.Normalize(toolName, fallback);
}