How to Implement MCP Sampling in ASP.NET Core 10 Using C# – Server-Initiated LLM Requests, Human Approval and Security (2026)
How to Implement MCP Sampling in ASP.NET Core 10 Using C# – Server-Initiated LLM Requests, Human Approval and Security (2026)
A documentation tool sometimes needs a short summary before it can finish its work. In a legacy MCP sampling workflow, the tool asks the connected client to generate that summary. The client controls the model, the account paying for it, the input it sends and the response it shares.
What is MCP sampling? Sampling is a client capability that lets an MCP server ask the client for a model completion during an operation. Legacy servers use sampling/createMessage. With the July 2026 protocol revision, the standalone callback is gone from the modern wire flow. A server can request compatibility sampling through Multi Round-Trip Requests (MRTR) where both sides support it. Sampling itself is deprecated, so new integrations can give the host direct responsibility for generation.
This tutorial uses ASP.NET Core 10 and MCP C# SDK 2.3.1. It tests a legacy callback and the modern MRTR flow against one loopback server. The client asks for approval before it generates a deterministic fixture response and again before it releases the response. A separate adapter shows where an approved live model would fit.
How does MCP sampling work?
The client calls a server tool, such as summarize_legacy. While processing that call, the legacy server sends a sampling request to the client. The client validates the requested content, applies consent policy, selects an approved model, and returns an assistant response or declines. The server decides how to use the response inside its original operation.
| Interaction | Direction | Responsibility |
|---|---|---|
| MCP tool call | Client → server | The server executes the requested operation under its own authorization policy. |
| Legacy MCP sampling | Server → client during an associated operation | The client controls generation, approval and what gets returned. |
| MRTR | Server returns input requirements, client resubmits the operation | The server receives input on a new request. The client decides how to fulfill it. |
| Direct model API call | Application → configured model provider | The calling application owns the model credentials, budget and data policy. |
| Multi-server orchestration | Host → chosen MCP servers | The host owns routing and tool selection across independent connections. |
A normal tool call can finish without any LLM. A sampling callback can occur inside a tool call, but it does not transfer model credentials or permission to the server. See the legacy sampling specification and the current MCP specification.
Which protocol revision supports sampling?
| Protocol and transport | Sampling path |
|---|---|
2025-11-25 over a compatible stdio connection or stateful Streamable HTTP |
Legacy callback with sampling/createMessage when the client advertises sampling. |
2025-11-25 over stateless Streamable HTTP |
No session to carry the legacy callback. Do not call SampleAsync on a stateless server. |
2026-07-28 over modern Streamable HTTP |
Use an input-required result and MRTR continuation where supported. The compatibility sampling input remains deprecated. |
| New application without a need for compatibility sampling | Return authorized document data through a tool or resource. Let the host call its approved model directly. |
The SDK marks legacy sampling-related APIs with diagnostic MCP9005. This sample suppresses that warning around the compatibility implementation so it stays visible as a deliberate choice. The current deprecation policy makes the feature eligible for removal in a revision released on or after July 28, 2027. That is an eligibility date, and it does not name a guaranteed removal release. See SEP-2577 and the SDK v2 release explanation.
Does every MCP client support sampling? No. In the legacy flow, a client must advertise the capability during initialization and provide a handler that can decide whether to fulfill each request. The SDK advertises legacy sampling when the client registers SamplingHandler. In the modern flow, the sample checks IsMrtrSupported and the client still needs a handler to resolve the sampling input. Protocol compatibility and user approval are separate.
Legacy sampling must be associated with an originating client operation. The sample sends the callback while handling tools/call. Do not use the callback as an independent background generation channel. Modern MRTR responds to a call with an input requirement. The client handles it and retries with the associated response and opaque request state. This sample uses the SDK’s convenience overload, which resolves a compatible input round through registered handlers. See the MRTR specification, SDK sampling guidance, and the client API.
What can a sampling request contain?
The core request includes messages and maxTokens. The request can also express model preferences, system guidance, temperature and other supported fields. Client and provider behavior determine which hints are honored. Model preferences can express desired properties or suggest models. The client retains model selection and can decline the operation.
The legacy specification defines user and assistant message roles and several content formats, including text and other content types where supported. Tool-enabled sampling requires the corresponding capability and adds a separate execution surface. This example accepts one user-role text block with a known synthetic document, requests up to 80 output tokens and exposes no tools to the model. The client returns one assistant text block and the model identifier. See the request API and legacy sampling specification.
Build the ASP.NET Core server and .NET client
Install the .NET 10 SDK and create two sibling projects. No model account is needed for the fixture. Pin the MCP SDK versions shown here. The server package supplies HTTP hosting, and the client package supplies the protocol and client types.
See the server NuGet package, client NuGet package, and SDK release notes. If you need a server registration introduction first, see the ASP.NET PB C# MCP server tutorial.
Configure the endpoint and implement both tool paths
The endpoint uses StatefulForInitializeClients. A legacy client can use a stateful session, while a modern client uses the stateless request form. This is a compatibility configuration for the exercise. The lab rejects unexpected Host and Origin headers and checks a separate local bearer credential on requests. Bind it to loopback as shown.
Add SummaryTools.cs. The only accepted document ID is timeouts. The server sends fixed public fixture text, never a file path or caller-supplied prompt. A legacy operation checks the negotiated revision and client capability, admits at most two callbacks at once and uses a linked deadline. The MRTR tool emits a single input requirement, validates the continuation shape, and treats the returned text as untrusted data.
The MRTR marker in this lab correlates the one synthetic read-only interaction. It confers no authority and can be copied by a client. For sensitive operations, authenticate each retry and bind continuation state to the caller, operation, input and expiration. Recheck authorization before any action. Use an integrity-protected state value or server-side state, and make side effects safe to retry. A returned summary is still client-provided content.
Implement human approval in the MCP client
The legacy protocol recommends a human in the loop with the ability to deny sampling. The interaction design belongs to the client. For this console demo, the client checks the exact expected input before showing it to the user. It then asks whether to submit the prompt and separately asks whether to share the generated output.
Replace SamplingClient/Program.cs. This process has one sampling attempt and a deadline. The local fixture returns a deterministic sentence. It makes no provider API request and incurs no model charge. The client disables redirects and connects to the fixed loopback endpoint.
A cancellation deadline can stop waiting for console input in this single-run process. A pending terminal read may remain until the process exits. A long-running client should use a cancelable UI with explicit request correlation. A sampling refusal ends this call. The application should never start a hidden fallback model after a user declines.
Connect the approval path to an actual model
Use a model adapter only after the input approval branch. Construct the provider-specific IChatClient in the host with trusted configuration and pass it to GenerateAsync. In the client handler, replace the fixture generation with var output = await ModelAdapter.GenerateAsync(trustedClient, text.Text, deadline.Token); and keep the output review. Set the returned MCP model field to the actual configured model identifier. Map provider exceptions to a safe error and keep credentials in the host. This optional adapter compiles but was not called against a live provider.
Use the provider’s own token usage, rate limits and billing signals. The requested output cap does not cap input tokens or every provider’s accounting. Count or bound input independently, cap output, require an appropriate plan or quota and record aggregate usage without saving prompt content. See IChatClient and the ASP.NET PB OpenAI API integration guide.
Run the example and verify failure cases
Run the commands in two terminals from the parent directory. Generate a random development-only key and set the same value in the two process environments. In PowerShell, use $env:Sampling__LabKey with the generated value. Do not put the key in source control or paste a production credential.
Start the client with the same environment value. Select the legacy route by default or pass --modern for MRTR. Type yes at each review prompt. The normal tool request carries {"id":"timeouts"}. The sampling payload contains one user message beginning with “Summarize in one sentence” and a max token request of 80.
Both approved local runs returned the following tool text.
| Test | Expected behavior |
|---|---|
| Approve the input and output | The client returns the fixture response to the original tool workflow. |
| Decline the input | No generation runs and the tool reports an error. |
| Approve input, decline output | The client withholds the generated text. |
Legacy client with --unsupported |
The server rejects the operation before asking the client to sample. |
Client with --bad-id |
The server rejects the unknown document. |
Legacy client with --slow and input approval |
The simulated model delay exceeds the local deadline and returns an error. |
| Request without lab credential | The endpoint returns HTTP 401. |
For repeatable checks, stop the manually started server, build both Debug projects and save the following optional harness as check.py beside them. Run python3 check.py with dotnet on PATH. It uses standard-library subprocess and HTTP tools. The harness supplies approval responses only for isolated test cases.
Execution record. Both projects built on .NET SDK 10.0.100 with MCP SDK 2.3.1. Eight local checks passed, including the legacy callback, modern MRTR, input and output refusal, unsupported client, invalid document ID, simulated provider timeout and missing HTTP credential. The model result was a deterministic fixture. Live provider inference and deployed HTTPS or OAuth were outside the test run.
How do you secure a sampling request in production?
- Separate endpoint authentication from model consent. Use HTTPS and an appropriate MCP authorization flow for a remote server. A valid access token does not grant the upstream server permission to use a client’s model budget.
- Bind the request to an authorized user action. Track the originating operation and server identity. Validate the exact input, deny unrequested tools and avoid implicit context from other servers.
- Minimize data exposure. Review the text before sending it to a provider. Redact sensitive fields and consider data residency, retention and tenant policy. Treat both source documents and generated text as untrusted.
- Bound resource use. Enforce size, time, token and concurrency budgets. Limit the number of input rounds. Cancel on user refusal or timeout and avoid automatic retries that can incur duplicate charges.
- Log outcomes with correlation IDs. Record approved, declined, timed out or failed states, the trusted model ID and aggregate token usage. Keep prompts, outputs and credentials out of ordinary logs.
- Recheck authorization on continuation. An MRTR state token or model response must never substitute for authorization. A client can alter returned data. Enforce the policy again before acting on it.
Use direct host-controlled generation for new applications unless you have a compatibility reason to support sampling. See MCP authorization, Microsoft’s MCP sampling lesson and the ASP.NET PB JWT authentication guide.
Troubleshooting and frequently asked questions
| Symptom | What to inspect |
|---|---|
SampleAsync fails in stateless mode |
Verify the negotiated revision and server session mode. The modern route uses MRTR. |
| Client does not advertise sampling | Set a compatible handler for legacy operation or use a host-controlled generation workflow. |
| Prompt never reaches the review step | Check the lab credential, document ID, exact message policy and advertised capabilities. |
| MRTR continuation is rejected | Verify the supported revision, handler registration, response key and returned state. |
| A sampling request exceeds its deadline | Separate user review time, provider latency and transport time. Keep limits explicit and propagate cancellation. |
| The output is empty or wrong type | Check the provider adapter and validate role, content type and length before sharing it. |
Can the server directly select the client’s LLM?
The server can express preferences or request properties, and the client chooses a model under its own policy. If the server calls a model API directly with its own credentials, that is a separate integration.
Does MCP sampling require human approval?
The legacy specification recommends human review and the ability to deny sampling. The client chooses the approval interface. This lab requires explicit input and output approval and fails closed when either decision is absent.
What if the client cannot sample?
Return an actionable unsupported-capability error. A host can fetch authorized document data and generate a summary directly under its own model policy. Ask the user before changing the destination or scope of shared data.
Is MRTR a replacement for all sampling use cases?
MRTR is a general continuation mechanism. It can carry deprecated sampling input for compatibility. New designs can use ordinary tool or resource results and let the host manage model calls.
Conclusion and further reading
For a legacy integration, test that the client advertises sampling and that refusal blocks both generation and release. For modern HTTP, verify how your SDK handles input-required continuations and that the client can decline. A new documentation assistant can expose an authorized resource and let the host summarize it under its own policy.
Future topics include MRTR continuation state integrity, consent logging for model calls, and resource-based summarization with a direct IChatClient pipeline.
Comments
Post a Comment