What Is Mastra?
Mastra is an open-source TypeScript framework for building AI agents and workflows. It gives developers everything needed to ship production-grade AI features: a model router with 3,000+ models, agents with memory and tool use, multi-step workflows with branching logic, RAG pipelines, evals, and observability, all in one framework. It integrates with Next.js, React, Express, SvelteKit, Hono, and any other modern TypeScript stack. Unlike no-code or desktop agent tools, Mastra agents are code. They live in your codebase, deploy with your app, and connect to your existing infrastructure.Why Connect ZenRows to Mastra?
- Ship agents that access any site: Mastra agents call tools to do their work. Without ZenRows, any page protected by Cloudflare, DataDome, or similar systems returns a blocked or empty response. Add ZenRows and your agents bypass the blocks to fetch the actual content every time.
- Structured output, ready for your app: ZenRows returns clean Markdown or JSON instead of raw HTML. Mastra agents receive structured, LLM-friendly data, resulting in less post-processing, fewer tokens, and cleaner output to pass downstream.
- Give any model on Mastra’s router real-time web access: Mastra supports 3,000+ models from OpenAI, Anthropic, Google, Groq, Mistral, and more. ZenRows MCP enables real-time web access regardless of which model your agent uses.
- Multi-agent workflows with live web data: Mastra supports supervisor agents that coordinate subagents. Each subagent can call ZenRows independently, and a coordinator synthesizes the results.
- Ship web data features into your product without building a scraping layer: With ZenRows MCP, your agent calls a tool and gets structured content back. No scraping infrastructure to maintain and no browser pool to spin up alongside your app.
- Keep your RAG pipelines current: Connect ZenRows with Mastra and your RAG ingestion workflow can pull live content from any source on demand, including pages behind bot protection and heavy JavaScript rendering that a plain HTTP fetch would never reach.
What You Can Build with Mastra and ZenRows
- A competitive pricing monitor shipped inside your product: Build an agent your users can query that scrapes live pricing across sites via ZenRows and returns a structured answer. Deploy it as part of your Next.js or Express app using Mastra’s server adapters.
- An e-commerce research workflow: Chain a multi-step Mastra workflow to scrape a product category page, extract product names and prices, enrich with reviews from a second page, run a structured-output step to rank by value, and return a clean JSON response to your frontend.
- A sales intelligence agent: Build an internal copilot that researches a prospect before a call, scraping their company site, recent news, and job postings via ZenRows, and returns a structured brief via your Slack channel or internal tool.
- Content automation for a CMS: Set up a Mastra workflow that scrapes a set of sources on a schedule, extracts key content, runs it through a summarization or transformation step, and writes structured output directly to your CMS or knowledge base.
- A data analysis agent with live market data: Extend Mastra’s text-to-SQL and data analysis agent template with ZenRows to pull live market data, competitor pricing, or industry benchmarks from the web, then feed it into the analysis pipeline alongside your internal database.
Prerequisites
- Node.js 18+ installed.
- A Mastra project scaffolded via
npm create mastra@latest, which creates the full project structure (src/mastra/agents,tools,workflows,index.ts) that you’ll build on top of. - An Anthropic API key (or your preferred provider).
- A ZenRows API key from the ZenRows Playground.
.env file as ANTHROPIC_API_KEY.
Setup
Install the required packages
@mastra/mcp and the Anthropic AI SDK provider:@mastra/mcp enables MCP client support in your Mastra project. @ai-sdk/anthropic is the Anthropic provider for the AI SDK, enabling your agent to connect directly to Claude without going through Mastra’s model router.Configure ZenRows as an MCP server
MCPClient that points to the ZenRows MCP server.Create src/mastra/mcp/zenrows-client.ts:.env file. ANTHROPIC_API_KEY should already be there from the project setup wizard. Add ZENROWS_API_KEY alongside it:Add ZenRows tools to your agent
listTools().Create src/mastra/agents/research-agent.ts:listTools() loads all ZenRows tools into the agent. If you only need a subset of tools, load them first and filter to keep the prompt lighter:src/mastra/index.ts already exists from the project scaffold. Add researchAgent to the imports and include it in the agents object:Run your agent
http://localhost:4111/swagger-ui in your browser to see all your registered agents as callable API endpoints.Go to http://localhost:4111/agents, select research-agent, and you’ll see all available ZenRows MCP tools connected to your agent in the right sidebar.Fill in a scraping prompt and send it:MCPClient, not an MCPServer. MCPClient connects your Mastra agent to an external MCP server (in this case, ZenRows) to consume its tools. MCPServer does the opposite: it exposes your Mastra agents and tools to other MCP-compatible clients. Use MCPClient here because you want Mastra to consume ZenRows tools, not the other way around.src/scripts/test-agent.ts:registerApiRoute is a helper from @mastra/core/server that lets you define custom HTTP routes on Mastra’s built-in server.Update src/mastra/index.ts:Dynamic Tools for Multi-Tenant Apps
If you’re building a SaaS app where each user provides their own ZenRows API key, uselistToolsets() instead of listTools(). This lets you pass per-request credentials without reinitializing the agent.
In this pattern, zenrows-client.ts is not used. Instead, a new MCPClient is created per request using the user’s API key and discarded after the response is received. This logic lives in your request handler inside a registerApiRoute handler in index.ts.
Add the import at the top of index.ts:
server.apiRoutes:
ZENROWS_API_KEY doesn’t need to be set in your .env. Each request supplies its own key at runtime, so there is no shared key on the server.Troubleshooting
This Site Can’t Be Reached or localhost:4111 Unreachable
The Mastra dev server isn’t running. Start it with:500 Internal Server Error on Custom Routes
Check that you’re usingmastra.getAgentById('research-agent') and not mastra.getAgent('research-agent') in your route handlers. The correct method is getAgentById. Using getAgent will cause a 500 with no clear error message in the response.
Could Not Find Config for Provider Anthropic Error
This occurs when using Mastra’s model router string format (anthropic/claude-sonnet-4-6) without Mastra’s gateway configured. You may also see a follow-up error such as "model: anthropic/claude-sonnet-4-6 not found" if the router tries to pass the full string directly to the Anthropic API.
The fix is to use Anthropic’s AI SDK provider directly instead of the router string:
@ai-sdk/openai for OpenAI and @ai-sdk/google for Google. See the AI SDK providers docs for the full list.
When using the AI SDK directly, pass only the model ID without the anthropic/ prefix:
Prompt Is Too Long Error
Mastra injects all registered tool schemas into the prompt on every request. When combined with page content returned by ZenRows, this can push the total token count past the model’s context limit. Option 1: Load tools first and select only the ones you need, such aszenrows_scrape:
model field in research-agent.ts:
Cannot Find Name ‘process’ or Relative Import Path Errors
Add"types": ["node"] to your tsconfig.json compiler options:
ZenRows Tools Not Appearing on the Agent
- Confirm
@mastra/mcpis installed:npm list @mastra/mcp. - Check that
ZENROWS_API_KEYis set in your.envand that dotenv is loading it. - When running scripts directly with
npx tsx, addimport 'dotenv/config'at the top of the file. The dev server loads.envautomatically, but standalone scripts don’t. - Make sure
await zenrowsClient.listTools()is called at the module level inresearch-agent.ts, outside theAgentconstructor. Theawaitis required and must be at the top level of the file.
Authentication Error from ZenRows
Verify your API key on the ZenRows dashboard. If using the HTTP connection option, ensure theAuthorization header is set to Bearer YOUR_ZENROWS_API_KEY with no extra whitespace.
Workflow Step Not Receiving ZenRows Output
Check theoutputSchema of your scrape step matches what the next step expects. Use Mastra Studio at http://localhost:4111 to inspect step inputs and outputs visually.
Further Reading
- Mastra MCP Overview
- Mastra Agents
- Mastra Workflows
- MCPClient Reference
- Dynamic Tools for Multi-Tenant Apps
- ZenRows MCP Documentation
Frequently Asked Questions
Does ZenRows work with all models on Mastra's model router?
Does ZenRows work with all models on Mastra's model router?
Can each user in my app use their own ZenRows API key?
Can each user in my app use their own ZenRows API key?
listToolsets() instead of listTools() and create a new MCPClient per request with the user’s key. In this case, you don’t need to set ZENROWS_API_KEY in your .env. Each request is self-contained. See the Dynamic Tools for Multi-Tenant Apps section for the full implementation.Should I use listTools() or listToolsets()?
Should I use listTools() or listToolsets()?
listTools() for single-user or internal tools where the API key is shared. Use listToolsets() for multi-tenant SaaS apps where each user provides their own credentials, avoiding the need to reinitialize the agent per request.Can I require human approval before ZenRows runs?
Can I require human approval before ZenRows runs?
requireToolApproval: true on the ZenRows server block in your MCPClient config:Can I use ZenRows alongside other MCP servers in the same agent?
Can I use ZenRows alongside other MCP servers in the same agent?
MCPClient:listTools() call.Can I test my ZenRows agent in Mastra Studio?
Can I test my ZenRows agent in Mastra Studio?
http://localhost:4111) lets you run your agent interactively, inspect every tool call including ZenRows requests and responses, view token usage, and debug step by step without writing test scripts. See the Mastra Agent Studio overview for more information.