文档AI / Agent

用 Deno 构建 MCP Server

使用官方 TypeScript SDK、Zod 和 stdio 暴露经过校验的 MCP tool

MCP Server 把工具、资源与 prompt 通过协议暴露给 AI 客户端。Deno 很适合运行本地 stdio server:单文件 TypeScript、明确权限、无需单独编译。

deno add npm:@modelcontextprotocol/sdk npm:zod
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({ name: "project-info", version: "1.0.0" });

server.registerTool(
  "read_project_note",
  {
    description: "Read one approved note by its short name",
    inputSchema: { name: z.string().regex(/^[a-z0-9-]+$/) },
  },
  async ({ name }) => ({
    content: [{
      type: "text",
      text: await Deno.readTextFile(`./notes/${name}.md`),
    }],
  }),
);

await server.connect(new StdioServerTransport());

客户端配置只授予 notes 目录读取权限:

{
  "mcpServers": {
    "project-info": {
      "command": "deno",
      "args": ["run", "--allow-read=./notes", "mcp_server.ts"]
    }
  }
}

远程 server 优先使用 Streamable HTTP;旧 HTTP+SSE transport 只用于兼容。公开部署时还要实现认证、Origin/DNS rebinding 防护、速率限制与每次调用的授权判断。

官方参考:Deno MCP server exampleMCP TypeScript SDK serverModel Context Protocol

输入关键词搜索全部文档。