Bỏ qua để vào nội dung chính
Thiết kế MCP server đúng: đừng map 1-1 REST API sang tool

Thiết kế MCP server đúng: đừng map 1-1 REST API sang tool

Bởi Hannah Cooper
26 thg 11, 20266 phút đọc

Map mỗi REST endpoint thành một MCP tool làm agent bịa UUID, trượt quy trình và đốt 8.000-12.000 token trước khi user gõ chữ. Cách sửa ở đây.

Bạn generate MCP server từ OpenAPI spec trong mười phút: 40 endpoint thành 40 tool, demo chạy mượt. Đến khi agent phải onboard một user thật, nó gọi sai thứ tự, bịa UUID, rồi kẹt vòng lặp retry ở bước gửi mail. Bài này chỉ ra ba thứ làm hỏng kiểu map 1-1 đó, cách gom tool theo quy trình nghiệp vụ, và một bài test auth bạn chạy được trước khi ship.

Protocol chuẩn hoá transport, không chuẩn hoá tool design

MCP giải quyết phần glue code, và giải quyết tốt. Theo bài hướng dẫn của Debojit trên Dev.to, đây là "an open protocol that standardizes how AI models discover and call external tools", với "server advertises what it can do, and the client (Claude, or any MCP-compatible host) discovers those capabilities at runtime over a standard JSON-RPC transport". Dựng server TypeScript chỉ cần npm install @modelcontextprotocol/sdk zod.

Nhưng protocol không quyết định hộ bạn server expose cái gì. Đó mới là chỗ phần lớn MCP server hỏng — và nó chỉ lộ ra khi agent chạy task thật.

Vì sao map 1-1 REST API luôn vỡ khi gặp task thật

Tác giả bài "Don't expose your REST APIs 1-to-1 in your MCP server" chỉ đúng gốc rễ: frontend và LLM tiêu thụ API theo hai cách khác nhau.

"Front-end applications know exactly how to interact with a REST API. Developers have manually created TypeScript which dictates an application's behaviour, such as the order in which requests are made, how to represent states (loading, success, error) and how to respond to errors. LLMs however do not compile code."

React app có thứ tự do dev viết tay. Agent phải tự suy ra thứ tự, tự giữ state, tự xử lý lỗi — và suy luận lại từ đầu mỗi lần chạy. Ba hệ quả cụ thể:

Vấn đềBiểu hiệnHậu quả thực tế
Token usageMọi tool schema nằm trong system promptNgốn context trước khi user gõ chữ
Process deviationAgent tự nối 4-5 requestKẹt retry, không rollback được
Parameter inferenceAgent gặp tham số lạBịa giá trị trông hợp lệ

Vấn đề 1: schema ăn context trước khi bắt đầu

Con số trong bài rất đáng để tính lại cho server của bạn: một REST endpoint — tính cả child object, query field và enum — "use between 150 and 300 tokens". Nhân lên, tác giả viết: "If there are 40 or more endpoints then prior to even beginning a user's input, the prompt has already used 8,000-12,000 tokens."

Tốn token mới là nửa vấn đề. Nửa còn lại là độ chính xác khi chọn tool. Khi context đầy các schema gần giống nhau, "being presented with tools such as users_update, users_patch and memberships_update causes a model to waste effort analysing the slight variations between these schemas."

Vấn đề 2: agent trượt giữa quy trình nhiều bước

Ví dụ trong bài là onboarding một thành viên: "locating the correct workspace ID, creating a user, identifying the relevant role ID and associating the user with the role. Finally an invitation email must be dispatched."

Năm bước, bốn đến năm request. Mỗi vòng request-response vừa thêm latency vừa thêm một cơ hội để model quên kết quả trước đó. Kịch bản hỏng bạn sẽ gặp trong production:

"Should stage three (email dispatch) fail due to, for instance, an email domain being blacklisted and an API therefore returning a 422 error, a model is seldom aware of how to reverse stage two."

Model sẽ loop retry bước đó, hoặc bỏ ngang. Để lại trong DB: một user tồn tại nhưng không có phân quyền workspace. Không exception, không alert — chỉ là dữ liệu bẩn bạn phát hiện ba tuần sau.

Vấn đề 3: tham số agent không hiểu thì nó bịa

REST API thường yêu cầu giá trị mà frontend che hết khỏi người dùng: "UUIDs, page 'pointers', and boolean values including include_archived and dry_run which are generally reserved for administrative interfaces."

Agent không có chỗ tra những giá trị đó, nên nó suy đoán. Hai kiểu hỏng dễ nhận ra khi đọc log: model "may incorrectly apply 0-indexing to an API expecting 1-indexing or fabricate a realistic seeming UUID".

UUID bịa trông y hệt UUID thật. Nó chỉ lộ khi API trả 404 — hoặc tệ hơn, khi vô tình trỏ đúng một record khác.

Cách sửa: expose quy trình, đừng expose bảng

Hướng xử lý trong bài gọn một câu: "avoid exposing database entities and instead expose business processes. Merge pertinent low-level tools into a higher level tool that reflects the true user goal."

Đây là shape mà bài viết gắn nhãn "Bad" — ba tool CRUD rời rạc cho một mục tiêu duy nhất:

// Bad: Exposing individual REST endpoints as MCP tools
[
  { "name": "users_create",       "inputSchema": { "properties": { "email": {}, "org_id": {} } } },
  { "name": "roles_list",         "inputSchema": { "properties": { "org_id": {}, "page": {} } } },
  { "name": "memberships_attach", "inputSchema": { "properties": { "user_id": {}, "role_id": {} } } }
]

Thay vì để agent tự ráp ba tool đó, gộp thành một tool phản ánh mục tiêu nghiệp vụ — ví dụ minh hoạ: onboard_team_member nhận email và tên role, còn tra workspace ID, tra role ID, attach membership và rollback khi gửi mail lỗi đều nằm trong code server, nơi bạn test được bằng unit test. Lợi ích kép: schema ngắn hơn hẳn, và thứ tự các bước do code quyết định chứ không do suy luận của model.

Đừng quên phần auth

Tool design gọn rồi thì đến lượt token. Michael Maurice mô tả một drill đáng mượn: "I hand it eight access tokens it should refuse, and I count how many it accepts."

Kết quả tác giả báo cáo trên server support-desk của mình — số liệu cá nhân, không phải benchmark độc lập: "A plain signature check accepted 5 of the 8. All five were signed by our real identity provider, because one identity provider signs tokens for every app in the company."

Baseline anh test ngược lại là cấu hình .NET quen thuộc trong mọi quick-start — chỉ verify chữ ký:

// The baseline I tested against: signature only
var signatureOnly = new TokenValidationParameters {
    IssuerSigningKey = signingKey,
    ValidateAudience = false,
    ValidateIssuer   = false,
    ValidateLifetime = false,
};

Nếu MCP server của bạn đang chạy đúng ba dòng false đó, thì bất kỳ token nào do IdP công ty ký — kể cả token của app khác — đều đi qua được.

Làm gì tuần này

  • Đếm số tool server bạn đang expose, nhân với khoảng 150-300 token mỗi schema, đối chiếu ngân sách context.
  • Chọn một quy trình nhiều bước thật (onboarding, tạo đơn, cấp quyền), gộp thành một tool duy nhất, kèm rollback trong code.
  • Xoá các tool CRUD trùng vai, nhất là cặp *_update / *_patch mà model hay nhầm.
  • Mở lại TokenValidationParameters, bật ValidateAudience, ValidateIssuer, ValidateLifetime.

Thứ cần theo dõi tiếp: khi số MCP server trong một team tăng lên, ngân sách context dành cho schema sẽ cạnh tranh trực tiếp với phần dành cho code. Server nào không gộp tool sẽ bị gỡ ra đầu tiên.

Không spam, hủy đăng ký bất kỳ lúc nào.

Bài viết liên quan