Mastra 实战:测试 Hacker News MCP 集成,让 Agent 掌握实时科技资讯
【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra
导读
本文聚焦 Mastra 课程《Agent Tools & MCP》中的一环——测试 Hacker News MCP 集成。当你为 Mastra Agent 配置好 Hacker News MCP 服务器后,如何通过 Playground 验证 Agent 能正确识别、调用 Hacker News 工具并返回真实数据,是本节要解决的核心问题。读完本文,你将掌握 Hacker News MCP 的完整接入链路(NPX 本地拉起 → 工具发现 → Agent 挂载 → Playground 验证)、首次调用的冷启动延迟原理,以及常见故障的排查方法,并了解 Mastra 底层 stdio 传输的实现细节。
回顾:Hacker News MCP 的接入链路
在进入测试环节之前,先快速回顾这一系列课程已经建立的完整链路。它由四个环节组成,本文的"测试"正是对这条链路的最终验收。
1. 配置 MCP 服务器(NPX 本地运行)
与 Zapier、GitHub 这类通过 URL 连接远程服务的 MCP 服务器不同,Hacker News MCP 服务器通过NPX 在本地直接运行,无需注册外部服务、无需 API Key。配置位于src/mastra/agents/index.ts:
import { MCPClient } from '@mastra/mcp' const mcp = new MCPClient({ servers: { zapier: { url: new URL(process.env.ZAPIER_MCP_URL || ''), requestInit: { headers: { Authorization: `Bearer ${process.env.ZAPIER_MCP_API_KEY}`, }, }, }, github: { url: new URL('https://api.githubcopilot.com/mcp/'), requestInit: { headers: { Authorization: `Bearer ${process.env.GITHUB_PERSONAL_ACCESS_TOKEN}`, }, }, }, hackernews: { command: 'npx', args: ['-y', '@devabdultech/hn-mcp-server'], }, }, })从 Mastra 源码可以看到,hackernews这种写法对应的是stdio(子进程)传输类型:packages/mcp/src/client/types.ts 中定义的StdioServerDefinition包含command(要执行的命令,如npx)、args(传给命令的参数数组)、env(子进程环境变量)等字段。-y标志会自动确认 npm 安装过程中的任何提示,让首次拉取更加顺滑。
2. 初始化并发现工具
配置完成后,需要异步拉取所有已配置服务器暴露的工具:
const mcpTools = await mcp.listTools()listTools()会连接配置中的每个服务器、检索其可用工具,并返回 Mastra Agent 可直接使用的格式。当你后续再向servers中追加新的 MCP 服务器时,mcpTools会自动把新工具一并纳入,无需改动这行代码。
3. 挂载到 Agent 并更新指令
将工具展开进 Agent 的tools属性,同时更新instructions,让 Agent 明白"什么时候该用、怎么用"这些工具:
export const personalAssistantAgent = new Agent({ name: 'Personal Assistant', instructions: ` You are a helpful personal assistant that can help with various tasks such as email, monitoring github activity, scheduling social media posts, and providing tech news. You have access to the following tools: 1. Gmail: - Use these tools for reading and categorizing emails from Gmail - You can categorize emails by priority, identify action items, and summarize content - You can also use this tool to send emails 2. GitHub: - Use these tools for monitoring and summarizing GitHub activity - You can summarize recent commits, pull requests, issues, and development patterns 3. Hackernews: - Use this tool to search for stories on Hackernews - You can use it to get the top stories or specific stories - You can use it to retrieve comments for stories Keep your responses concise and friendly. `, model: 'openai/gpt-5.4', tools: { ...mcpTools }, memory, })指令中明确写出 Hacker News 工具的三种能力——搜索故事、获取热门故事、读取评论,这是后面测试时判断 Agent 行为是否符合预期的基准。
正式测试:在 Playground 中验收集成
这是本课的核心环节。整个测试流程分为三步:
- 确保开发服务器正在运行:执行
npm run dev - 打开 Playground:浏览器访问 http://localhost:4111/
- 向 Agent 提问 Hacker News 相关问题,例如:
- "What are the top stories on Hacker News today?"(今天 Hacker News 的热门故事有哪些)
- "Find Hacker News discussions about AI agents"(查找关于 AI Agent 的 Hacker News 讨论)
- "Summarize the comments on the top story"(总结头条故事的评论)
- "What's trending in tech on Hacker News?"(Hacker News 上科技领域在流行什么)
建议从第一句开始按顺序测试,它最能直观反映工具链路的完整性:Agent 需要先调用工具拉取"热门故事"列表,这涉及一次完整的 MCP 工具调用往返。
首次提问的冷启动延迟:为什么第一次会慢
课程文档特别提示了一个预期内的现象:第一次提出 Hacker News 相关问题时,可能会有轻微延迟,因为 NPX 命令需要先安装并启动服务器;后续查询会明显变快。
这个现象与 Mastra 的底层实现完全吻合。在 packages/mcp/src/client/client.ts 中,MCPClient 通过StdioClientTransport以子进程方式拉起 MCP 服务器,再执行connect握手:
private async connectStdio(command: string) { this.log('debug', `Using Stdio transport for command: ${command}`); try { this.transport = new StdioClientTransport({ command, args: this.serverConfig.args, env: this.buildStdioEnv(), stderr: this.serverConfig.stderr, cwd: this.serverConfig.cwd, }); await this.client.connect(this.transport, { timeout: this.serverConfig.timeout ?? this.timeout }); ... } }也就是说,第一次提问时npx -y @devabdultech/hn-mcp-server需要经历:解析并下载 npm 包(若本地无缓存)→ 启动 Node 子进程 → 完成 MCP 协议握手 → 才能响应工具调用。这一整段冷启动路径都发生在用户的第一次请求中。之后 NPX 已缓存该包、子进程也可复用,延迟自然大幅下降。测试时请给首次请求留出耐心。
如何判断测试是否通过
观察 Agent 的行为是否符合预期:
- 工具识别:当用户提到 "Hacker News"、科技新闻、热门故事、具体话题时,Agent 应能识别出需要调用 Hacker News 工具,而不是凭自身训练知识直接作答或报"无法访问"。
- 真实 API 调用:Agent 应通过 MCP 工具触发对 Hacker News 的数据检索(对应其"检索热门故事、搜索故事、读取评论"三类能力),而不是编造新闻内容。
- 结果可用性:返回的故事标题、讨论话题、评论摘要应与 Hacker News 实际内容一致。
测试的意义在于确认整条链路闭环:NPX 本地服务器可正常拉起 →listTools()成功发现工具 → 工具已挂载进 Agent → Agent 能自主选择正确工具并完成 API 调用。
工具是否加载成功?去 Playground 的 Tools 标签确认
如果 Agent 始终不使用 Hacker News 工具,最快的定位方式是检查 Playground 的 Tools 标签页:它直接列出当前 Agent 已挂载的所有工具。若列表中没有 Hacker News 相关工具,说明问题出在更早的环节(配置、工具发现或 Agent 挂载),而不是模型推理层面。
结合 packages/mcp/src/client/configuration.ts 的源码,MCPClient还支持一些值得了解的选项:
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
id | string | 自动生成 | 唯一标识,用于防止相同配置的多个实例造成内存泄漏 |
servers | Record<string, MastraMCPServerDefinition> | 必填 | 服务器名到连接配置的映射 |
timeout | number | 60000(60 秒) | 所有服务器的全局连接超时(毫秒) |
在StdioServerDefinition中(packages/mcp/src/client/types.ts),除了command/args之外,还可以配置:
env:传给子进程的自定义环境变量;inheritDefaultEnv:是否继承 MCP SDK 的默认环境(默认true;该默认环境只继承白名单变量,POSIX 下为HOME、LOGNAME、PATH、SHELL、TERM、USER,Windows 下另有对应白名单,并非完整的process.env);cwd:子进程工作目录;stderr:stderr 处理方式。
这些字段对排查"子进程环境不完整导致 NPX 无法运行"这类问题很有帮助。
故障排查:测试不通过怎么办
课程文档给出的排查清单按可能性从高到低排列:
- NPX 是否已安装且工作正常——这是本地运行型 MCP 服务器的基础前提;
- 网络是否允许 NPX 下载并运行包——首次运行必须从 npm 拉取
@devabdultech/hn-mcp-server; - 通过 Playground 的 Tools 标签确认工具是否已正确加载——验证链路前段是否通畅。
常见问题集中在三类:
- NPX 未安装或配置不当;
- 网络受限导致 NPX 无法下载包;
- 防火墙或代理设置阻断了 Hacker News API 的访问。
最有效的定位手段是在终端手动运行一次这条命令:
npx -y @devabdultech/hn-mcp-server如果手动运行就能正常启动(表现为服务器进程保持运行、等待 MCP 握手),说明 NPX 与包本身没有问题,故障点在 Mastra 侧的配置或环境传递;如果手动运行即报错,则问题出在 NPX 安装、网络或包源上。这种"先手动、再归因"的方法能快速切开问题面。
小结
测试 Hacker News 集成是验证 Mastra Agent 外部工具能力的标准动作:通过npm run dev启动开发服务器、在 http://localhost:4111/ 的 Playground 中提出与 Hacker News 相关的真实问题,观察 Agent 是否自主识别并调用 Hacker News 工具。首次提问的短暂延迟来自 NPX 的冷启动(下载并启动服务器),属预期行为;测试不通过时,从 NPX 可用性、网络连通性、Playground Tools 标签三处依次排查,必要时手动运行npx -y @devabdultech/hn-mcp-server定位故障源头。完成本课验证后,你的 Agent 就具备了获取实时科技资讯与社区讨论的能力,下一步可以为它继续接入 Filesystem MCP,使其获得读写本地文件的能力。
相关文档与源码延伸阅读:
- 本节课程起点:MCP 是什么(课程)
- Hacker News MCP 服务器介绍(课程):docs/src/course/02-agent-tools-mcp/19-what-is-hackernews-mcp.md
- 配置与 Agent 指令更新(课程):docs/src/course/02-agent-tools-mcp/20-updating-mcp-config-hackernews.md、docs/src/course/02-agent-tools-mcp/21-updating-agent-instructions-hackernews.md
- 故障排查(课程):docs/src/course/02-agent-tools-mcp/23-troubleshooting-hackernews.md
- MCP 客户端源码:MCPClient 配置(含 timeout 默认值)、stdio 传输连接实现、StdioServerDefinition 字段定义
【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考