MCP‑Mastra--Next.js+Express+Mastra代理
](https://nodejs.org) ](https://www.npmjs.com/)     
一个端到端的示例,展示了现代Next.js前端如何与Mastra代理和工具支持的Express后端进行通信。后端为天气和上下文问答提供了简单的端点。前端演示了一个调用这些端点并呈现JSON响应的最小UI。
亮点
- 前端Next.js 15(应用路由器)、React 19、轻量级UI原语(按钮、输入)、Tailwind实用程序助手。
- 后端:Express 5,Mastra代理与自定义工具,OpenAI模型集成通过
@ai-sdk/openai. - 代理/工具:
- contextAgent 用途 contextTool 返回策划的内容。 - weatherAgent 脚手架就位;一 weatherTool 存在当前天气短截线。
建筑
该项目分为两个顶级工作区: Frontend/ (Next.js应用程序)和 Backend/ (快递+马斯特拉)。
flowchart TD
A[User] --> B[NextJS App Frontend]
B -->|POST| C[Express API Backend]
C --> D[Mastra Runtime]
D --> E[Agents]
E --> F[Tools]
F --> G[External Services]
subgraph Frontend
B
end
subgraph Backend
C --> D
D --> E
E --> F
end请求流:上下文问答(POST /api/question)
sequenceDiagram
participant U as UserUI
participant FE as Frontend
participant BE as Backend
participant M as MastraContextAgent
participant T as ContextTool
U->>FE: Enter question and submit
FE->>BE: POST /api/question { question }
BE->>M: agent.generate(question)
M->>T: execute()
Note over T: Fetch curated context content
T-->>M: { output: "...curated content..." }
M-->>BE: { text: "answer with context" }
BE-->>FE: 200 OK { question, text }
FE-->>U: Render JSON result请求流:天气(GET /api/weather?city=...)
sequenceDiagram
participant U as User
participant FE as Frontend
participant BE as Backend
participant M as MastraWeatherAgent
participant WT as WeatherTool
U->>BE: GET /api/weather?city=London
BE->>M: agent.generate("What's the weather like in London?")
Note over M: Agent uses tools to answer (scaffold)
M->>WT: execute()
Note over WT: Returns stubbed weather output
WT-->>M: { output: "The weather is sunny" }
M-->>BE: { text: "..." }
BE-->>U: 200 OK { city, text }注:在目前的脚手架中, weatherTool 返回一个静态存根和 weatherAgent 以类似的方式连接以显示集成模式。根据需要扩展它以调用真实天气API。
技术栈
- 前端:
- Next.js 15.5.4,反应 19.1.0,顺风助手(tailwind-merge, clsx), lucide-react
- 后端:
- 快速 5.1.0马斯特拉(@mastra/core), @ai-sdk/openai, zod
项目结构
/Backend
package.json
src/
index.ts # Express server: routes and agent calls
mastra/
index.ts # Mastra runtime and agent registry
agents/
context-agent.ts # contextAgent -> uses contextTool + OpenAI model
weather-agent.ts # weatherAgent -> scaffold for weather
tools/
context-tool.ts # Returns curated content (stubbed data)
weather-tool.ts # Returns stubbed weather output
tsconfig.json
/Frontend
package.json
next.config.ts
src/
app/
page.tsx # Minimal UI to POST /api/question
test/page.tsx # Starter Next.js page
components/ui/
button.tsx, input.tsx # Reusable UI primitives
lib/
config.ts # API base + endpoint builders
utils.ts # Tailwind className helper后端
关键终点
GET /→ 健康检查:“Hello World”GET /api/v1/auth/login→ 占位符路线GET /api/weather?city=London→ CallsweatherAgent.generate(...)并返回{ city, text }POST /api/question
- 主体: { "question": "..." } - 呼叫 mastra.getAgent("contextAgent").generate(question) - 退货 { question, text }
代理和工具
contextAgent
- 型号: openai("gpt-4o-mini") - 工具: contextTool 它返回经过策划的内容进行演示 - 说明强调调用上下文工具并告诉用户它被使用过
weatherAgent
- 型号: openai("gpt-4o-mini") - 工装脚手架: weatherTool (静态存根)。扩展到呼叫真实天气提供商
环境变量
OPENAI_API_KEY(必填):需要@ai-sdk/openai访问OpenAI模型。PORT(可选):默认为3001.
创建 Backend/.env (或在您的shell中导出):
OPENAI_API_KEY=sk-live-or-test-key
PORT=3001运行后端
cd Backend
npm install
npm run dev
# Server listens on http://localhost:3001测试API
# Health
curl http://localhost:3001/
# Weather (stubbed)
curl "http://localhost:3001/api/weather?city=London"
# Context Q&A
curl -X POST http://localhost:3001/api/question \
-H "Content-Type: application/json" \
-d '{"question":"What are the key ad best practices?"}'前端
主页位于 src/app/page.tsx 将输入POST到后端 /api/question 端点和漂亮打印JSON响应。
环境变量
NEXT_PUBLIC_API_BASE(可选):默认为http://localhost:3001。如果您的后端在其他地方运行,请设置此选项。
创建 Frontend/.env.local:
NEXT_PUBLIC_API_BASE=http://localhost:3001运行前端
cd Frontend
npm install
npm run dev
# App listens on http://localhost:3000打开 http://localhost:3000 在您的浏览器中。输入问题并提交;您应该看到后端的JSON响应。
扩展系统
添加新工具
- 在以下位置创建文件
Backend/src/mastra/tools/your-tool.ts使用createTool随着zod输入/输出模式。 - 通过将工具添加到代理中,将其连接到代理中
tools代理定义中的映射。 - 更新代理说明,明确何时以及如何调用工具的要求。
添加新代理
- 创建
Backend/src/mastra/agents/your-agent.ts通过new Agent({...}). - 在中注册
Backend/src/mastra/index.ts里面agents: { ... }对象。 - 在中添加Express路线(或重复使用)
Backend/src/index.ts叫mastra.getAgent("yourAgent").generate(...).
制作笔记
- 使用
npm run build && npm start这两个应用程序在生产环境中的模式(或您首选的流程管理器)。 - 在中配置CORS和身份验证
Backend/src/index.ts用于实际部署。 - 用对真实API的调用替换被截断的工具输出;确保机密得到安全管理(例如,环境管理器、KMS或平台机密)。
- 根据需要添加可观察性(结构化日志、跟踪)。
脚本
- 后端:
- npm run dev:Nodemon+ts节点用于实时重新加载 - npm run start:使用ts节点寄存器运行服务器(无需重新加载) - npm run mastra:dev:启动Mastra-dev工具(如果全局/本地安装)
- 前端:
- npm run dev:Next.js开发服务器(Turbopack) - npm run build:生产建设 - npm run start:为构建的应用程序提供服务 - npm run lint:运行ESLint
