-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathUrlElicitationTests.cs
More file actions
570 lines (503 loc) · 22.9 KB
/
UrlElicitationTests.cs
File metadata and controls
570 lines (503 loc) · 22.9 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol.Tests.Configuration;
public partial class UrlElicitationTests(ITestOutputHelper testOutputHelper) : ClientServerTestBase(testOutputHelper)
{
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
mcpServerBuilder.WithCallToolHandler(async (request, cancellationToken) =>
{
Assert.NotNull(request.Params);
if (request.Params.Name == "TestUrlElicitation")
{
var result = await request.Server.ElicitAsync(new()
{
Mode = "url",
ElicitationId = "test-elicitation-id",
Url = $"https://auth.example.com/oauth/authorize?state=test-elicitation-id",
Message = "Please authorize access to your account by logging in through your browser.",
},
cancellationToken);
// For URL mode, we expect the client to accept (consent to navigate)
// The actual OAuth flow happens out-of-band
Assert.Equal("accept", result.Action);
await request.Server.SendNotificationAsync(
NotificationMethods.ElicitationCompleteNotification,
new ElicitationCompleteNotificationParams
{
ElicitationId = "test-elicitation-id",
},
McpJsonUtilities.DefaultOptions,
cancellationToken);
return new CallToolResult
{
Content = [new TextContentBlock { Text = "authorization-pending:test-elicitation-id" }],
};
}
else if (request.Params.Name == "TestUrlElicitationDecline")
{
var elicitationId = Guid.NewGuid().ToString();
var result = await request.Server.ElicitAsync(new()
{
Mode = "url",
ElicitationId = "elicitation-declined-id",
Url = $"https://payment.example.com/pay?transaction=elicitation-declined-id",
Message = "Please complete payment in your browser.",
},
cancellationToken);
// User declined
Assert.Equal("decline", result.Action);
return new CallToolResult
{
Content = [new TextContentBlock { Text = "payment-declined" }],
};
}
else if (request.Params.Name == "TestUrlElicitationCancel")
{
var elicitationId = Guid.NewGuid().ToString();
var result = await request.Server.ElicitAsync(new()
{
Mode = "url",
ElicitationId = "elicitation-canceled-id",
Url = $"https://verify.example.com/verify?id=elicitation-canceled-id",
Message = "Please verify your identity.",
},
cancellationToken);
// User canceled (dismissed without explicit choice)
Assert.Equal("cancel", result.Action);
return new CallToolResult
{
Content = [new TextContentBlock { Text = "verification-canceled" }],
};
}
else if (request.Params.Name == "TestUrlElicitationRequired")
{
throw new UrlElicitationRequiredException(
"Authorization is required to continue.",
new[]
{
new ElicitRequestParams
{
Mode = "url",
ElicitationId = "elicitation-required-id",
Url = "https://auth.example.com/connect?elicitationId=elicitation-required-id",
Message = "Authorization is required to access Example Co.",
}
});
}
else if (request.Params.Name == "TestUrlElicitationMissingId")
{
try
{
await request.Server.ElicitAsync(new()
{
Mode = "url",
Url = "https://missing-id.example.com/oauth",
Message = "URL elicitation without ID should fail.",
},
cancellationToken);
}
catch (ArgumentException ex)
{
throw new McpException(ex.Message);
}
return new CallToolResult
{
Content = [new TextContentBlock { Text = "missing-id-succeeded" }],
};
}
else if (request.Params.Name == "ProbeUrlCapability")
{
try
{
await request.Server.ElicitAsync(new()
{
Mode = "url",
ElicitationId = Guid.NewGuid().ToString(),
Url = "https://probe.example.com/oauth",
Message = "Capability probe for url mode.",
},
cancellationToken);
return new CallToolResult
{
Content = [new TextContentBlock { Text = "url-allowed" }],
};
}
catch (InvalidOperationException ex)
{
throw new McpException(ex.Message);
}
}
else if (request.Params.Name == "ProbeFormCapability")
{
try
{
var elicitationResult = await request.Server.ElicitAsync(new()
{
Message = "Capability probe for form mode.",
RequestedSchema = new(),
},
cancellationToken: cancellationToken);
return new CallToolResult
{
Content = [new TextContentBlock { Text = $"form-allowed:{elicitationResult.Action}" }],
};
}
catch (InvalidOperationException ex)
{
throw new McpException(ex.Message);
}
}
else if (request.Params.Name == "TestFormElicitationMissingSchema")
{
try
{
await request.Server.ElicitAsync(new()
{
Message = "Form elicitation without schema should fail.",
},
cancellationToken);
}
catch (ArgumentException ex)
{
throw new McpException(ex.Message);
}
return new CallToolResult
{
Content = [new TextContentBlock { Text = "missing-schema-succeeded" }],
};
}
Assert.Fail($"Unexpected tool name: {request.Params.Name}");
return new CallToolResult { Content = [] };
});
}
[Fact]
public async Task Can_Elicit_OutOfBand_With_Url()
{
string? capturedElicitationId = null;
string? capturedUrl = null;
string? capturedMessage = null;
var completionNotification = new TaskCompletionSource<string?>(TaskCreationOptions.RunContinuationsAsynchronously);
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
// Explicitly declare support for both modes
Elicitation = new ElicitationCapability
{
Form = new FormElicitationCapability(),
Url = new UrlElicitationCapability()
}
},
Handlers = new McpClientHandlers()
{
ElicitationHandler = async (request, cancellationToken) =>
{
Assert.NotNull(request);
// Verify this is an URL mode elicitation request
Assert.NotNull(request.Mode);
Assert.Equal("url", request.Mode);
// Capture the request details
capturedElicitationId = request.ElicitationId;
capturedUrl = request.Url;
capturedMessage = request.Message;
// Verify URL-specific fields
Assert.NotNull(request.ElicitationId);
Assert.NotNull(request.Url);
Assert.StartsWith("https://auth.example.com/oauth/authorize", request.Url);
Assert.Contains("state=", request.Url);
Assert.Equal("Please authorize access to your account by logging in through your browser.", request.Message);
// Verify that RequestedSchema is null for URL mode
Assert.Null(request.RequestedSchema);
// Simulate user consent to navigate to the URL
// In a real implementation, the client would:
// 1. Display a consent dialog showing the URL and message
// 2. Open the URL in the system browser
// 3. Return "accept" to indicate user consented
// Return accept (user consented to navigate)
return new ElicitResult
{
Action = "accept",
// Note: No Content for URL mode - the actual interaction happens out-of-band
};
}
}
});
await using var completionHandler = client.RegisterNotificationHandler(
NotificationMethods.ElicitationCompleteNotification,
async (notification, cancellationToken) =>
{
var payload = notification.Params?.Deserialize<ElicitationCompleteNotificationParams>(McpJsonUtilities.DefaultOptions);
if (payload is not null)
{
completionNotification.TrySetResult(payload.ElicitationId);
}
await Task.CompletedTask;
});
var result = await client.CallToolAsync("TestUrlElicitation", cancellationToken: TestContext.Current.CancellationToken);
// Verify the tool completed successfully
Assert.Single(result.Content);
var textContent = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.StartsWith("authorization-pending:", textContent.Text);
// Verify we captured all the expected URL mode elicitation data
Assert.NotNull(capturedElicitationId);
Assert.NotNull(capturedUrl);
Assert.NotNull(capturedMessage);
Assert.Contains(capturedElicitationId, capturedUrl);
var notifiedElicitationId = await completionNotification.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
Assert.Equal(capturedElicitationId, notifiedElicitationId);
}
[Fact]
public async Task UrlElicitation_User_Can_Decline()
{
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
Elicitation = new ElicitationCapability
{
Url = new UrlElicitationCapability()
}
},
Handlers = new McpClientHandlers()
{
ElicitationHandler = async (request, cancellationToken) =>
{
Assert.NotNull(request);
Assert.NotNull(request.Mode);
Assert.Equal("url", request.Mode);
Assert.Contains("payment.example.com", request.Url);
// Simulate user declining to navigate to the URL
// This might happen if user doesn't trust the URL or doesn't want to proceed
return new ElicitResult
{
Action = "decline"
};
}
}
});
var result = await client.CallToolAsync("TestUrlElicitationDecline", cancellationToken: TestContext.Current.CancellationToken);
// Server should handle decline gracefully
Assert.Single(result.Content);
var textContent = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("payment-declined", textContent.Text);
}
[Fact]
public async Task UrlElicitation_User_Can_Cancel()
{
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
Elicitation = new ElicitationCapability
{
Url = new UrlElicitationCapability()
}
},
Handlers = new McpClientHandlers()
{
ElicitationHandler = async (request, cancellationToken) =>
{
Assert.NotNull(request);
Assert.NotNull(request.Mode);
Assert.Equal("url", request.Mode);
Assert.Contains("verify.example.com", request.Url);
// Simulate user canceling (dismissing dialog without explicit choice)
return new ElicitResult
{
Action = "cancel"
};
}
}
});
var result = await client.CallToolAsync("TestUrlElicitationCancel", cancellationToken: TestContext.Current.CancellationToken);
// Server should handle cancellation
Assert.Single(result.Content);
var textContent = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("verification-canceled", textContent.Text);
}
[Fact]
public async Task UrlElicitation_Defaults_To_Unsupported_When_Handler_Provided()
{
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Handlers = new McpClientHandlers()
{
ElicitationHandler = (request, cancellationToken) =>
{
throw new InvalidOperationException("URL handler should not be invoked in default mode.");
},
}
});
var defaultCapability = AssertServerElicitationCapability();
Assert.NotNull(defaultCapability.Form);
Assert.Null(defaultCapability.Url);
var result = await client.CallToolAsync("ProbeUrlCapability", cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError);
var textContent = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("An error occurred invoking 'ProbeUrlCapability': Client does not support URL mode elicitation requests.", textContent.Text);
}
[Fact]
public async Task FormElicitation_Defaults_To_Supported_When_Handler_Provided()
{
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Handlers = new McpClientHandlers()
{
ElicitationHandler = (_, _) => new ValueTask<ElicitResult>(new ElicitResult { Action = "decline" }),
}
});
var capability = AssertServerElicitationCapability();
Assert.NotNull(capability.Form);
Assert.Null(capability.Url);
var result = await client.CallToolAsync("ProbeFormCapability", cancellationToken: TestContext.Current.CancellationToken);
var textContent = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("form-allowed:decline", textContent.Text);
}
[Fact]
public async Task UrlElicitation_BlankCapability_Allows_Only_Form()
{
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
Elicitation = new ElicitationCapability(),
},
Handlers = new McpClientHandlers()
{
ElicitationHandler = (_, _) => new ValueTask<ElicitResult>(new ElicitResult { Action = "decline" }),
}
});
var capability = AssertServerElicitationCapability();
Assert.NotNull(capability.Form);
Assert.Null(capability.Url);
var urlResult = await client.CallToolAsync("ProbeUrlCapability", cancellationToken: TestContext.Current.CancellationToken);
Assert.True(urlResult.IsError);
var urlTextContent = Assert.IsType<TextContentBlock>(urlResult.Content[0]);
Assert.Equal("An error occurred invoking 'ProbeUrlCapability': Client does not support URL mode elicitation requests.", urlTextContent.Text);
var formResult = await client.CallToolAsync("ProbeFormCapability", cancellationToken: TestContext.Current.CancellationToken);
var textContent = Assert.IsType<TextContentBlock>(formResult.Content[0]);
Assert.Equal("form-allowed:decline", textContent.Text);
}
[Fact]
public async Task FormElicitation_UrlOnlyCapability_NotSupported()
{
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
Elicitation = new ElicitationCapability
{
Url = new UrlElicitationCapability(),
}
},
Handlers = new McpClientHandlers()
{
ElicitationHandler = (request, cancellationToken) =>
{
Assert.NotNull(request);
Assert.Equal("url", request.Mode);
return new ValueTask<ElicitResult>(new ElicitResult { Action = "decline" });
},
}
});
var capability = AssertServerElicitationCapability();
Assert.Null(capability.Form);
Assert.NotNull(capability.Url);
var urlResult = await client.CallToolAsync("ProbeUrlCapability", cancellationToken: TestContext.Current.CancellationToken);
var urlText = Assert.IsType<TextContentBlock>(urlResult.Content[0]);
Assert.Equal("url-allowed", urlText.Text);
var formResult = await client.CallToolAsync("ProbeFormCapability", cancellationToken: TestContext.Current.CancellationToken);
Assert.True(formResult.IsError);
var formText = Assert.IsType<TextContentBlock>(formResult.Content[0]);
Assert.Equal("An error occurred invoking 'ProbeFormCapability': Client does not support form mode elicitation requests.", formText.Text);
}
[Fact]
public async Task UrlElicitation_Requires_ElicitationId_For_Url_Mode()
{
var elicitationHandlerCalled = false;
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
Elicitation = new ElicitationCapability
{
Url = new UrlElicitationCapability(),
}
},
Handlers = new McpClientHandlers()
{
ElicitationHandler = (request, cancellationToken) =>
{
elicitationHandlerCalled = true;
return new ValueTask<ElicitResult>(new ElicitResult());
},
}
});
var result = await client.CallToolAsync("TestUrlElicitationMissingId", cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError);
var textContent = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("An error occurred invoking 'TestUrlElicitationMissingId': URL mode elicitation requests require an elicitation ID.", textContent.Text);
Assert.False(elicitationHandlerCalled);
}
[Fact]
public async Task UrlElicitationRequired_Exception_Propagates_To_Client()
{
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
Elicitation = new ElicitationCapability
{
Url = new UrlElicitationCapability(),
}
}
});
var exception = await Assert.ThrowsAsync<UrlElicitationRequiredException>(
async () => await client.CallToolAsync("TestUrlElicitationRequired", cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal(McpErrorCode.UrlElicitationRequired, exception.ErrorCode);
var elicitation = Assert.Single(exception.Elicitations);
Assert.Equal("url", elicitation.Mode);
Assert.Equal("elicitation-required-id", elicitation.ElicitationId);
Assert.Equal("https://auth.example.com/connect?elicitationId=elicitation-required-id", elicitation.Url);
Assert.Equal("Authorization is required to access Example Co.", elicitation.Message);
}
[Fact]
public async Task FormElicitation_Requires_RequestedSchema()
{
var elicitationHandlerCalled = false;
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new ClientCapabilities
{
Elicitation = new(),
},
Handlers = new McpClientHandlers()
{
ElicitationHandler = (request, cancellationToken) =>
{
elicitationHandlerCalled = true;
return new ValueTask<ElicitResult>(new ElicitResult());
},
}
});
var result = await client.CallToolAsync("TestFormElicitationMissingSchema", cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError);
var textContent = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("An error occurred invoking 'TestFormElicitationMissingSchema': Form mode elicitation requests require a requested schema.", textContent.Text);
Assert.False(elicitationHandlerCalled);
}
private ElicitationCapability AssertServerElicitationCapability()
{
var capabilities = Server.ClientCapabilities;
Assert.NotNull(capabilities);
Assert.NotNull(capabilities.Elicitation);
return capabilities.Elicitation;
}
private sealed class TestForm
{
public required string Value { get; set; }
}
}