-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
280 lines (237 loc) · 9.53 KB
/
Program.cs
File metadata and controls
280 lines (237 loc) · 9.53 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
using System.Collections.Concurrent;
using Anthropic;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
using SkillsDotNet.Mcp;
// --- Configuration ---
// Server configs the client host knows about. In a real app this might come from
// a config file, user settings, or a registry. The key point is that the client host
// owns this mapping — the skill library only communicates server names.
var serverConfigs = new Dictionary<string, Func<Task<McpClient>>>
{
["everything-server"] = () => McpClient.CreateAsync(
new StdioClientTransport(new()
{
Name = "everything-server",
Command = "npx",
Arguments = ["-y", "@modelcontextprotocol/server-everything"],
})),
};
var serverProject = args.Length > 0
? args[0]
: Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "SkillServer"));
var model = Environment.GetEnvironmentVariable("ANTHROPIC_MODEL") ?? "claude-sonnet-4-6";
// --- Track dynamically connected MCP servers ---
var connectedServers = new ConcurrentDictionary<string, McpClient>();
// --- Connect to skill server ---
Console.WriteLine($"Connecting to skill server: {serverProject}");
await using var skillClient = await McpClient.CreateAsync(
new StdioClientTransport(new()
{
Name = "SkillServer",
Command = "dotnet",
Arguments = ["run", "--no-launch-profile", "--project", serverProject],
}));
// --- Build skill catalog with dependency callback ---
var catalog = await SkillCatalog.CreateAsync(skillClient);
// We need to create this so it will be in scope for the callback
var options = new ChatOptions { };
// Rebuilds options.Tools from the current catalog + connected-servers state.
// Called at every turn AND inside the dependency callbacks, so newly-connected
// server tools become visible to the model on the very next round-trip within
// the same turn (FunctionInvokingChatClient re-reads options.Tools each iteration).
async Task RefreshToolsAsync()
{
var tools = new List<AITool>(catalog.Tools);
foreach (var (_, client) in connectedServers)
{
var mcpTools = await client.ListToolsAsync();
tools.AddRange(mcpTools);
}
options.Tools = tools;
}
// This is the key part: when a skill is loaded that declares dependencies,
// the callback fires and the client host connects to the required MCP servers.
catalog.OnDependenciesRequired = async (request, cancellationToken) =>
{
Console.WriteLine($"\n[host] Skill '{request.SkillName}' requires MCP servers: {string.Join(", ", request.ServerNames)}");
foreach (var serverName in request.ServerNames)
{
if (connectedServers.ContainsKey(serverName))
{
Console.WriteLine($"[host] '{serverName}' is already connected.");
continue;
}
if (!serverConfigs.TryGetValue(serverName, out var factory))
{
Console.WriteLine($"[host] Unknown server '{serverName}' — cannot connect.");
return false;
}
Console.WriteLine($"[host] Connecting to '{serverName}'...");
try
{
var client = await factory();
connectedServers[serverName] = client;
Console.WriteLine($"[host] Connected to '{serverName}'.");
}
catch (Exception ex)
{
Console.WriteLine($"[host] Failed to connect to '{serverName}': {ex.Message}");
return false;
}
}
// Make the newly-connected server's tools visible to the model in the next
// round-trip of this same turn — without this, the model sees load_skill
// succeed but the server's tools are still missing until the next user turn.
await RefreshToolsAsync();
return true;
};
// Skills the model has unloaded *during* the current turn. We can't scrub the
// chat history mid-stream — FunctionInvokingChatClient is iterating it — so we
// queue the names here and process them after GetStreamingResponseAsync returns.
var pendingScrubs = new List<string>();
// Fires whenever a skill is unloaded (via the unload_skill tool or a direct call).
// The catalog computes which MCP servers are no longer needed by *any* still-loaded
// skill, so we can disconnect those without ref-counting. We also queue the skill
// name for message-history scrubbing once the streaming turn finishes.
catalog.OnSkillUnloaded = async (result, cancellationToken) =>
{
Console.WriteLine($"\n[host] Skill '{result.SkillName}' unloaded.");
foreach (var serverName in result.ReleasedServers)
{
if (!connectedServers.TryRemove(serverName, out var client))
{
continue;
}
Console.WriteLine($"[host] Disconnecting from '{serverName}'...");
try
{
await client.DisposeAsync();
}
catch (Exception ex)
{
Console.WriteLine($"[host] Error disconnecting from '{serverName}': {ex.Message}");
}
}
// Drop the disconnected servers' tools from options.Tools immediately, so the
// model can't keep calling them after the unload in the same turn.
await RefreshToolsAsync();
pendingScrubs.Add(result.SkillName);
};
// Walks the chat history and removes the load_skill call/result pair for the named
// skill — that's the SKILL.md content block plus the model's invocation that
// produced it. Run this AFTER the streaming turn completes so we don't mutate the
// list out from under FunctionInvokingChatClient.
static void ScrubLoadCallsForSkill(IList<ChatMessage> messages, string skillName)
{
// 1. Find every load_skill(skillName) call and collect its CallId.
var idsToScrub = new HashSet<string>(StringComparer.Ordinal);
foreach (var msg in messages)
{
foreach (var content in msg.Contents)
{
if (content is FunctionCallContent fcc
&& fcc.Name == "load_skill"
&& fcc.CallId is not null
&& fcc.Arguments is not null
&& fcc.Arguments.TryGetValue("skillName", out var v)
&& v?.ToString() == skillName)
{
idsToScrub.Add(fcc.CallId);
}
}
}
if (idsToScrub.Count == 0) return;
// 2. Filter contents in place; drop messages that become empty.
for (int i = messages.Count - 1; i >= 0; i--)
{
var msg = messages[i];
var filtered = msg.Contents.Where(c =>
!(c is FunctionCallContent fcc && fcc.CallId is not null && idsToScrub.Contains(fcc.CallId))
&& !(c is FunctionResultContent frc && idsToScrub.Contains(frc.CallId))
).ToList();
if (filtered.Count == 0)
{
messages.RemoveAt(i);
}
else if (filtered.Count != msg.Contents.Count)
{
msg.Contents = filtered;
}
}
}
Console.WriteLine($"Discovered {catalog.SkillNames.Count} skill(s):");
foreach (var name in catalog.SkillNames)
{
Console.WriteLine($" {name}");
}
Console.WriteLine();
// --- Set up chat client with function invocation ---
using IChatClient chatClient = new AnthropicClient()
.AsIChatClient(model)
.AsBuilder()
.UseFunctionInvocation()
.Build();
// --- System message with skill context ---
List<ChatMessage> messages =
[
new(ChatRole.System,
[
new TextContent(
"You are a helpful assistant. " +
"When the user asks you to perform a task that matches an available skill, " +
"use the load_skill tool to load the full skill instructions before proceeding. " +
"After a skill is loaded, its required MCP servers will be connected automatically " +
"and their tools will become available to you. " +
"It is very important you do not fake function calls - if the expected tools are missing, " +
"it means the server dependencies were not loaded and you should ask the user to clarify or try a different task. " +
"The following skills are available:"),
.. catalog.GetSkillContexts()
]),
];
// --- Chat loop ---
Console.WriteLine("Chat started. Type a message or Ctrl+C to exit.");
Console.WriteLine("Try: \"Explore the everything server and show me what tools it has.\"");
Console.WriteLine();
try
{
while (true)
{
Console.Write("Q: ");
var input = Console.ReadLine();
if (input is null)
break;
messages.Add(new(ChatRole.User, input));
await RefreshToolsAsync();
List<ChatResponseUpdate> updates = [];
await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options))
{
Console.Write(update);
updates.Add(update);
}
Console.WriteLine();
Console.WriteLine();
messages.AddMessages(updates);
// Now that the streaming iteration is done, it's safe to mutate `messages`.
// Drop the load_skill call/result pairs for any skills the model unloaded
// during this turn — that frees the SKILL.md context for good.
if (pendingScrubs.Count > 0)
{
foreach (var skillName in pendingScrubs)
{
ScrubLoadCallsForSkill(messages, skillName);
Console.WriteLine($"[host] Scrubbed load_skill call/result for '{skillName}' from message history.");
}
pendingScrubs.Clear();
}
}
}
finally
{
// Clean up dynamically connected servers
foreach (var (name, client) in connectedServers)
{
Console.WriteLine($"[host] Disconnecting from '{name}'...");
await client.DisposeAsync();
}
}