MCP(Model Context Protocol) 是一種協定,讓大型語言模型(LLM)可以與外部系統或服務進行互動,例如查詢資料庫、調用 API 或執行特定功能。其主要目的是解決 LLM 的「幻覺問題」(hallucination),即模型可能基於訓練數據生成不準確的回應。
MCP 的架構分為三個角色:
-
Host:負責接收使用者請求的 LLM 應用程式,例如 Claude 桌面應用程式。
-
Client:Host 的一部分,負責與 MCP server 通信。
-
Server:提供外部功能或資料的服務端,具備工具(Tools)和資源(Resources)。
MCP 的運作流程:
-
Host 啟動時,Client 會向 Server 請求工具清單。
-
根據使用者的輸入,LLM 決定使用哪些工具。
-
Client 調用 Server 的工具,完成功能後回傳結果。
-
Host 整合回應並傳遞給使用者。
應用案例: 可以用 MCP server 與 LINE Messaging API 結合,讓 LLM 發送訊息給 LINE 官方帳號的好友,或根據天氣資訊生成動態內容。
二、C# MVC 範例:簡易 MCP Server
以下是基於 C# ASP.NET Core MVC 實作的一個簡單 MCP Server 範例,實現一個名為 broadcast_message
的工具,用於模擬發送訊息。
1. 建立 Model(工具定義)
// Models/Tool.cs
public class Tool
{
public string Name { get; set; }
public string Description { get; set; }
}
2. 建立 Controller(處理請求)
// Controllers/McpController.cs
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("mcp")]
public class McpController : ControllerBase
{
// 模擬工具清單
private static readonly List<Tool> Tools = new List<Tool>
{
new Tool { Name = "broadcast_message", Description = "Send a message to all users" }
};
// Endpoint: tools/list
[HttpGet("tools/list")]
public IActionResult GetTools()
{
return Ok(Tools);
}
// Endpoint: tools/call
[HttpPost("tools/call")]
public IActionResult CallTool([FromBody] dynamic request)
{
string toolName = request.tool;
string message = request.parameters?.message;
if (toolName == "broadcast_message" && !string.IsNullOrEmpty(message))
{
// 模擬訊息廣播
return Ok(new { success = true, message = $"Broadcasted: {message}" });
}
return BadRequest(new { success = false, error = "Invalid tool or parameters" });
}
}
3. 建立 View(測試頁面)
<!-- Views/Home/Index.cshtml -->
<html>
<head>
<title>MCP Test</title>
</head>
<body>
<h1>MCP Server 測試</h1>
<p>訪問 `/mcp/tools/list` 取得工具清單</p>
<p>訪問 `/mcp/tools/call` 測試工具呼叫</p>
</body>
</html>
4. 啟動專案並測試
-
啟動 ASP.NET Core 專案。
-
測試工具清單:
-
用瀏覽器訪問:
http://localhost:5000/mcp/tools/list
-
回應:
[ { "name": "broadcast_message", "description": "Send a message to all users" } ]
-
-
測試工具呼叫:
-
用 Postman 或其他工具發送 POST 請求到
http://localhost:5000/mcp/tools/call
,Body(JSON)如下:{ "tool": "broadcast_message", "parameters": { "message": "Hello, MCP!" } }
-
回應:
{ "success": true, "message": "Broadcasted: Hello, MCP!" }
-
總結
以上範例展示了如何用 C# MVC 實現一個簡單的 MCP Server,包含工具清單和工具調用功能,適用於理解 MCP 的基本概念與運作方式。
參考連結