Building Your First MCP Server: Exposing Internal Tools to AI Agents Safely
说明与用途
构建一个 TypeScript MCP 服务器,安全地向 AI 代理公开内部工具,使用严格的输入模式、默认只读、仅创建待处理退款请求,并记录审计日志。
问题
Expose internal order lookup and refund request tools to AI agents while ensuring safety and auditability.
结果
A functional MCP server that safely exposes internal tools, with audit logging and strict schemas, enabling AI agents to interact without risking unintended actions.
工作流
- 1. Initialize project with npm and TypeScript.
- 2. Install @modelcontextprotocol/sdk, zod, and dev dependencies.
- 3. Add "type":"module" to package.json and create src/index.ts.
- 4. Import McpServer, StdioServerTransport, zod, audit, and backend functions.
- 5. Create McpServer instance with name and version.
- 6. Register "lookup_order" tool with title, description, inputSchema (orderId regex), outputSchema (orderId, status, totalCents, itemCount), and annotations (readOnlyHint).
- 7. Implement async handler: fetch order via getOrder, audit call, return error or structured result.
- 8. Register transport (StdioServerTransport) and connect server.
- 9. Log server running message.
- 10. (Optional) Extend with refund request tool following similar pattern.
证据
Instead of writing a custom integration for every model and every client, you write one MCP server, and any MCP-capable client can discover and call its tools.
apply safety patterns from the start: strict input schemas, read-only by default, write actions that only create pending requests, and an audit log of every call.
server.registerTool("lookup_order", { title: "Look up an order", description: "Returns status, items and totals for one order. Read-only.", ...});
- 记录日期: 2026-10-18T03:41:18.800Z