Step 9 of 16
Consume MCP tools, expose an agent capability as an MCP tool, and secure the protocol boundary.
เมื่อ local tools ใช้งานได้แล้ว ค่อยเพิ่ม MCP boundary พร้อม auth, allow-list และ timeout ครับ
Level: Advanced
Model Context Protocol หรือ MCP แยก tool provider ออกจาก agent host ครับ ทำให้ tool ชุดเดียวถูกใช้จากหลาย clients ได้ แต่ network boundary เพิ่มเรื่อง authentication, timeout, schema compatibility และ data exposure
ต่อ MCP server แบบ allow-list พร้อม authentication และ contract tests จากนั้น expose read-only agent capability เป็น MCP tool ครับ
using ModelContextProtocol.Client;
using Microsoft.Extensions.AI;
await using var mcpClient = await McpClient.CreateAsync(
new StdioClientTransport(new StdioClientTransportOptions
{
Name = "HandbookTools",
Command = "dotnet",
Arguments = ["run", "--project", "../TPCoder.HandbookMcp"]
}));
var mcpTools = await mcpClient.ListToolsAsync();
AIAgent agent = projectClient.AsAIAgent(
model: model,
instructions: "Use handbook tools for internal policy questions.",
tools: [.. mcpTools.Cast<AITool>()]);
Stdio เหมาะกับ local process ส่วน remote deployment ต้องใช้ transport และ authentication ที่เข้ากับสภาพแวดล้อมครับ Allow-list server และ tool names อย่าเชื่อ metadata จาก server ที่ผู้ใช้กำหนดเอง
Agent Framework แปลง agent เป็น AIFunction และ MCP tool ได้:
using ModelContextProtocol.Server;
McpServerTool tool = McpServerTool.Create(agent.AsAIFunction());
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithTools([tool]);
ตั้ง name และ description ของ agent ให้บอก capability ชัด เพราะค่าทั้งสองกลายเป็น contract ที่ MCP client ใช้เลือก tool ครับ
ทดสอบ list tools, invalid arguments, cancellation, server restart และ protocol error ก่อนต่อกับ agent หลักครับ
Snapshot tool names, descriptions และ schemas ใน contract test เพื่อจับ breaking change ทดสอบ invalid auth, forbidden tool, oversized input, timeout, cancellation และ server disconnect ครับ
แยก MCP server identity จาก end-user identity แล้วส่ง user context ด้วยกลไกที่ server ตรวจได้ Pin package หรือ container digest, จำกัด egress และปิด dynamic server command จาก user input
ส่ง approved-server registry, auth configuration, schema contract tests, timeout policy, audit events และ threat-model update