|
| 1 | +using ModelContextProtocol; |
| 2 | +using ModelContextProtocol.Protocol; |
| 3 | +using ModelContextProtocol.Server; |
| 4 | +using System.ComponentModel; |
| 5 | + |
| 6 | +namespace AspNetCoreMcpServer.Tools; |
| 7 | + |
| 8 | +[McpServerToolType] |
| 9 | +public class UrlElicitationTool(ApiKeyStore apiKeyStore, IHttpContextAccessor httpContextAccessor, ILogger<UrlElicitationTool> logger) |
| 10 | +{ |
| 11 | + [McpServerTool, Description("Requests an API Key from the user via out-of-band elicitation.")] |
| 12 | + public async Task<string> NeedsApiKey(McpServer server, CancellationToken cancellationToken) |
| 13 | + { |
| 14 | + var httpContext = httpContextAccessor.HttpContext; |
| 15 | + if (httpContext == null) |
| 16 | + { |
| 17 | + throw new InvalidOperationException("No HttpContext available."); |
| 18 | + } |
| 19 | + |
| 20 | + var elicitationId = Guid.NewGuid().ToString(); |
| 21 | + var request = httpContext.Request; |
| 22 | + var baseUrl = $"{request.Scheme}://{request.Host}"; |
| 23 | + var url = $"{baseUrl}/apikey?id={elicitationId}"; |
| 24 | + |
| 25 | + if (server.ClientCapabilities?.Elicitation?.Url is null) |
| 26 | + { |
| 27 | + //throw new McpException("Client does not support URL elicitation."); |
| 28 | + } |
| 29 | + |
| 30 | + var result = await server.ElicitAsync(new ElicitRequestParams |
| 31 | + { |
| 32 | + Mode = "url", |
| 33 | + ElicitationId = elicitationId, |
| 34 | + Url = url, |
| 35 | + Message = "Please provide your API Key to continue." |
| 36 | + }, cancellationToken); |
| 37 | + |
| 38 | + if (!result.IsAccepted) |
| 39 | + { |
| 40 | + throw new McpException("User declined to provide API Key."); |
| 41 | + } |
| 42 | + |
| 43 | + var key = apiKeyStore.GetKey(elicitationId); |
| 44 | + if (key is null) |
| 45 | + { |
| 46 | + throw new McpException("User accepted but no key found."); |
| 47 | + } |
| 48 | + |
| 49 | + logger.LogInformation("Received API Key for session: {SessionId}", server.SessionId); |
| 50 | + return "API Key received and stored."; |
| 51 | + } |
| 52 | +} |
0 commit comments