> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 发布 MCP server 本示例将指导你使用 stdio 传输方式设置一个基本的 Mastra MCPServer、构建它,并为发布到 NPM 做好准备。 ## 安装依赖项 安装所需软件包: **npm**: ```bash npm install @mastra/mcp @mastra/core tsup ``` **pnpm**: ```bash pnpm add @mastra/mcp @mastra/core tsup ``` **Yarn**: ```bash yarn add @mastra/mcp @mastra/core tsup ``` **Bun**: ```bash bun add @mastra/mcp @mastra/core tsup ``` ## 设置 MCP server 1. 为 stdio server 创建一个文件,例如 `src/mastra/stdio.ts`。 2. 将以下代码添加到文件中。请记得导入你实际使用的 Mastra Tool,并为 server 指定合适的名称。 ```typescript #!/usr/bin/env node import { MCPServer } from '@mastra/mcp' import { weatherTool } from './tools' const server = new MCPServer({ name: 'my-mcp-server', version: '1.0.0', tools: { weatherTool }, }) server.startStdio().catch(error => { console.error('Error running MCP server:', error) process.exit(1) }) ``` 3. 更新 `package.json`,添加指向已构建 server 文件的 `bin` 条目,以及用于同时构建 ESM 和 CJS 输出的脚本。 ```json { "bin": "dist/stdio.mjs", "scripts": { "build:mcp": "tsup src/mastra/stdio.ts --format esm,cjs --no-splitting --dts && echo '#!/usr/bin/env node' | cat - dist/stdio.mjs > temp && mv temp dist/stdio.mjs && chmod +x dist/stdio.mjs" } } ``` 该构建命令会同时生成 ESM(`.mjs`)和 CJS(`.cjs`)输出,以提供最大的兼容性。它会在 ESM 构建产物前添加 shebang(`#!/usr/bin/env node`),使其可以直接执行,而 `bin` 条目则指向此文件。 4. 运行构建命令: **npm**: ```bash npm run build:mcp ``` **pnpm**: ```bash pnpm run build:mcp ``` **Yarn**: ```bash yarn build:mcp ``` **Bun**: ```bash bun run build:mcp ``` 该命令会把 server 代码编译为 ESM 和 CJS 两种格式,并让 ESM 输出文件可执行。在类 Unix 系统中,`chmod +x` 步骤会让该文件可以直接执行。Windows 用户可能需要使用 WSL,或直接通过 Node.js 执行它。 ## 发布到 NPM 要让其他人(或你自己)能够通过 `npx` 使用 MCP server,或把它用作依赖项,你可以将其发布到 NPM。 1. 确保你拥有 NPM 账户且已登录(`npm login`)。 2. 确保 `package.json` 中的软件包名称唯一且尚未被占用。 3. 构建完成后,在项目根目录运行发布命令: ```bash npm publish --access public ``` 有关发布软件包的更多详情,请参阅 [NPM 文档](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages)。 ## 使用已发布的 MCP server 发布后,可以通过指定运行软件包的命令,让 `MCPClient` 使用你的 MCP server。你也可以使用 Claude desktop、Cursor 或 Windsurf 等其他 MCP client。 ```typescript import { MCPClient } from '@mastra/mcp' const mcp = new MCPClient({ servers: { // Give this MCP server instance a name yourServerName: { command: 'npx', args: ['-y', '@your-org-name/your-package-name@latest'], // Replace with your package name }, }, }) // You can then get tools or toolsets from this configuration to use in your agent const tools = await mcp.listTools() const toolsets = await mcp.listToolsets() ``` 注意:如果发布时没有使用组织 scope,`args` 可能是 `["-y", "your-package-name@latest"]`。