Building a Secure Enterprise MCP Server with .NET
articleNovember 5, 2026By Ali Haghighi
In MCP vs REST API: When Do You Actually Need MCP?, I argued that an MCP server needs to earn its place. Wrapping an existing endpoint just to call it a tool is not an architectural improvement.
But sometimes the requirement is real. Several AI applications need a consistent way to discover and invoke capabilities owned by different teams. The existing REST APIs already hold the business logic, and we want to make a carefully selected subset available without giving an AI model arbitrary API access.
I explored that problem with a small .NET 10 proof of concept: an MCP server in front of three fictional enterprise services, with .NET, JavaScript, and Java consumers. The goal was not to build another agent framework. It was to test the integration boundary and the security decisions around it.
This is a local demonstration, not a production-ready identity or security implementation. That distinction is important throughout the design.
The problem: three APIs, one useful business capability
Imagine separate teams owning orders, payments, and shipping.
The APIs expose operations similar to:
GET /api/orders/ORD-1001
GET /api/payments/ORD-1001
GET /api/shipments/ORD-1001A support assistant asks: Why has ORD-1001 not been delivered?
The useful capability is not "call these three URLs." It is get the order's current context, correlate the facts, and return the evidence.
The demo exposes two read-only MCP tools:
get_order_contextretrieves one order together with its payment and shipment state.find_at_risk_ordersidentifies a bounded set of orders that meet explicit risk rules.
The second tool is deliberately more than a one-to-one REST proxy. It composes several backend operations behind a stable, business-oriented contract.
A model might choose to invoke a tool, but it does not get to define the backend URL, issue arbitrary HTTP requests, or change the risk policy.
Keep the architecture small
The implementation uses a thin MCP adapter, an application service, and a typed HTTP client:
Browser MCP client .NET client JavaScript client Java client
\ | | /
MCP over HTTP
|
ASP.NET Core /mcp
|
OrderTools (adapter)
|
OrderInvestigationService
/ \
OrderRiskPolicy EnterpriseApiClient
| |
Pure rules Existing REST APIs
|
Orders / Payments / ShippingThere is no need for an event bus, mediator, repository abstraction, or distributed agent coordinator here.
The components have different responsibilities:
| Component | Responsibility |
| --- | --- |
| OrderTools | MCP contracts, request validation, access checks, and tool results |
| OrderInvestigationService | Compose the order, payment, and shipping information |
| OrderRiskPolicy | Apply deterministic rules to observed business data |
| EnterpriseApiClient | Encapsulate the existing HTTP contracts, timeouts, and transport errors |
| ASP.NET Core boundary | Authenticate callers and enforce transport-level access policy |
A REST endpoint and an MCP tool can use the same application service. The business rules should not depend on ModelContextProtocol types.
This is the same separation I would aim for in a production integration, even though the surrounding security and infrastructure would be substantially more demanding.
Hosting MCP with the official .NET SDK
The server uses the official MCP C# SDK, specifically the ModelContextProtocol.AspNetCore package.
A small part of the demo configuration is:
builder.Services.AddMcpServer()
.WithHttpTransport(options =>
options.SessionMode =
HttpServerSessionMode.StatefulForInitializeClients)
.WithTools<OrderTools>();
// After UseAuthentication() and UseAuthorization():
app.MapMcp("/mcp").RequireAuthorization();This is an excerpt, not a complete application. Authentication registration, configuration, the tool implementation, and error handling are deliberately omitted.
Why choose StatefulForInitializeClients instead of plain stateless mode?
The 2026-07-28 MCP specification has a stateless protocol core. The C# SDK v2 supports it. However, an older Java SDK client in this demo still uses the initialization-based protocol. The hybrid setting serves modern clients statelessly while allowing older clients to initialize sessions.
That is a compatibility decision, not a reason to make a new server stateful by default. For a new deployment with compatible clients and no session-dependent behavior, I would use HttpServerSessionMode.Stateless.
The SDK transport documentation explains these modes and the migration behavior in detail.
Design tools as capabilities, not unrestricted gateways
An unsafe shortcut is to publish a tool that accepts a URL, HTTP method, and request body, then forwards whatever the model supplies.
A better interface starts with a narrow operation and a constrained argument:
[McpServerToolType]
public sealed class OrderTools
{
[McpServerTool]
[Description("Read-only context for one order.")]
public static async Task<CallToolResult> get_order_context(
[Description("Order ID such as ORD-1001")] string orderId,
OrderInvestigationService service,
IHttpContextAccessor contextAccessor,
ILogger<OrderInvestigationService> logger,
CancellationToken cancellationToken)
{
// Validate access and orderId, then call the application service.
// Convert expected business failures to bounded tool results.
throw new NotImplementedException();
}
}This is an abbreviated signature to show where the boundary belongs. The real tool implementation validates IDs, checks scopes, delegates to the service, and maps expected failures to structured MCP results.
For example, the demo accepts order identifiers matching ORD- followed by exactly four digits. A path-like value such as ../../etc/passwd is rejected before any downstream call.
Tool schemas help an AI client understand the contract, but a schema is not a security control. Validation must run on the server.
Also, a tool's description is not permission to access data. The model cannot grant itself extra rights by generating plausible arguments.
Authorization has two layers
An enterprise MCP server needs at least two distinct authorization decisions.
First: may this caller access the MCP endpoint at all? For a remote server, use HTTPS, an appropriate OAuth flow, validated access tokens, and ASP.NET Core authentication and authorization middleware. A token's signature alone is insufficient; validate issuer, audience, expiry, and the relevant scopes.
Second: may this caller execute this tool against this resource? The server must check the operation and, for real business data, the particular order and tenant.
The demo illustrates the distinction with two fictional roles:
| Caller | Read one order | Scan for at-risk orders |
| --- | --- | --- |
| Anonymous | Denied | Denied |
| Viewer (orders:read) | Allowed | Denied |
| Investigator (orders:read, orders:scan) | Allowed | Allowed |
The local demo mints short-lived, signed tokens for those fictional personas. Anyone with local access to its demo token endpoint can choose a persona. That endpoint is not authentication and must never be exposed as a real sign-in service.
In production, identity would come from a trusted authorization server, with a complete MCP OAuth integration, appropriate token validation, tenant and object-level policy, and suitably scoped downstream credentials.
The demo checks tool scopes in the tool adapter. The SDK also offers authorization request filters, including AddAuthorizationFilters() for ASP.NET Core authorization attributes. Whichever approach is chosen, make sure endpoint authentication, tool authorization, and business-object authorization are not accidentally treated as the same check.
An MCP tool returning isError: true for a denied operation is a useful structured result, but it does not replace correct HTTP-layer authentication or authorization.
Do not forward tokens blindly
One of the easiest mistakes is to use the same bearer token from the AI client for every downstream API.
That token might be intended for the MCP server, not for the order service. Passing it along without the proper audience and trust relationship undermines token boundaries.
Instead, the design needs an explicit downstream identity strategy:
- Use appropriately scoped service-to-service credentials when the operation is safely authorized at the MCP boundary.
- Use an approved on-behalf-of or token-exchange flow when the backend must enforce the end user's permissions.
- Enforce tenant and resource ownership where the authoritative data lives.
- Never allow a tool argument to choose the token issuer, target host, or arbitrary credential.
The current local demo uses synthetic identities and fictional backend data. It does not implement production-grade downstream delegation.
These concerns are covered in the official MCP authorization specification and security guidance.
Make failures explicit and boring
The order investigation may call three APIs. The payment service can respond while shipping times out. The tool must not reinterpret that timeout as "no shipping issues."
The demo uses a typed HttpClient with a five-second downstream timeout. For an individual order, the application service fetches order, payment, and shipment information concurrently. If the required records are not available, it does not fabricate a complete context.
Expected problems are represented with bounded error codes such as:
{
"error": "backend_timeout",
"message": "A downstream API timed out."
}The MCP result marks the failed tool call with isError: true. Internal exception details are logged by the service, not returned to the model as unrestricted stack traces.
One trade-off deserves attention: in the demo, a missing required record produces a simple incomplete/not-found outcome. A production system may need to distinguish missing order, missing payment, missing shipment, and temporary data inconsistency. That distinction should come from explicit domain contracts, not from the model guessing what an empty value means.
Evidence should survive the model's explanation
A support assistant might say that a failed shipment caused an undelivered order. But the application should keep the underlying facts visible:
{
"orderId": "ORD-1001",
"paymentStatus": "Captured",
"shipmentStatus": "Failed",
"evidence": [
"orders:GET /api/orders/ORD-1001",
"payments:GET /api/payments/ORD-1001",
"shipping:GET /api/shipments/ORD-1001"
]
}This is a simplified illustrative response, not the exact serialized demo contract.
The application returns observations and source references. Deterministic code evaluates the demo risk rules. A model can then explain the evidence or suggest checks without being the source of truth.
For real production evidence, source references need stronger semantics than route names alone: timestamps, correlation IDs, data versions, and appropriate authorization to retrieve the original record. A source reference is not automatically a trustworthy citation.
That approach is consistent with AI Proposes, Measurements Decide: the AI can assist with interpretation, while code and verifiable records retain responsibility for the facts.
Security tests that demonstrate something real
A demonstration is more credible when it includes negative cases, not just a successful tool call.
The proof of concept checks:
- An anonymous request cannot access the protected MCP endpoint.
- A Viewer can read an order but cannot perform the broader risk scan.
- A malformed order ID is rejected before the backend call.
- A request for an unknown write tool, such as
refund_payment, is rejected. - Cross-origin browser requests are denied by the local server's origin check.
- Backend failures produce bounded errors rather than revealing internal details.
These checks are useful, but none proves that the system is secure against all threats. In particular, origin checks do not replace authentication, and a loopback-bound demo still needs to be treated as local development software.
The current demo runs synthetic scenarios through real MCP clients. Its validation workflow covers .NET, JavaScript, Java, and browser behavior; the latest checked CI run passed. That is evidence for the tested flows, not a security certification.
What is still missing before production?
I would not expose this server to a corporate network as-is.
The local version does not have real user sign-in, complete OAuth authorization-server integration and metadata, tenant isolation, persistent audit records, production TLS, rate limiting, gateway policy, or fully defined downstream credential delegation.
For a production implementation I would add:
- Identity and authorization: OIDC/OAuth integration, valid token audience and scopes, resource and tenant checks, and appropriate user approval for write operations.
- Network protections: TLS, host and origin validation, outbound destination allowlists, and controlled ingress.
- Operational guardrails: timeouts, concurrency limits, quotas, bounded outputs, and consistent retry policy.
- Observability: structured audit events, OpenTelemetry traces, MCP tool-call metrics, and correlated downstream activity.
- Reliability tests: dependency failures, cancellation, mixed-version clients, load, and authorization regression tests.
- Governance: tool catalog ownership, contract versioning, schema reviews, deprecation policy, and data classification.
A gateway can help with common controls, but it cannot know whether a particular support employee is allowed to see order ORD-1001. That still belongs in application and domain authorization.
Why test clients in different languages?
The original goal was to demonstrate interoperability, not model intelligence.
The same tools are consumed by a browser MCP client and SDK-based clients in .NET, JavaScript, and Java. The browser connects to the actual /mcp endpoint; it does not bypass the protocol with a separate convenience REST endpoint.
That is a more meaningful demo of MCP's value than showing one LLM answer. We can verify discovery, argument validation, output contracts, and access control without paying for or depending on any model.
An optional locally hosted LLM can make the demonstration more conversational. It does not change the security architecture: the model still receives a bounded tool catalog and the server still owns every access decision.
The trade-off I would keep
MCP is useful here because one curated set of capabilities can serve several AI clients while the existing REST services keep ownership of the business data.
The most important architecture decisions remain conventional software engineering:
- Keep the MCP adapter thin.
- Reuse application services instead of duplicating business logic.
- Enforce permissions on the server, not in prompts.
- Make failures and evidence explicit.
- Prefer deterministic business rules where possible.
- Separate a convenient local demo from what an enterprise security review would actually require.
A production MCP integration is not just a working tools/call. It is an integration surface that the organization can authorize, monitor, evolve, and trust.
The protocol makes the capability accessible. The application architecture and security controls determine whether exposing it is a good idea.