📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you'd build an MCP server in C# with the official MCP SDK to expose part of your product's API to AI assistants. Explain tools, resources and prompts, stdio versus Streamable HTTP, and how you keep the server safe to expose.

Building a Model Context Protocol server in .NET 10 with the ModelContextProtocol SDK: the three primitives (tools, resources, prompts), stdio vs Streamable HTTP transports, tool annotations, DI, authorisation with MapMcp, and keeping tools narrow and validated.

Mid-Level Coding Intermediate ai aspnet-core mcp model-context-protocol security tool-calling

🎯 Key points

  • MCP standardises how an AI host discovers and calls tools, reads resources and fetches prompts over JSON-RPC
  • Tools = model-invoked actions; resources = app-controlled readable data; prompts = user-selected templates
  • stdio for local, per-user servers; Streamable HTTP (ModelContextProtocol.AspNetCore, MapMcp) for remote, shared servers
  • AddMcpServer().WithHttpTransport().WithTools<T>() with [McpServerToolType] / [McpServerTool] and [Description]
  • As of November 2026: SDK 1.0 shipped March 2026 (spec 2025-11-25); 2.x since July 2026 (spec 2026-07-28, stateless HTTP by default); check release notes before copying samples
  • Tools wrap application use cases, not raw endpoints or SQL; narrow parameters, validated in code
  • Annotate ReadOnly / Destructive / Idempotent and require authorisation on MapMcp; the user's identity flows to the tool
  • Return compact, model-friendly results and errors the model can act on

⏱ 30-second answer

MCP (Model Context Protocol) is an open JSON-RPC protocol that lets any AI host (Copilot, Claude, VS Code, your own agent) discover and call capabilities on a server. A server exposes three primitives: tools (actions the model decides to call), resources (data the application reads into context) and prompts (templates the user picks). In .NET you use the official ModelContextProtocol SDK (1.0 in March 2026, 2.0 in July 2026): AddMcpServer().WithHttpTransport().WithTools<T>() plus app.MapMcp() for remote Streamable HTTP, or WithStdioServerTransport() for a local process. Tools are plain C# methods marked [McpServerTool], resolved through DI. To keep it safe, wrap use cases, not raw endpoints, validate every argument, mark tools read-only or destructive, and require authorisation so each call runs as the signed-in user. The trade-off: one server serves every AI host, but it is a new public attack surface.

🗣 Full answer (senior)

How I would answer this in an interview

"MCP is a protocol, not a library: a host like VS Code or Claude connects to my server over JSON-RPC, asks what it offers, and then calls it. The server offers three things. Tools are actions the model can choose to invoke, like search_orders or create_return. Resources are read-only data the host application can pull into context, addressed by URI, like orders://ORD-12345. Prompts are reusable templates the user selects, like 'summarise this customer's open tickets'. The point is that I write the integration once and every MCP-capable host can use it.

In .NET 10 I use the official ModelContextProtocol SDK. For a remote server I add ModelContextProtocol.AspNetCore, call AddMcpServer().WithHttpTransport().WithTools<OrderTools>() and app.MapMcp("/mcp"). Tools are methods on a class marked [McpServerToolType], each with [McpServerTool] and [Description] attributes, and their parameters become the JSON schema the model sees. They are resolved from DI, so they call my existing MediatR handlers or services. For a developer tool that runs on someone's laptop, I'd use WithStdioServerTransport() and ship it as a dotnet tool. The SDK reached 1.0 in March 2026 and 2.0 in July 2026, which follows the 2026-07-28 spec and makes HTTP stateless by default, so it scales out behind a load balancer without sticky sessions.

The mistake I see is wrapping the REST API one-to-one, or worse, giving the model a 'run SQL' tool. I design tools around tasks with narrow, validated parameters, mark them with ReadOnly or Destructive annotations so hosts can ask for confirmation, and put RequireAuthorization() on MapMcp so the tool runs with the caller's identity and my existing authorisation rules. An MCP server is a public API whose client is a model, so I design it with the same care and less trust."


The three primitives

Primitive Who decides to use it Example .NET attribute
Tool The model get_order_status(orderNumber) [McpServerTool] on a method in a [McpServerToolType] class
Resource The host application / user orders://ORD-12345 as JSON [McpServerResource] in a [McpServerResourceType] class
Prompt The user (slash command, picker) summarise_customer(customerId) [McpServerPrompt] in a [McpServerPromptType] class

Transports

Transport Use when Notes
stdio Local tool per user, e.g. a CLI for your dev team Host launches the process; identity is the local user; ship as a dotnet tool
Streamable HTTP Shared, remote server for many users MapMcp() in ASP.NET Core; OAuth 2.1 bearer tokens; stateless by default in SDK 2.0

Designing tools

Do Don't
One tool per user task (create_return) Mirror every REST endpoint
Typed, narrow parameters with descriptions Free-form query or sql strings
Compact results with the fields the model needs Return whole entities or 5 MB JSON
Clear error text the model can recover from Stack traces
Annotations: ReadOnly, Destructive, Idempotent Leave hosts guessing which tools change data

Production example

We exposed [an internal order-management API] through an MCP server with 6 tools instead of the 40 REST endpoints. Tool-selection errors in our evaluation set dropped from about 18% to 4% because the descriptions were task-shaped, and since the server reused the existing MediatR handlers and authorisation policies, the security review took [two days] instead of a new design.

🔍 What the interviewer is checking

Checks whether the candidate can build an MCP server with the real .NET SDK and design its tools as a safe, narrow API.

Green flags

  • Distinguishes tools, resources and prompts by who controls them
  • Uses AddMcpServer, WithHttpTransport/WithStdioServerTransport, MapMcp, [McpServerTool] correctly
  • Reuses application handlers and existing authorisation
  • Knows annotations are hints and enforces rules server-side
  • Aware of SDK versions and the stateless HTTP change

Red flags

  • A run_sql or generic HTTP tool
  • No authentication on a remote server
  • Confuses MCP with a specific vendor's plugin format
  • Returns whole entities or stack traces as tool results

📚 Learn in depth

1. What MCP is on the wire

MCP is JSON-RPC 2.0 messages between a client (inside a host such as VS Code, Claude or your own agent) and a server. The client discovers capabilities (tools/list, resources/list, prompts/list) and invokes them (tools/call, resources/read, prompts/get).

 ┌────────────── Host (IDE, chat app, your agent) ─────────────┐
 │   LLM  ◄──►  MCP client ──────────────┐                      │
 └───────────────────────────────────────┼──────────────────────┘
                                         │ JSON-RPC over stdio or
                                         │ Streamable HTTP (+ OAuth bearer)
                          ┌──────────────▼───────────────┐
                          │      MCP server (.NET)       │
                          │  tools / resources / prompts │
                          │      ↓ DI                    │
                          │  MediatR handlers, services  │
                          └──────────────────────────────┘

2. Specification versions and the C# SDK

The SDK is maintained in the modelcontextprotocol/csharp-sdk repository with Microsoft. As of late 2026:

  • 1.0 (5 March 2026) implemented the 2025-11-25 spec: tool/resource/prompt icons, improved authorisation server discovery, and experimental tasks for long-running requests.
  • 2.0 (28 July 2026) implements the 2026-07-28 spec, the largest revision so far: the HTTP transport is stateless by default (no Mcp-Session-Id session pinning), negotiation is discovery-first instead of the old initialize handshake, and Roots, Sampling and Logging capability APIs are deprecated (diagnostic MCP9005). Stable, non-deprecated 1.x APIs such as AddMcpServer() keep working.

Check the SDK release notes before you copy older blog code; samples from 2025 often use preview APIs that were renamed.

3. How a tool becomes a schema

The SDK reflects over methods marked [McpServerTool]. The method name (snake-cased) or Name property becomes the tool name; [Description] on the method and parameters becomes the descriptions; parameter types become the JSON schema. Parameters of types it recognises, such as CancellationToken, IServiceProvider, McpServer or services registered in DI, are injected and not shown to the model. The return value is serialised into the tool result content. The same tools are AIFunctions, so on the client side McpClientTool plugs straight into ChatOptions.Tools for an IChatClient.

4. Annotations and what hosts do with them

Tool annotations (ReadOnly, Destructive, Idempotent, OpenWorld, Title) are hints in the tool list. Hosts use them to auto-approve read-only tools and ask the user before destructive ones. They are hints, not enforcement: a malicious or careless host can ignore them, so enforcement stays in your server.

5. Authorisation for remote servers

For Streamable HTTP, the MCP authorisation spec uses OAuth 2.1: the server is a protected resource, publishes protected resource metadata pointing to your authorisation server (for example Microsoft Entra ID), and validates bearer tokens. In ASP.NET Core that is ordinary JWT bearer authentication plus MapMcp().RequireAuthorization(...). Inside the tool, IHttpContextAccessor or the injected ClaimsPrincipal gives you the user, so your existing authorisation policies decide what they can see.

6. Results and errors

A tool result is content (text, structured JSON, images, resource links). Errors should come back as a tool result flagged as an error with a short message, so the model can retry with better arguments; protocol errors are for broken requests. Keep results small: the host puts them into the model's context window.

Try it yourself

  1. Create an ASP.NET Core project, add ModelContextProtocol.AspNetCore, expose one read-only tool and connect from VS Code's MCP configuration.
  2. Run the MCP Inspector (npx @modelcontextprotocol/inspector) against it and look at the generated tool schema.
  3. Add a destructive tool with Destructive = true and observe the host asking for confirmation.
  4. Add JWT bearer authentication and RequireAuthorization(); confirm unauthenticated calls get 401.
  5. Write an xUnit test that connects an McpClient to the server through WebApplicationFactory and calls ListToolsAsync.

💻 Code

A remote MCP server that reuses application use cases, requires authorisation and marks tool behaviour.

// Program.cs (.NET 10, ModelContextProtocol.AspNetCore)
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Orders.Mcp;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = builder.Configuration["Auth:Authority"];   // e.g. Entra ID tenant
        o.Audience = builder.Configuration["Auth:McpAudience"];  // token must be issued for THIS server
    });
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("mcp.orders", p => p.RequireAuthenticatedUser().RequireClaim("scp", "orders.mcp"));

builder.Services.AddHttpContextAccessor();
builder.Services
    .AddMcpServer()
    .WithHttpTransport()          // Streamable HTTP; stateless by default in SDK 2.x
    .WithTools<OrderTools>();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapMcp("/mcp").RequireAuthorization("mcp.orders");
app.Run();
using System.ComponentModel;
using MediatR;
using ModelContextProtocol.Server;

namespace Orders.Mcp;

[McpServerToolType]
public sealed class OrderTools(ISender mediator)
{
    [McpServerTool(Name = "get_order_status", ReadOnly = true, Idempotent = true)]
    [Description("Gets the status and last update of one of the signed-in customer's orders.")]
    public async Task<string> GetOrderStatus(
        [Description("Order number in the form ORD-nnnnn")] string orderNumber,
        CancellationToken ct)
    {
        if (!OrderNumber.TryParse(orderNumber, out var id))
            return "Invalid order number. Expected ORD-nnnnn.";

        // The handler applies the same ownership checks as the REST API.
        var result = await mediator.Send(new GetOrderStatusQuery(id), ct);
        return result is null ? "Order not found." : $"{result.Status} (updated {result.UpdatedUtc:u})";
    }

    [McpServerTool(Name = "request_return", Destructive = true, Idempotent = false)]
    [Description("Starts a return for one order line. Hosts should confirm with the user first.")]
    public async Task<string> RequestReturn(
        [Description("Order number in the form ORD-nnnnn")] string orderNumber,
        [Description("Line number on the order, starting at 1")] int lineNumber,
        [Description("Short reason given by the customer")] string reason,
        CancellationToken ct)
    {
        if (!OrderNumber.TryParse(orderNumber, out var id) || lineNumber is < 1 or > 200)
            return "Invalid order or line number.";

        var outcome = await mediator.Send(new RequestReturnCommand(id, lineNumber, reason[..Math.Min(reason.Length, 500)]), ct);
        return outcome.Succeeded ? $"Return {outcome.ReturnId} created." : outcome.Error!;
    }
}

⚠ Common mistakes

  • Mistake: Wrapping every REST endpoint as a tool. Why it is wrong: Dozens of overlapping tools confuse tool selection and inflate the prompt. Instead: Expose a handful of task-shaped tools.
  • Mistake: Offering a generic run_sql or call_api(url) tool. Why it is wrong: It hands the model, and anyone who can inject into it, unrestricted access. Instead: Narrow, typed parameters behind your existing use cases.
  • Mistake: Running a remote server without authentication, or with a shared service account. Why it is wrong: Every caller gets the same, usually broad, access and nothing is attributable. Instead: OAuth bearer tokens issued for this server's audience and RequireAuthorization(), with per-user checks in handlers.
  • Mistake: Relying on Destructive/ReadOnly annotations for safety. Why it is wrong: They are hints that hosts may ignore. Instead: Enforce permissions, limits and confirmations server-side.
  • Mistake: Returning raw entities with internal fields. Why it is wrong: Wastes context and can leak data the user shouldn't see. Instead: Purpose-built, compact result shapes.
  • Mistake: Copying 2025 preview samples. Why it is wrong: APIs were renamed for 1.0 and the protocol changed in 2.0. Instead: Check the current SDK version and release notes.
  • Mistake: Using stdio for a shared multi-user service. Why it is wrong: stdio servers run per user on their machine and carry their local credentials. Instead: Streamable HTTP for shared servers.

🏛 Senior insight: trade-offs

An MCP server is an API whose consumer is a model acting for a user, so I apply the normal API rules (versioning, authorisation, rate limits, audit) and then distrust the caller a bit more. The best design reuses the application layer: tools call the same handlers as the REST API, so the business rules and ownership checks are not duplicated. I measure success with an evaluation set of user tasks (did the model pick the right tool with valid arguments), plus per-tool error rates and latency in Application Insights.

Option When it fits Cost When not to
MCP server (Streamable HTTP) Many AI hosts or teams need the same capabilities New public surface, OAuth setup Only your own app's agent uses the tools
In-process AIFunction tools One agent inside your own service Lowest latency, no protocol Other hosts need the capability too
MCP server (stdio, dotnet tool) Developer tooling on laptops Distribution and updates Shared data needing central authorisation

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the server is ready to ship Why: Checks automated testing of MCP tools and schema stability
    How to answer

    Unit-test the tool classes directly as ordinary C# (they are plain methods with DI dependencies), including edge cases: invalid formats, out-of-range numbers, missing records, over-long strings, and inputs that look like instructions. For the protocol, host the server in WebApplicationFactory and connect an McpClient over the test server's HTTP handler, then snapshot ListToolsAsync (names, descriptions, schemas, annotations) so accidental schema changes fail CI, and call tools to assert on result content and error messages, not just shape. Add authorisation tests (no token → 401, wrong scope → 403, another user's data → refused). Load-test the HTTP endpoint (for example with k6 or NBomber) against a latency target, since hosts call tools inside a user's wait. Finally run an evaluation set of user tasks against a real model to check tool selection, because a description change can break the model's choices without breaking any code.

  2. When: Candidate mentions validating arguments in tools Why: Checks depth on tool calling and argument validation
    How to answer

    With tool calling, you describe functions (name, description, JSON schema of parameters) in the request. The model can reply with a tool-call request instead of text; your app executes it and sends the result back, and the model continues. In Microsoft.Extensions.AI, AIFunctionFactory.Create turns a C# method into a tool, you pass it in ChatOptions.Tools, and UseFunctionInvocation() runs the loop.

    The model chooses the arguments, so treat them as untrusted input: validate them, authorise against the signed-in user inside the tool, expose only least-privilege tools, require approval for side effects and cap iterations. The trade-off: tools make the model useful, but every tool widens what a confused or manipulated model can do.

  3. When: Candidate mentions logging or tracing tool calls Why: Checks how they'd make MCP calls observable with Activity and OpenTelemetry
    How to answer

    Activity is .NET's span type and ActivitySource is the factory that creates them, the equivalent of an OpenTelemetry Tracer. They live in System.Diagnostics, so libraries can emit spans without referencing OpenTelemetry at all. You call source.StartActivity("name", ActivityKind.Internal) inside a using, add tags (attributes), events and a status, and disposing it records the duration.

    StartActivity returns null when nothing is listening or the sampler drops the span, which is why you write activity?.SetTag(...). The OpenTelemetry SDK only listens to sources registered with AddSource("MyCompany.Orders"). Activity.Current is stored in an AsyncLocal, flows across await, and becomes the parent of the next activity.

    The trade-off: the API is free when tracing is off, but you must name sources consistently or your spans silently go nowhere.

🛠 Real-world problems: how you handle them

MCP tool returned whole customer records and blew the context window
Situation
[An internal MCP server] exposed a `search_customers` tool to [around 200] support staff using VS Code and a chat host. The tool returned full customer entities for every match.
Signals
Users reported the assistant 'forgetting' instructions mid-conversation; Application Insights showed tool results averaging [180 KB]; model calls failing with context-length errors on broad searches; token cost per conversation up [4x] in a week.
Investigation
Traced conversations with OpenTelemetry GenAI spans to see input tokens per model call jump after `search_customers`; inspected tool result sizes in custom metrics; reviewed the tool code and found it serialised the EF entity including notes and address history; checked with the privacy lead whether those fields were needed at all.
Resolution
Immediately capped results at 10 matches and truncated fields. Then replaced the result with a purpose-built DTO (id, display name, status, last contact) and added a separate `get_customer_summary` tool for one customer, with ownership checks in the handler.
Prevention
Snapshot tests of tool schemas and result shapes in CI; a histogram metric of tool result size with an alert above [8 KB]; a review checklist item 'tool returns DTO, not entity'; documented in an ADR on MCP tool design.

How to tell it (STAR)

**S:** We had an MCP server used by [about 200] support staff, and after a release people said the assistant kept losing track of the conversation. **T:** I was asked to find out why and fix it without taking the tool away. **A:** I looked at the GenAI traces and saw input tokens jump every time `search_customers` ran; the tool was returning whole EF entities, [180 KB] at a time, including fields support didn't need. I capped results that day, then replaced the payload with a small DTO and split out a single-customer summary tool behind the existing ownership checks. I added a result-size metric with an alert and snapshot tests for tool outputs. **R:** Average tool result fell to [3 KB], context-length errors went to zero and cost per conversation dropped by [about 70%].

More in AI Agents and MCP

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me