How to Implement MCP Elicitation in ASP.NET Core 10 Using C# – Interactive User Input, Form Validation and Secure Approval Workflows (2026)

How to Implement MCP Elicitation in ASP.NET Core 10 Using C# – Interactive User Input, Form Validation and Secure Approval Workflows (2026)

An IT support assistant receives “Office Wi-Fi disconnects.” It knows the issue title, but it still needs a category and priority. With MCP elicitation in C#, the ASP.NET Core server can ask the MCP client to collect those fields, let the user review them, and continue only after the user responds. This tutorial builds both sides of that exchange with .NET 10 and the official MCP C# SDK 2.3.1.

The example uses the 2026-07-28 protocol and Multi Round-Trip Requests (MRTR). It produces a support-ticket preview and has no database write, external help-desk integration, or model dependency. You can test accept, decline, cancel, and invalid input from a terminal before introducing a real host UI or an approval process.

What is MCP elicitation?

MCP elicitation is a server request for additional user input, presented and mediated by the MCP client during an existing operation. The server explains what it needs, the client shows who is asking and lets the user decide, and the server interprets and validates the returned response. A client can render the same request in a terminal, a chat application, or a graphical form.

The operator reviews the form in the client. The authenticated MCP server validates it and returns a read-only ticket preview.
The operator reviews the form in the client. The authenticated MCP server validates it and returns a read-only ticket preview.
Mechanism Who provides the input? What is it for?
Tool call A client or its agent provides arguments Start an operation such as preparing a support ticket
Form elicitation A user reviews and supplies structured values Fill in missing ticket category and priority
URL elicitation A user interacts with a consented browser destination Complete a sensitive or out-of-band step
Sampling A client obtains model-generated content Request model output in compatible legacy integrations
Ordinary web form A user submits directly to the web application Run a browser-owned flow outside the MCP tool contract
Elicitation collects a human response through the client. Legacy sampling asks the client to obtain model-generated content.
Elicitation collects a human response through the client. Legacy sampling asks the client to obtain model-generated content.

The MCP tool and the prompt solve different problems. The tool advertises an operation and accepts a title. The elicitation form supplies information that depends on the user’s judgment. Model output cannot substitute for a user’s review or authorization. Sampling is deprecated in the current protocol, so treat older sampling examples as compatibility material. See the official C# SDK v2 announcement and the MCP elicitation specification.

How do modern MCP round trips work?

  1. The client calls preview_ticket with a title and advertises form support. On the July 2026 protocol, capability metadata lives in _meta.io.modelcontextprotocol/clientCapabilities on each request.
  2. The server returns an InputRequiredResult. The C# tool expresses this by throwing InputRequiredException with an InputRequest.ForElicitation(...) entry named ticket-form and an opaque requestState.
  3. The client calls its elicitation handler. The operator reviews the fields and chooses accept, decline, or cancel.
  4. The SDK sends a new call with the original operation, requestState, and inputResponses. The server verifies the state and checks the matching answer.
The first HTTP response carries a form request and protected state. The next request carries that state and the user response.
The first HTTP response carries a form request and protected state. The next request carries that state and the user response.

The server can release the first HTTP request while the user is thinking. Any server instance that can verify the state can process the next request. A timeout on the client and an expiry on server state address two different failure modes. The first bounds how long the UI waits. The second bounds how long a continuation is usable. See Multi Round-Trip Requests.

Older examples use ElicitAsync as a server-to-client request on a stateful connection. The 2025-11-25 version has separate rules for initialization and callbacks. The C# SDK continues to support that API on compatible stateful sessions, such as stdio or appropriately configured stateful HTTP. Calling it on a stateless server fails. This tutorial pins the modern version so a legacy negotiation cannot quietly change the example. Compare the November 2025 spec with the current SDK elicitation guide.

What if the client does not support elicitation?

Check both protocol behavior and mode support. A missing elicitation capability means the client cannot receive the form. A URL-only capability does not imply form support. The current spec treats an explicitly empty elicitation object as form-only for backward compatibility. This tool returns a clear error for unsupported clients. Another design could offer a separate tool with explicit required arguments for noninteractive callers.

The tool requests form input only if the client supports both the round-trip protocol and form mode.
The tool requests form input only if the client supports both the round-trip protocol and form mode.

Capability checks tell you which interaction a client can render. They do not authenticate the user, authorize a write, or prove that the user has already agreed to share data.

Form mode, URL mode, and consent

Form values pass through the client. URL mode opens a consented browser destination and the server independently verifies completion.
Form values pass through the client. URL mode opens a consented browser destination and the server independently verifies completion.

Use form mode for structured, non-secret fields

Form mode uses a restricted JSON Schema subset. Use a flat object with string, number or integer, boolean, and enum fields. The protocol defines single- and multi-select enum forms and recognizes string formats such as email, uri, date, and date-time. Avoid nested objects and arbitrary arrays. The required list identifies fields needed on acceptance. Client-side validation is useful feedback. Server-side validation decides whether the values can be used. Review the exact schema rules in the requested schema section.

The sample form asks for these three values.

Field Required Server rule
category Yes Exact member of network, hardware, software
priority Yes JSON integer, 1 through 3
note No If present, text up to 120 UTF-16 code units and no control characters

Treat the note as untrusted text. The UI should render it as text and should never interpret it as HTML, a shell command, or a new instruction to an AI system. Do not request passwords, API keys, access tokens, or payment credentials in a form. The ticket preview does not need contact details, so it asks for none.

Use URL mode for sensitive out-of-band interaction

URL mode sends a message and a URL for the client to present to the user. The client shows the requesting server and destination host, asks before navigation, and avoids prefetching or inspecting the sensitive browser interaction. Use a verified HTTPS destination. Keep credentials, personal data, and preauthenticated links out of the URL. If an external account is involved, bind the pending interaction to the authenticated user and client, verify completion independently, and reject expired or mismatched state.

Accepting a URL prompt gives the client permission to navigate. The server still needs proof that the interaction completed, such as a verified callback that consumes a short-lived nonce. A consent response alone should never commit a payment or connect an account. SDK v2 documents UrlElicitationRequiredException for URL-required interactions. Older examples use an elicitationId for their stateful protocol flow. For this version, use the current URL-mode flow and the appropriate continuation/error path. MCP OAuth protects access to the MCP server itself, while URL elicitation can guide an already connected user through a separate downstream authorization step. See URL mode security and MCP authorization.

Navigation consent precedes the browser interaction. The MCP server verifies proof of completion and rechecks authorization before a separate write.
Navigation consent precedes the browser interaction. The MCP server verifies proof of completion and rechecks authorization before a separate write.

The runnable sample implements form mode. The URL-mode diagram is a design guide. An implementation needs a real HTTPS endpoint, an authenticated browser interaction, server-side proof of completion, and tests for each failure branch.

Set up the ASP.NET Core 10 solution

Install the .NET 10 SDK and an editor. The commands use a POSIX shell with OpenSSL for generating the local lab key. NuGet access is required during restore. Start in an empty folder, then create the web project, client, and check runner.

Create the three projects
dotnet --version
dotnet new web -n TicketServer --framework net10.0
dotnet new console -n TicketClient --framework net10.0
dotnet new console -n TicketChecks --framework net10.0
dotnet add TicketServer package ModelContextProtocol.AspNetCore --version 2.3.1
dotnet add TicketClient package ModelContextProtocol.Core --version 2.3.1
dotnet add TicketChecks reference TicketServer/TicketServer.csproj

The server uses the ASP.NET Core transport package. The console client uses Core directly. ASP.NET Core Data Protection comes from the shared ASP.NET Core framework. The sample versions are pinned so restoring the same source is reproducible. See the official SDK 2.3.1 release and Core package metadata.

TicketServer hosts MCP, TicketClient supplies the review UI, and TicketChecks exercises form validation and state protection.
TicketServer hosts MCP, TicketClient supplies the review UI, and TicketChecks exercises form validation and state protection.
Project layout
TicketServer/
  Program.cs
  TicketPolicy.cs
  TicketContinuation.cs
  TicketTools.cs
TicketClient/
  Program.cs
TicketChecks/
  Program.cs

Build the server, schema, and validation

Configure the HTTP endpoint and dependency injection

Replace TicketServer/Program.cs. This is a loopback-only development lab. Both processes receive a random shared key through Tickets__LabKey. The server caps request size, checks the host, rejects requests with an Origin header in this terminal-only setup, and checks the key before invoking MCP. Every accepted request uses the same lab identity. Use standard authentication and per-user authorization for remote deployment.

TicketServer/Program.cs
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

var builder = WebApplication.CreateBuilder(args);
var secret = builder.Configuration["Tickets:LabKey"];
if (string.IsNullOrWhiteSpace(secret) || secret.Length is < 32 or > 128)
    throw new InvalidOperationException("Set Tickets__LabKey to a random 32–128 character value.");

var expected = SHA256.HashData(Encoding.UTF8.GetBytes("Bearer " + secret));
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 16 * 1024);
builder.Services.AddDataProtection();
builder.Services.AddSingleton<TicketContinuation>();
builder.Services.AddMcpServer().WithHttpTransport().WithTools<TicketTools>();

var app = builder.Build();
app.Use(async (context, next) =>
{
    if (context.Request.Host.Host is not ("127.0.0.1" or "localhost") ||
        context.Request.Headers.ContainsKey("Origin"))
    {
        context.Response.StatusCode = 403;
        return;
    }

    var token = context.Request.Headers.Authorization;
    if (token.Count != 1 || token.ToString().Length > 140 ||
        !CryptographicOperations.FixedTimeEquals(expected,
            SHA256.HashData(Encoding.UTF8.GetBytes(token.ToString()))))
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.WWWAuthenticate = "Bearer";
        return;
    }

    context.User = new ClaimsPrincipal(new ClaimsIdentity(
        [new Claim(ClaimTypes.NameIdentifier, "local-ticket-operator")], "LabKey"));
    await next(context);
});
app.MapMcp("/mcp");
await app.RunAsync();

Validate the title and form payload

Create TicketPolicy.cs. The title is bounded and checked before prompting. After acceptance, the server validates exact names, JSON types, range, and string length. A submitted string "2" does not satisfy the integer rule. Empty optional notes can simply be omitted. Rejecting unexpected fields also prevents accidentally retaining extra data.

The schema guides the client. The server independently checks the permitted fields, category, integer range and note length.
The schema guides the client. The server independently checks the permitted fields, category, integer range and note length.
TicketServer/TicketPolicy.cs
using System.Text.Json;

public sealed record TicketDetails(string Category, int Priority, string? Note);

public static class TicketPolicy
{
    public static bool ValidTitle(string? title) =>
        title is { Length: >= 4 and <= 100 } && !string.IsNullOrWhiteSpace(title) &&
        !title.Any(char.IsControl);

    public static TicketDetails? Parse(IDictionary<string, JsonElement>? content)
    {
        if (content is null ||
            content.Keys.Any(key => key is not ("category" or "priority" or "note")) ||
            !content.TryGetValue("category", out var category) ||
            category.ValueKind != JsonValueKind.String ||
            category.GetString() is not ("network" or "hardware" or "software") ||
            !content.TryGetValue("priority", out var priority) ||
            priority.ValueKind != JsonValueKind.Number ||
            !priority.TryGetInt32(out var level) || level is < 1 or > 3)
            return null;

        string? note = null;
        if (content.TryGetValue("note", out var supplied))
        {
            if (supplied.ValueKind != JsonValueKind.String)
                return null;

            note = supplied.GetString();
            if (note is null || note.Length > 120 || note.Any(char.IsControl))
                return null;
        }

        return new(category.GetString()!, level, note);
    }
}

Bind the continuation to the caller and request

Create TicketContinuation.cs. The time-limited protector encrypts and authenticates the caller and title with a dedicated purpose. The state becomes invalid after two minutes, under the wrong identity, with an altered title, or after tampering. It can be reused within that window because the tool only produces a preview. A write would need a durable, one-time approval record, shared idempotency state, and an atomic consume-and-commit operation. If several servers handle the modern flow, configure their key rings and application isolation deliberately. See ASP.NET Core Data Protection.

TicketServer/TicketContinuation.cs
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;

public sealed class TicketContinuation(IDataProtectionProvider provider)
{
    private readonly ITimeLimitedDataProtector protector =
        provider.CreateProtector("TicketPreview.Form.v1").ToTimeLimitedDataProtector();

    public string Issue(string caller, string title) =>
        protector.Protect(Serialize(caller, title), TimeSpan.FromMinutes(2));

    public bool Matches(string? state, string caller, string title)
    {
        if (state is null || state.Length > 2048)
            return false;

        try
        {
            return string.Equals(protector.Unprotect(state),
                Serialize(caller, title), StringComparison.Ordinal);
        }
        catch (CryptographicException)
        {
            return false;
        }
    }

    private static string Serialize(string caller, string title) =>
        JsonSerializer.Serialize(new[] { caller, title });
}

Implement the support-ticket tool

Create TicketTools.cs. A call without state requests input. A call carrying continuation data must match the original title and caller, and supply exactly the ticket-form response. Accept creates the preview only after validation. Decline and cancel return distinct statuses without details. The application’s success log stores only the outcome, and tool errors use fixed messages. Configure SDK and transport logging separately and avoid collecting request bodies and authorization headers.

Accept leads to input validation. Decline and cancel are separate outcomes and neither produces a preview.
Accept leads to input validation. Decline and cancel are separate outcomes and neither produces a preview.
TicketServer/TicketTools.cs
using System.ComponentModel;
using System.Security.Claims;
using ModelContextProtocol;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;

[McpServerToolType]
public sealed class TicketTools
{
    [McpServerTool(Name = "preview_ticket", ReadOnly = true, UseStructuredContent = true)]
    [Description("Collect non-secret support details and return a ticket preview.")]
    public static TicketOutcome Preview(
        RequestContext<CallToolRequestParams> context, ClaimsPrincipal principal,
        TicketContinuation continuation, ILogger<TicketTools> log,
        string title, CancellationToken ct)
    {
        ct.ThrowIfCancellationRequested();
        var caller = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value
            ?? throw new McpException("Authentication required.");
        if (!TicketPolicy.ValidTitle(title))
            throw new McpException("Use a title of 4–100 characters without control characters.");

        var capability = context.Server.ClientCapabilities?.Elicitation;
        if (!context.Server.IsMrtrSupported || capability is null ||
            (capability.Form is null && capability.Url is not null))
            throw new McpException("This tool requires an MRTR client with form elicitation.");

        var call = context.Params!;
        if (call.RequestState is not null || call.InputResponses is { Count: > 0 })
        {
            if (!continuation.Matches(call.RequestState, caller, title) ||
                call.InputResponses is not { Count: 1 } answers ||
                !answers.TryGetValue("ticket-form", out var response))
                throw new McpException("Invalid or expired ticket continuation.");

            ElicitResult? reply;
            try
            {
                reply = response.Deserialize(InputResponse.ElicitResultJsonTypeInfo);
            }
            catch (System.Text.Json.JsonException)
            {
                throw new McpException("Malformed form response.");
            }

            var outcome = reply?.Action switch
            {
                "accept" => new TicketOutcome("preview", title,
                    TicketPolicy.Parse(reply.Content)
                    ?? throw new McpException("Invalid ticket form fields.")),
                "decline" => new TicketOutcome("declined", title, null),
                "cancel" => new TicketOutcome("canceled", title, null),
                _ => throw new McpException("Unknown elicitation action.")
            };
            log.LogInformation("Ticket form finished: {Outcome}", outcome.Status);
            return outcome;
        }

        throw new InputRequiredException(new Dictionary<string, InputRequest>
        {
            ["ticket-form"] = InputRequest.ForElicitation(new ElicitRequestParams
            {
                Mode = "form",
                Message = "Choose a category and priority to prepare a support-ticket preview.",
                RequestedSchema = new()
                {
                    Required = ["category", "priority"],
                    Properties = new Dictionary<string, ElicitRequestParams.PrimitiveSchemaDefinition>
                    {
                        ["category"] = new ElicitRequestParams.UntitledSingleSelectEnumSchema
                        {
                            Enum = ["network", "hardware", "software"]
                        },
                        ["priority"] = new ElicitRequestParams.NumberSchema
                        {
                            Type = "integer", Minimum = 1, Maximum = 3,
                            Description = "1 low, 2 normal, 3 urgent"
                        },
                        ["note"] = new ElicitRequestParams.StringSchema
                        {
                            MaxLength = 120, Description = "Optional. Do not include secrets."
                        }
                    }
                }
            })
        }, requestState: continuation.Issue(caller, title));
    }
}

public sealed record TicketOutcome(string Status, string Title, TicketDetails? Details);

Build the C# client and review UI

Replace TicketClient/Program.cs. The client pins the modern protocol, advertises form support, and uses a single elicitation handler. It limits the interaction to one expected form, shows the server identity, lets the user edit the response, and requires explicit acceptance. The form UI times out after 45 seconds. The entire operation has a 60-second budget, and Ctrl+C cancels it. The caller passes cancellation through the SDK. The terminal example uses an asynchronous wait around blocking console input, so the OS read itself can persist until input arrives or the short-lived process exits.

For a full graphical client, validate the rendered schema, enforce field types and limits before submission, and present accessible review controls. This lab deliberately allows entering an invalid priority so you can see the server reject it.

TicketClient/Program.cs
using System.Text.Json;
using ModelContextProtocol;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;

var key = Environment.GetEnvironmentVariable("Tickets__LabKey");
if (string.IsNullOrWhiteSpace(key))
    throw new InvalidOperationException("Set Tickets__LabKey.");

const string serverName = "local TicketServer (127.0.0.1:5080)";
bool unsupported = args.Contains("--unsupported");
int forms = 0;

async Task<string?> AskAsync(string prompt, CancellationToken ct)
{
    Console.Error.WriteLine(prompt);
    return await Task.Run(Console.ReadLine).WaitAsync(ct);
}

async ValueTask<ElicitResult> FormAsync(ElicitRequestParams? request, CancellationToken ct)
{
    if (Interlocked.Increment(ref forms) != 1 ||
        request is null || request.Mode is not (null or "form") ||
        request.RequestedSchema?.Properties is not { Count: 3 } fields ||
        !fields.ContainsKey("category") || !fields.ContainsKey("priority") ||
        !fields.ContainsKey("note"))
        throw new McpException("Unexpected form or unsupported mode.");

    using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
    budget.CancelAfter(TimeSpan.FromSeconds(45));
    try
    {
        var choice = await AskAsync(
            $"Form requested by {serverName}. Prepare preview? Enter edit, decline, or cancel.",
            budget.Token);
        if (choice != "edit")
            return new() { Action = choice == "decline" ? "decline" : "cancel" };

        while (true)
        {
            var category = await AskAsync("Category (network, hardware, software):", budget.Token);
            var priority = await AskAsync("Priority (1 low, 2 normal, 3 urgent):", budget.Token);
            var note = await AskAsync("Optional note (no secrets, 120 characters max):", budget.Token);
            if (category is null || priority is null || note is null)
                return new() { Action = "cancel" };

            var review = await AskAsync(
                $"Share with {serverName}? Category={category}; priority={priority}; note={note}\n"
                + "Enter accept, edit, decline, or cancel.", budget.Token);
            if (review == "edit")
                continue;
            if (review != "accept")
                return new() { Action = review == "decline" ? "decline" : "cancel" };

            var content = new Dictionary<string, JsonElement>
            {
                ["category"] = JsonSerializer.SerializeToElement(category)
            };
            if (int.TryParse(priority, out var level))
                content["priority"] = JsonSerializer.SerializeToElement(level);
            else
                content["priority"] = JsonSerializer.SerializeToElement(priority);
            if (note.Length > 0)
                content["note"] = JsonSerializer.SerializeToElement(note);

            return new() { Action = "accept", Content = content };
        }
    }
    catch (OperationCanceledException) when (!ct.IsCancellationRequested)
    {
        return new() { Action = "cancel" };
    }
}

using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(60));
Console.CancelKeyPress += (_, e) => { e.Cancel = true; deadline.Cancel(); };
using var http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var transport = new HttpClientTransport(new HttpClientTransportOptions
{
    Endpoint = new Uri("http://127.0.0.1:5080/mcp"),
    TransportMode = HttpTransportMode.StreamableHttp,
    AdditionalHeaders = new Dictionary<string, string> { ["Authorization"] = "Bearer " + key }
}, http);
var options = new McpClientOptions
{
    ProtocolVersion = "2026-07-28",
    Capabilities = new ClientCapabilities
    {
        Elicitation = unsupported ? null : new ElicitationCapability { Form = new() }
    },
    Handlers = new McpClientHandlers { ElicitationHandler = unsupported ? null : FormAsync }
};

try
{
    await using var client = await McpClient.CreateAsync(transport, options,
        cancellationToken: deadline.Token);
    var result = await client.CallToolAsync("preview_ticket",
        new Dictionary<string, object?> { ["title"] = "Office Wi-Fi disconnects" },
        cancellationToken: deadline.Token);
    if (result.IsError == true)
    {
        foreach (var block in result.Content.OfType<TextContentBlock>())
            Console.Error.WriteLine(block.Text);
        Environment.ExitCode = 2;
    }
    else
        Console.WriteLine(result.StructuredContent?.ToString());
}
catch (McpException)
{
    Console.Error.WriteLine("The MCP request failed or could not be completed.");
    Environment.ExitCode = 2;
}
catch (OperationCanceledException)
{
    Console.Error.WriteLine("Client canceled or exceeded its deadline.");
    Environment.ExitCode = 3;
}

Run the workflow and verify the results

Run both terminals in the project root. Export the same randomly generated key in both sessions. Keep it out of source, logs, and screenshots. Leave the server bound to loopback.

Start the local server
export Tickets__LabKey="$(openssl rand -hex 32)"
dotnet run --project TicketServer --no-launch-profile -- --urls http://127.0.0.1:5080
Start the client in a shell with the same lab key
dotnet run --project TicketClient

The arguments for the initial tools/call are shown below without the JSON-RPC envelope and capability metadata. The SDK assembles those pieces.

Initial tool parameters
{
  "name": "preview_ticket",
  "arguments": { "title": "Office Wi-Fi disconnects" }
}

Choose edit, enter network, 2, and VPN drops, then type accept after review. The accepted form content carries the category, numeric priority, and optional note. The resulting structured content observed locally was:

Observed successful ticket preview
{
  "status": "preview",
  "title": "Office Wi-Fi disconnects",
  "details": {
    "category": "network",
    "priority": 2,
    "note": "VPN drops"
  }
}
Test Reproduce it Outcome
Accept Enter the values above and accept JSON preview with validated fields
Decline Enter decline at the first prompt status: declined and no preview details
Cancel Enter cancel at the first prompt status: canceled and no preview details
Invalid priority Enter 4 and accept Tool error and client exit code 2
Unsupported Run dotnet run --project TicketClient -- --unsupported Tool error before the form is shown
Missing authentication Run curl -i http://127.0.0.1:5080/mcp without a key HTTP 401

A tool error can arrive within HTTP 200. Inspect the tool result and the client exit status. The transport and application operate at different layers. Use a fresh call after a validation failure. A retry is appropriate only after the invalid fields are corrected.

Run isolated policy and continuation checks

Put this code in TicketChecks/Program.cs, then run dotnet run --project TicketChecks. These checks run without the MCP transport. The scenarios above separately exercise the full loopback workflow with both SDK components.

TicketChecks/Program.cs
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;

static TicketDetails? Read(string json) =>
    TicketPolicy.Parse(JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json));

static void Check(bool passed, string scenario)
{
    if (!passed) throw new Exception($"Failed: {scenario}");
    Console.WriteLine($"PASS {scenario}");
}

Check(TicketPolicy.ValidTitle("VPN drops"), "title");
Check(!TicketPolicy.ValidTitle("a\nb\nc"), "control character");
Check(Read("""{"category":"network","priority":2}""") is { Note: null }, "optional note");
Check(Read("""{"category":"hardware","priority":1,"note":"Lab"}""") is { Note: "Lab" }, "note");
Check(Read("""{"category":"network"}""") is null, "missing priority");
Check(Read("""{"category":"network","priority":"2"}""") is null, "string priority");
Check(Read("""{"category":"network","priority":4}""") is null, "out of range");
Check(Read("""{"category":"hardware","priority":1,"token":"x"}""") is null, "unknown field");

var continuation = new TicketContinuation(new EphemeralDataProtectionProvider());
var state = continuation.Issue("alice", "VPN drops");
Check(continuation.Matches(state, "alice", "VPN drops"), "valid continuation");
Check(!continuation.Matches(state, "bob", "VPN drops"), "other caller");
Check(!continuation.Matches(state, "alice", "Other title"), "other title");
Check(!continuation.Matches(state[1..], "alice", "VPN drops"), "tampered state");

The local build and run used .NET SDK 10.0.100 with the pinned packages. The loopback checks covered the six outcomes in the table. Browser URL completion, production OAuth, distributed key rings, and the 45-second wait were outside the executed scenarios.

Design a separate approval workflow for writes

Authenticate the caller, verify protected state and validate form values independently. A read-only preview cannot authorize ticket creation.
Authenticate the caller, verify protected state and validate form values independently. A read-only preview cannot authorize ticket creation.

If the next step is to create a real ticket, split preview from commitment. Start with a stable, server-generated operation ID and a preview of the exact target and payload. Require the user to review that specific action. Bind approval to the user, tenant, client, target, and operation payload. On commit, authenticate again, check the current permission and target, verify the approval has not expired, and consume it atomically with the write. Handle duplicate submissions using an idempotency key and return the existing result when appropriate.

For production, enforce HTTPS and validate token issuer, audience, expiry, and scopes. The lab key cannot distinguish two people, and the lab’s HTTP binding is suitable only for the local reproduction. Restrict where clients can navigate. Never turn a model-generated URL into an automatic browser action. Use per-user quotas and request limits, keep form contents out of logs, and document retention of approval records. If an existing web app uses JWT, the ASP.NET PB JWT authentication guide explains application authentication. Use the MCP authorization specification to design the MCP boundary.

Troubleshooting MCP elicitation

Symptom Check Fix
Tool refuses to show a form MRTR support and form capability Pin the protocol for this lab and configure the elicitation handler
ElicitAsync throws on HTTP Transport is stateless Use MRTR with the current protocol
HTTP 401 or 403 Lab key, host, or Origin header Use matching keys and the fixed loopback terminal client
Continuation invalid State expired, changed, or failed identity/title binding Start a new operation and review the fresh prompt
Integer looks valid but fails Payload sent a JSON string or out-of-range number Send a whole numeric value from 1 to 3
Browser tab opened but approval is pending URL navigation was accepted, completion is unverified Verify the browser callback and pending operation before retrying
Dev shell seems to hang Console is waiting for entry Cancel with Ctrl+C and check the deadline and process logs

Frequently asked questions

Can I use elicitation with a tool hosted in ASP.NET Core?

Yes. Host the MCP endpoint using the C# SDK ASP.NET Core transport package. In the modern protocol, use InputRequiredException from the tool and configure the MCP client’s handler to process the form.

Does MCP elicitation work without an LLM?

Yes. The console client calls the MCP tool directly. It collects the response from the user and the server applies deterministic validation. An LLM can help decide when to call a tool, but user consent should still come through an explicit review.

What’s the difference between decline and cancel?

Decline means the user chose not to provide the requested input. Cancel means they dismissed or aborted the interaction. Both prevent a preview in this sample. The server records different outcomes so a host can show the right status.

Can I ask for an API key in a form?

No. Use a secure out-of-band flow for credentials. The server should request only the data needed for the current task, and the client should clearly identify the server and let the user decline.

Do I need a database for MRTR?

The protocol permits an opaque state value or a reference to server state. This read-only preview uses protected state. A durable approval workflow often needs a database to support audit, one-time consumption, expiry, and idempotency across instances.

Conclusion and further reading

A good elicitation flow keeps the user in control of missing information. This sample uses a short-lived continuation, checks capability before prompting, validates the response on the server, and stops at a read-only preview. Those boundaries give you a concrete starting point for adding an accessible UI or a separately authorized write.

Related follow-up tutorials could cover building an accessible schema-driven form renderer, verifying OAuth callback completion for URL elicitation, or consuming a single-use approval atomically with a help-desk write.

Comments