-
Notifications
You must be signed in to change notification settings - Fork 681
Expand file tree
/
Copy pathAIFunctionMcpServerPrompt.cs
More file actions
253 lines (212 loc) · 9.87 KB
/
AIFunctionMcpServerPrompt.cs
File metadata and controls
253 lines (212 loc) · 9.87 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
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Protocol;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace ModelContextProtocol.Server;
/// <summary>Provides an <see cref="McpServerPrompt"/> that's implemented via an <see cref="AIFunction"/>.</summary>
internal sealed class AIFunctionMcpServerPrompt : McpServerPrompt
{
private readonly IReadOnlyList<object> _metadata;
/// <summary>
/// Creates an <see cref="McpServerPrompt"/> instance for a method, specified via a <see cref="Delegate"/> instance.
/// </summary>
public static new AIFunctionMcpServerPrompt Create(
Delegate method,
McpServerPromptCreateOptions? options)
{
Throw.IfNull(method);
options = DeriveOptions(method.Method, options);
return Create(method.Method, method.Target, options);
}
/// <summary>
/// Creates an <see cref="McpServerPrompt"/> instance for a method, specified via a <see cref="MethodInfo"/> instance.
/// </summary>
public static new AIFunctionMcpServerPrompt Create(
MethodInfo method,
object? target,
McpServerPromptCreateOptions? options)
{
Throw.IfNull(method);
options = DeriveOptions(method, options);
return Create(
AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),
options);
}
/// <summary>
/// Creates an <see cref="McpServerPrompt"/> instance for a method, specified via a <see cref="MethodInfo"/> instance.
/// </summary>
public static new AIFunctionMcpServerPrompt Create(
MethodInfo method,
Func<RequestContext<GetPromptRequestParams>, object> createTargetFunc,
McpServerPromptCreateOptions? options)
{
Throw.IfNull(method);
Throw.IfNull(createTargetFunc);
options = DeriveOptions(method, options);
return Create(
AIFunctionFactory.Create(method, args =>
{
Debug.Assert(args.Services is RequestServiceProvider<GetPromptRequestParams>, $"The service provider should be a {nameof(RequestServiceProvider<>)} for this method to work correctly.");
return createTargetFunc(((RequestServiceProvider<GetPromptRequestParams>)args.Services!).Request);
}, CreateAIFunctionFactoryOptions(method, options)),
options);
}
private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
MethodInfo method, McpServerPromptCreateOptions? options) =>
new()
{
Name = options?.Name ?? method.GetCustomAttribute<McpServerPromptAttribute>()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),
Description = options?.Description,
MarshalResult = static (result, _, cancellationToken) => new ValueTask<object?>(result),
SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,
JsonSchemaCreateOptions = options?.SchemaCreateOptions,
ConfigureParameterBinding = pi =>
{
if (RequestServiceProvider<GetPromptRequestParams>.IsAugmentedWith(pi.ParameterType) ||
(options?.Services?.GetService<IServiceProviderIsService>() is { } ispis &&
ispis.IsService(pi.ParameterType)))
{
return new()
{
ExcludeFromSchema = true,
BindParameter = (pi, args) =>
args.Services?.GetService(pi.ParameterType) ??
(pi.HasDefaultValue ? null :
throw new ArgumentException("No service of the requested type was found.")),
};
}
if (pi.GetCustomAttribute<FromKeyedServicesAttribute>() is { } keyedAttr)
{
return new()
{
ExcludeFromSchema = true,
BindParameter = (pi, args) =>
(args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??
(pi.HasDefaultValue ? null :
throw new ArgumentException("No service of the requested type was found.")),
};
}
return default;
},
};
/// <summary>Creates an <see cref="McpServerPrompt"/> that wraps the specified <see cref="AIFunction"/>.</summary>
public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options)
{
Throw.IfNull(function);
List<PromptArgument> args = [];
HashSet<string>? requiredProps = function.JsonSchema.TryGetProperty("required", out JsonElement required)
? new(required.EnumerateArray().Select(p => p.GetString()!), StringComparer.Ordinal)
: null;
if (function.JsonSchema.TryGetProperty("properties", out JsonElement properties))
{
foreach (var param in properties.EnumerateObject())
{
args.Add(new()
{
Name = param.Name,
Description = param.Value.TryGetProperty("description", out JsonElement description) ? description.GetString() : null,
Required = requiredProps?.Contains(param.Name) ?? false,
});
}
}
Prompt prompt = new()
{
Name = options?.Name ?? function.Name,
Title = options?.Title,
Description = options?.Description ?? function.Description,
Arguments = args,
Icons = options?.Icons,
// Populate Meta from options and/or McpMetaAttribute instances if a MethodInfo is available
Meta = function.UnderlyingMethod is not null ?
AIFunctionMcpServerTool.CreateMetaFromAttributes(function.UnderlyingMethod, options?.Meta) :
options?.Meta
};
return new AIFunctionMcpServerPrompt(function, prompt, options?.Metadata ?? []);
}
private static McpServerPromptCreateOptions DeriveOptions(MethodInfo method, McpServerPromptCreateOptions? options)
{
McpServerPromptCreateOptions newOptions = options?.Clone() ?? new();
if (method.GetCustomAttribute<McpServerPromptAttribute>() is { } promptAttr)
{
newOptions.Name ??= promptAttr.Name;
newOptions.Title ??= promptAttr.Title;
// Handle icon from attribute if not already specified in options
if (newOptions.Icons is null && promptAttr.IconSource is { Length: > 0 } iconSource)
{
newOptions.Icons = [new() { Source = iconSource }];
}
}
if (method.GetCustomAttribute<DescriptionAttribute>() is { } descAttr)
{
newOptions.Description ??= descAttr.Description;
}
// Set metadata if not already provided
newOptions.Metadata ??= AIFunctionMcpServerTool.CreateMetadata(method);
return newOptions;
}
/// <summary>Gets the <see cref="AIFunction"/> wrapped by this prompt.</summary>
internal AIFunction AIFunction { get; }
/// <summary>Initializes a new instance of the <see cref="McpServerPrompt"/> class.</summary>
private AIFunctionMcpServerPrompt(AIFunction function, Prompt prompt, IReadOnlyList<object> metadata)
{
AIFunction = function;
ProtocolPrompt = prompt;
_metadata = metadata;
}
/// <inheritdoc />
public override Prompt ProtocolPrompt { get; }
/// <inheritdoc />
public override IReadOnlyList<object> Metadata => _metadata;
/// <inheritdoc />
public override async ValueTask<GetPromptResult> GetAsync(
RequestContext<GetPromptRequestParams> request, CancellationToken cancellationToken = default)
{
Throw.IfNull(request);
cancellationToken.ThrowIfCancellationRequested();
request.Services = new RequestServiceProvider<GetPromptRequestParams>(request);
AIFunctionArguments arguments = new() { Services = request.Services };
if (request.Params.Arguments is { } argDict)
{
foreach (var kvp in argDict)
{
arguments[kvp.Key] = kvp.Value;
}
}
object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);
return result switch
{
GetPromptResult getPromptResult => getPromptResult,
string text => new()
{
Description = ProtocolPrompt.Description,
Messages = [new() { Role = Role.User, Content = new TextContentBlock { Text = text } }],
},
PromptMessage promptMessage => new()
{
Description = ProtocolPrompt.Description,
Messages = [promptMessage],
},
IEnumerable<PromptMessage> promptMessages => new()
{
Description = ProtocolPrompt.Description,
Messages = [.. promptMessages],
},
ChatMessage chatMessage => new()
{
Description = ProtocolPrompt.Description,
Messages = [.. chatMessage.ToPromptMessages()],
},
IEnumerable<ChatMessage> chatMessages => new()
{
Description = ProtocolPrompt.Description,
Messages = [.. chatMessages.SelectMany(chatMessage => chatMessage.ToPromptMessages())],
},
null => throw new InvalidOperationException("Null result returned from prompt function."),
_ => throw new InvalidOperationException($"Unknown result type '{result.GetType()}' returned from prompt function."),
};
}
}