Model Context Protocol
Model Context Protocol (MCP) standardizes how AI applications discover and invoke external tools, read contextual resources, and use reusable prompts. This guide connects the programming model to production decisions, failure modes, security, testing, performance, deployment, and operations.
Overview
The official C# SDK lets .NET applications act as MCP servers or clients. Servers publish capabilities such as tools, resources, and prompts over transports including standard input/output and HTTP, while clients negotiate capabilities and invoke them through a consistent protocol. MCP improves interoperability, but every exposed capability remains a security boundary that needs validation, authorization, consent, timeouts, and auditability. The central design goal is interoperable discovery and invocation of tools, resources, and prompts over a capability-negotiated JSON-RPC protocol. MCP describes how a host, client, and server exchange capabilities; the server remains responsible for identity, authorization, validation, rate limits, and safe tool semantics. Teams should begin with a concrete user outcome and quality-attribute scenario, choose the smallest architecture that satisfies it, and record the operational owner. An overpowered tool, confused-deputy flow, untrusted server, prompt injection, or unbounded result can turn useful model context into a security incident. A production design therefore needs explicit limits, identity, cancellation, telemetry, evaluation, recovery, and a safe change path. The dedicated sample keeps external infrastructure optional so readers can inspect the governing mechanics locally, then maps those mechanics to the hosted services and controls required in a real environment.
What you will learn
- Explain the purpose and boundaries of Model Context Protocol without confusing the tool with the whole architecture.
- Decide when Model Context Protocol is appropriate and when a simpler design is safer.
- Design the core contracts, ownership, data flow, and failure behavior for interoperable discovery and invocation of tools, resources, and prompts over a capability-negotiated JSON-RPC protocol.
- Apply authentication, authorization, validation, privacy, and least privilege at every trust boundary.
- Test normal behavior, negative paths, dependency failure, recovery, and operational signals.
- Deploy incrementally with observable acceptance criteria, rollback, and accountable ownership.
- Run and extend the dedicated MCP Inventory Tools sample.
Prerequisites
- .NET 10, C# async programming, dependency injection, configuration, and structured logging.
- The domain and platform fundamentals referenced by Model Context Protocol.
- Basic security, testing, observability, and continuous-delivery concepts.
- A .NET 10 SDK to run MCP Inventory Tools; no paid cloud account is required for its default path.
When to use Model Context Protocol
Good fit
- Use Model Context Protocol when interoperable discovery and invocation of tools, resources, and prompts over a capability-negotiated JSON-RPC protocol directly addresses a measured product or operational need.
- Use it when a named team can own the contracts, data, deployment, telemetry, cost, and incident response.
- Introduce it behind a narrow boundary and prove the riskiest assumption with a production-shaped experiment.
Choose another approach when
- Avoid Model Context Protocol when the same outcome is available through a smaller in-process or managed capability.
- Do not adopt it only for résumé value, diagram symmetry, or a vendor checklist.
- Do not proceed without a threat model, failure policy, observability, and an exit or rollback path.
Key concepts
An MCP server publishes capabilities; an MCP client connects, negotiates supported features, and makes those capabilities available to an AI host.
Model-invocable operations have typed inputs and outputs and can perform actions such as querying an order or creating a support ticket.
Resources expose contextual data through URIs, while prompts provide reusable, parameterized interaction templates.
Stdio suits local process integration, while HTTP supports remote services; initialization, capability negotiation, cancellation, and errors are protocol concerns.
Capability negotiation is a first-class design concern for interoperable discovery and invocation of tools, resources, and prompts over a capability-negotiated JSON-RPC protocol.
Tool safety boundaries is a first-class design concern for interoperable discovery and invocation of tools, resources, and prompts over a capability-negotiated JSON-RPC protocol.
Architecture
An AI host uses an MCP client to discover server capabilities, then invokes narrowly scoped tools or reads resources through a negotiated transport.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the critical path deliberately, then verify its observable behavior.
- 01
- 02
- 03
- 04
- 05
- 06
- 07
Code example
A small stdio server registers attributed tools from the assembly so compatible clients can discover and call the order-status capability.
using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;
var builder = Host.CreateApplicationBuilder(args);
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
[McpServerToolType]
public static class OrderTools
{
[McpServerTool, Description("Gets the current status of an order.")]
public static string GetOrderStatus(
[Description("The public order identifier.")] string orderId)
{
// Replace with an authorized application-service call.
return $"Order {orderId} is being prepared.";
}
}Testing strategy
Test Model Context Protocol as a behavior and operational boundary, not only as a library call.
- Unit-test deterministic policy, validation, mapping, and error classification.
- Use contract tests for provider, protocol, platform, and downstream boundaries.
- Run integration tests with realistic serialization, configuration, identity, cancellation, and dependency behavior.
- Exercise the primary failure: An overpowered tool, confused-deputy flow, untrusted server, prompt injection, or unbounded result can turn useful model context into a security incident.
- Load-test representative and adversarial inputs while observing latency, errors, saturation, and cost.
- Keep a versioned acceptance suite that protects behavior during dependency and configuration changes.
Security considerations
Treat Model Context Protocol input, dependencies, credentials, output, and administrative controls as separate trust boundaries.
- Authenticate the caller and workload; authorize the operation and resource at the system that performs it.
- Validate type, size, count, format, tenant, and allowed values before expensive or consequential work.
- Use short-lived identity and least privilege; keep secrets out of source, logs, prompts, packages, and client storage.
- Classify data, minimize collection and retention, redact telemetry, encrypt in transit and at rest, and support deletion policy.
- Require explicit approval and idempotency for external side effects; audit actor, intent, policy decision, and outcome.
- Patch and inventory dependencies, pin trusted sources, scan artifacts, and restrict outbound destinations.
Performance and scalability
Optimize the end-to-end user outcome within downstream capacity and cost limits.
- Measure p50, p95, p99, throughput, failures, saturation, queue time, payload size, and cost together.
- Set end-to-end deadlines and propagate cancellation instead of stacking independent timeouts.
- Bound concurrency, queues, retries, payloads, fan-out, and caches so overload cannot grow without limit.
- Cache only when identity, freshness, privacy, invalidation, and failure semantics are explicit.
- Batch or stream only when the workload and user latency target justify the complexity.
- Capacity-test dependency degradation and recovery because retry and replay traffic often dominate peak load.
Deployment and operations
Promote an immutable, observable change through environments with compatibility and rollback evidence.
- Keep environment configuration external, validated at startup, and free of long-lived credentials.
- Provision dependencies, identity, network policy, dashboards, alerts, and budgets through reviewed automation.
- Use additive contracts and mixed-version compatibility before removing old behavior.
- Deploy with canary or staged exposure, health gates, graceful shutdown, and automated rollback signals.
- Record version and configuration in telemetry; retain runbooks, ownership, recovery targets, and escalation paths.
- Rehearse dependency loss, restore, credential rotation, region or device failure, and data recovery where applicable.
Common problems and fixes
The local sample works but production behavior differs
Likely cause: Provider, identity, network, limits, data, or configuration assumptions were hidden.
Fix: Compare effective configuration and correlated dependency telemetry, then reproduce the smallest differing boundary.
Latency rises sharply under load
Likely cause: Concurrency, fan-out, retries, queues, or a downstream quota is unbounded.
Fix: Inspect saturation and queue time, stop retry amplification, apply backpressure, and reduce work per request.
A request succeeds twice or creates duplicate effects
Likely cause: The caller retried after an ambiguous result and the operation was not idempotent.
Fix: Use a stable operation ID, persist the outcome with the effect, and return the recorded result on replay.
Sensitive information appears in telemetry
Likely cause: Raw inputs, outputs, headers, or exceptions were logged without classification and redaction.
Fix: Stop the leak, restrict and rotate access as needed, redact by default, and test the telemetry schema.
A dependency upgrade changes behavior
Likely cause: Application semantics depended on provider-specific defaults or an untested protocol detail.
Fix: Pin or roll back, compare release notes and contract traces, then update the acceptance suite before retrying.
Operators cannot explain a failed user outcome
Likely cause: Logs, metrics, traces, version, and business identifiers are not correlated.
Fix: Add end-to-end correlation and a dashboard that links the user journey to dependency and deployment signals.
Best practices
- Expose small, intention-revealing tools with strict schemas instead of giving a model generic database, shell, or network access.
- Authenticate clients, authorize every capability and target resource, and require confirmation for destructive or financially meaningful actions.
- Validate inputs and outputs, apply cancellation and timeouts, and return structured errors that do not reveal secrets or internal topology.
- Log capability identity, caller, result, latency, and correlation data while redacting prompts, credentials, and sensitive payloads.
- Expose narrowly scoped tools with explicit JSON schemas, bounded output, read-only defaults, and clear side-effect descriptions.
- Treat every MCP server and returned content as untrusted; apply user consent, allowlists, authorization, and audit at the host and server.
Production checklist
- The need for Model Context Protocol, alternatives, owner, constraints, and exit criteria are recorded.
- Contracts, data ownership, trust boundaries, limits, and compatibility policy are explicit.
- Identity, least privilege, validation, privacy, redaction, audit, and side-effect approval are enforced.
- Timeout, cancellation, retry, backpressure, idempotency, fallback, and recovery behavior are tested.
- Logs, metrics, traces, cost, quality, business outcomes, dashboards, alerts, and runbooks identify version and owner.
- Capacity, dependency failure, restore, rollback, credential rotation, and incident response are rehearsed.
- Lifecycle, deprecation, data retention, dependency patching, and operational cost have named owners.
Common interview questions
How is MCP different from function calling?
Function calling is usually a model-provider feature for requesting a named function. MCP standardizes discovery, schemas, invocation, resources, prompts, transports, and lifecycle between AI hosts and external capability servers.
When should an MCP server use stdio instead of HTTP?
Stdio is a good fit when the host starts and owns a local child process. HTTP is appropriate for independently deployed or remotely shared servers that need network authentication, scaling, and operations.
What is the main security risk of MCP tools?
A model can turn untrusted instructions into real side effects. Tools must enforce the same authentication, authorization, validation, least privilege, and confirmation rules as any other application endpoint.
What roles participate in MCP?
A host owns the user experience and policy, a client maintains a connection, and a server exposes negotiated tools, resources, or prompts.
Why is tool discovery not authorization?
A listed tool only describes availability and schema. Each invocation still needs authenticated identity, policy checks, validation, and safe execution.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
MCP Inventory Tools
A .NET 10 line-oriented JSON-RPC MCP teaching server that implements initialize, tools/list, and a schema-validated inventory tool without external services.
- Run
dotnet run --project src/McpInventoryTools- Test
dotnet run --project src/McpInventoryTools -- --self-test