跳到正文
DEV Community· Nilesh Vishwakarma·· 3 小時前AI 評分62

MCP 為何重要:理解 Model Context Protocol,並在 .NET 建立首個 MCP 伺服器

Why MCP Matters: Understanding Model Context Protocol and Building Your First MCP Server in .NET

AI 導讀

MCP 以標準方式讓 AI 應用與外部工具及數據來源溝通,文章並示範如何在 .NET 建立 MCP 伺服器。範例使用 .NET 10 SDK 和官方 MCP C# SDK,以固定示範資料建立訂單狀態工具,並用 MCP Inspector 測試;輸入訂單 ID 102 會回傳 Shipped。MCP 可與既有 REST API 配合,權限檢查和業務規則仍由底層應用負責。

正文

AI models can understand our questions, but connecting them to real applications is a different challenge. Here's where MCP fits in.

AI assistants are useful when we want to explain a concept, summarize something, or work through a problem. But the moment we ask about data inside our own applications, things get more complicated.

Imagine asking an AI assistant: “What is the current status of order 102?”

The model understands the question. What it doesn't have is access to our order system. Somewhere, we need an integration that knows how to retrieve the answer.

We could build that integration ourselves, using an API and a bit of custom code. That works well for one application. The challenge grows when several AI tools need to work with the same systems. This is the problem Model Context Protocol (MCP) is intended to address.

So, what is MCP?

MCP is an open protocol that provides a standard way for AI applications to communicate with external tools and data sources.

It doesn't turn a database into an AI system. It doesn't replace an API. And it doesn't decide what the model should say.

Instead, MCP defines how an application can discover available capabilities, call them, and receive their results.

An MCP server can expose three common kinds of capabilities:

  • Tools are operations a client can invoke, like looking up an order or searching an issue tracker.
  • Resources provide data a client can read, such as documentation or configuration.
  • Prompts provide reusable templates for particular interactions.

For a first project, tools are the easiest place to start.

Three main types of MCP server capabilities: tools, resources, and prompts

Figure 1. MCP server capabilities at a glance. The examples are illustrative.

Why not just use a REST API?

You absolutely can. In fact, many useful MCP servers call existing REST APIs internally.

The difference is who is consuming the interface and how they discover it. An ordinary API usually expects a developer to know its endpoints, authentication rules, and request formats. MCP provides a common way for compatible AI applications to discover the tools explicitly exposed by an MCP server and their input schemas.

Think of an order service. It might already expose GET /orders/{id}. We don't need to rewrite it. We can place an MCP server in front of the existing service and expose a tool such as GetOrderStatus.

The application still owns its business rules and security checks. MCP only provides another interface to selected operations.

That is why comparing MCP and REST as if one must replace the other misses the point. They often work together.

Comparison of repeated custom adapters and a shared MCP server over an existing API

Figure 2. Conceptual comparison: applications can reuse one MCP server rather than implementing separate adapters. MCP clients remain within their host applications.

What happens when an AI application uses MCP?

There are three parts worth understanding:

  • The host is the AI application the user interacts with.
  • An MCP client runs as part of that host and communicates with an MCP server.
  • The MCP server exposes tools or other capabilities, and can call services behind the scenes.

A typical request can follow this flow:

Conceptual MCP order-status request flow between user, AI host, MCP client, MCP server, and orders API

Figure 3. Conceptual request flow. Host decisions and permissions depend on the application; arrows show relevant interactions, not every protocol message.

This is a conceptual flow, not a complete protocol sequence. The host may choose to invoke a tool depending on the user's request, available permissions, and its configuration. The MCP server returns data; the host uses it to prepare an answer.

The MCP server itself does not need an AI model.

Let's build a small MCP server in .NET

Rather than starting with a database, let's expose a tiny order-status tool using fixed demo data. Once that works, the same structure can call a real service.

This example uses the .NET 10 SDK and the official MCP C# SDK.

Create a console project and install the packages:

dotnet new console -n OrdersMcp -f net10.0
cd OrdersMcp

dotnet add package ModelContextProtocol
dotnet add package Microsoft.Extensions.Hosting

Replace Program.cs with:

using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;

var builder = Host.CreateApplicationBuilder(args);

// Standard output is used for MCP messages.
builder.Logging.AddConsole(options =>
    options.LogToStandardErrorThreshold = LogLevel.Trace);

builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();

[McpServerToolType]
public static class OrderTools
{
    [McpServerTool]
    [Description("Gets the status of an order in the demo data.")]
    public static string GetOrderStatus(int orderId) =>
        orderId switch
        {
            101 => "Processing",
            102 => "Shipped",
            _ => "Order not found in demo data"
        };
}

A few lines do most of the work:

AddMcpServer() registers the MCP server. WithStdioServerTransport() allows a local MCP client to communicate with the process through standard input and output. WithToolsFromAssembly() discovers our annotated tool.

The two attributes on OrderTools and GetOrderStatus tell the SDK which method should be exposed. The method accepts an order ID and returns a string. The values are hard-coded for learning purposes; this is not connected to a real order database.

Build the project:

dotnet build -c Release

How can we test it?

The MCP Inspector is a testing tool that can connect to MCP servers, list available tools, and invoke them directly. You don't need to connect an AI model just to check whether the server works.

Install a supported Node.js version (the current Inspector v2 documentation specifies Node.js 22.19 or later), then run:

npx @modelcontextprotocol/inspector dotnet /absolute/path/to/OrdersMcp/bin/Release/net10.0/OrdersMcp.dll

Replace the path with your compiled DLL's location. Open the local address printed by Inspector, connect, and look for GetOrderStatus under the available tools.

Try 102 as the order ID. The demo tool should return Shipped.

That's the important milestone: a separate client can discover and call a tool written in C# through MCP.

To use it in an AI assistant, you then configure an MCP-compatible host to launch or connect to your server. The exact configuration file and approval behavior vary between hosts.

What changes in a real application?

Very little about the basic idea. Instead of returning a value from a switch expression, the tool could call an existing order service.

For example, the responsibilities might look like this:

  • The MCP tool accepts an order ID and invokes the application service.
  • The service checks permissions, applies business rules, and queries the system of record.
  • The tool returns a limited, useful result to the client.

One mistake to avoid is putting all business logic directly into MCP tool methods. If you already have well-designed services, reuse them. That keeps your application usable by web clients, background jobs, and other integrations without depending on MCP.

Security matters too. A tool that only reads an order status is very different from one that cancels orders or issues refunds. Validate inputs, enforce authorization in the underlying application, restrict exposed operations, and consider explicit user approval for sensitive actions. Connecting an AI application should not bypass any existing security boundary.

When should you use MCP, and when shouldn't you?

MCP is a good fit when multiple compatible AI applications need access to the same tools, or when you want a consistent way to expose carefully selected operations from an existing system.

It may be unnecessary when you're writing a regular backend service, building a conventional web or mobile API, or adding one simple function to an AI application you fully control. Direct function calling or an ordinary API might be easier to build and maintain in those cases.

And MCP is not a performance feature. A call still has to reach the underlying service, which has its own latency, failures, permissions, and dependencies. The protocol standardizes the integration boundary; it doesn't remove the engineering work behind it.

Final thoughts

The most useful way to look at MCP is as a bridge between AI applications and capabilities we already have.

You don't need to replace your APIs or redesign your system to try it. Start with one small, read-only tool. Confirm that a client can discover it and call it. Then, if there's a real use case, connect that tool to an existing application service.

Once you understand that flow, MCP becomes much less mysterious. It is not the intelligence behind the assistant. It is one of the ways the assistant can interact with the systems that hold the information it needs.


References

來源:DEV Community · dev.to