# Mastra.ai MCP Agent (`jakub.kopecky/actor-mastra-mcp-agent`) Actor

🤖 AI agent using mastra.ai with Apify MCP Server. 🚀 Runs queries via OpenAI models, taps Apify Actors for web data, and outputs to datasets. 🛠️

- **URL**: https://apify.com/jakub.kopecky/actor-mastra-mcp-agent.md
- **Developed by:** [Jakub Kopecký](https://apify.com/jakub.kopecky) (community)
- **Categories:** AI, Agents, Open source
- **Security:** Full permissions
- **Stats:** 62 total users, 0 monthly users, 0.0% runs succeeded, 3 bookmarks
- **User rating**: No ratings yet

## Pricing

from $400.00 / 1,000 price for completing the tasks

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Mastra AI Agent with Apify MCP Server

[![Mastra AI Agent](https://apify.com/actor-badge?actor=jakub.kopecky/actor-mastra-mcp-agent)](https://apify.com/jakub.kopecky/actor-mastra-mcp-agent)
[![GitHub Repo stars](https://img.shields.io/github/stars/apify/actor-mastra-mcp-agent)](https://github.com/apify/actor-mastra-mcp-agent/stargazers)

The **Mastra AI Agent with Apify MCP Server** is a generic AI agent designed to demonstrate the power of the [mastra.ai](https://mastra.ai/) framework when paired with the [Apify MCP Server](https://apify.com/apify/actors-mcp-server). This Actor leverages the Model Context Protocol (MCP) to connect AI-driven workflows with Apify’s extensive library of Actors, enabling seamless data extraction, web scraping, and task automation.

Built with TypeScript and the Apify SDK, this Actor serves as a flexible starting point for developers looking to create custom AI agents that tap into real-time web data and tools.

### 🛠️ Use cases

#### TikTok trend analysis

Scrape TikTok posts from a specific account and summarize key trends.

**Example input**:

```json
{
  "prompt": "Scrape the latest 10 posts from @techcrunch on TikTok and summarize key tech topics.",
  "agentName": "TikTok Tech Analyzer",
  "agentInstructions": "You are a tech analyst scraping TikTok posts to identify trends.",
  "modelName": "gpt-4o-mini",
  "actors": ["clockworks/free-tiktok-scraper"]
}
```

**Example output**:

```json
{
  "prompt": "Scrape the latest 10 posts from @techcrunch on TikTok and summarize key tech topics.",
  "response": "Here are the latest 10 posts from TechCrunch on TikTok, along with key tech topics summarized..."
}
```

#### Web research synthesis

Search the web for a topic and distill top findings.

**Example input**:

```json
{
  "prompt": "Search the web for recent advances in quantum computing and explain the top 3 breakthroughs.",
  "agentName": "Quantum Research Bot",
  "agentInstructions": "You are a research assistant that scours the web for technical info.",
  "modelName": "gpt-4o",
  "actors": ["apify/rag-web-browser"]
}
```

**Example output**:

```json
{
  "prompt": "Search the web for recent advances in quantum computing and explain the top 3 breakthroughs.",
  "response": "Here are the top three recent advances in quantum computing as of 2025..."
}
```

#### Your use case 💡

Tweak the input and create your own AI agent to tackle your use case! 🚀

### 🎯 Features

- 🤖 **AI-powered assistance**: Uses the [mastra.ai](https://mastra.ai/) framework to process prompts with OpenAI models (e.g., `gpt-4o`, `gpt-4o-mini`).
- 🌐 **Apify MCP integration**: Connects to the Apify MCP Server to access tools like `clockworks/free-tiktok-scraper` and more.
- 💰 **Pay-per-event pricing**: Flexible, usage-based billing for Actor runs and task completions.

### 🔄 How it works

1. 📥 **Input**
   - Prompt (e.g., "Analyze posts from @openai and summarize AI trends")
   - Agent name (e.g., "Helpful Assistant Agent") - name for the agent
   - Agent instructions (e.g., "You are a helpful assistant...") - description of the agent's role, who the agent is and what it does
   - Model selection (`gpt-4o` or `gpt-4o-mini`)
   - Actors (e.g., `["clockworks/free-tiktok-scraper"]`) - list of Apify Actors to be served by the MCP server for the agent

2. 🤖 **Processing with Mastra**
   - Initializes the agent using the mastra.ai framework.
   - Connects to the Apify MCP Server via Server-Sent Events (SSE).
   - Fetches available tools (e.g., TikTok scrapers, web browsers) dynamically.
   - Executes the prompt, leveraging MCP tools as needed.

3. 📤 **Output**
   - Returns the agent’s response as text.
   - Stores results in an Apify dataset with the prompt and response.

#### 💰 Pricing

This Actor uses the [Pay Per Event](https://docs.apify.com/platform/actors/publishing/monetize#pay-per-event-pricing-model) (PPE) model for cost-effective, usage-based pricing.

| Event                  | Price (USD) |
|------------------------|-------------|
| Actor start            | $0.10       |
| Task completion        | $0.40       |

#### Input example

```json
{
  "prompt": "Analyze the posts of @openai and summarize current trends in AI.",
  "agentName": "Social Media Analyst",
  "agentInstructions": "You are a social media analyst who specializes in analyzing posts from various social media platforms.",
  "modelName": "gpt-4o-mini",
  "actors": ["clockworks/free-tiktok-scraper"]
}
```

#### Output example

Dataset entry:

```json
{
  "prompt": "Analyze the posts of @openai and summarize current trends in AI.",
  "response": "Here’s a summary of the recent posts from OpenAI's account, highlighting current trends in AI..."
}
```

### 🔧 Technical highlights

- **Mastra.ai framework**: Powers the AI agent.
- **Apify MCP Server**: Exposes Apify Actors as tools via the Model Context Protocol.
- **Apify SDK**: Ensures seamless integration with the Apify platform.
- **TypeScript**: Provides type safety and modern JavaScript features.

### 🤖 Under the hood with [mastra.ai](https://mastra.ai/)

This Actor uses the mastra.ai framework to create a generic AI agent that interacts with the Apify ecosystem:

#### 🛠️ Tools

Expandable to any Apify Actor from the [Apify Store](https://apify.com/store) via the MCP Server configuration.

### ⚙️ Usage

#### Running on Apify

1. Clone the repository.
2. Push the Actor to the Apify platform:
   ```bash
   apify push
   ```
3. Set Actor `OPENAI_API_KEY` [environment variable](https://docs.apify.com/platform/actors/development/programming-interface/environment-variables#custom-environment-variables).
4. Run the Actor with your input via the Apify Console or API.

#### Local development

1. Install dependencies:
   ```bash
   npm install
   ```
2. Run locally:
   ```bash
   OPENAI_API_KEY=<your-openai-api-key> apify run -i '{"prompt": "Show me latest post from @openai TikTok profile", "actors": ["clockworks/free-tiktok-scraper"]}'
   ```

### 📖 Learn more

- [Mastra.ai Framework](https://mastra.ai/)
- [Apify MCP Server](https://apify.com/apify/actors-mcp-server)
- [Apify Platform](https://apify.com)
- [Apify SDK Documentation](https://docs.apify.com/sdk/js)
- [What is MCP?](https://blog.apify.com/what-is-model-context-protocol/)
- [What are AI agents?](https://blog.apify.com/what-are-ai-agents/)
- [How to build an AI agent on Apify](https://blog.apify.com/how-to-build-an-ai-agent/)

### 🚀 Get started

Ready to build your own AI agent? Deploy this Actor on Apify, tweak the input, and explore the possibilities of mastra.ai and MCP! 🤖✨

### 🌐 Open source

This Actor is open-source, hosted on [GitHub](https://github.com/apify/actor-mastra-mcp-agent). Want to add features? Open an issue or submit a pull request!

# Actor input Schema

## `prompt` (type: `string`):

Prompt for the agent.

## `agentName` (type: `string`):

Name of the agent.

## `agentInstructions` (type: `string`):

Instructions for the agent. Defines who the agent is and what it does.

## `modelName` (type: `string`):

The OpenAI model to use. Currently supported models are gpt-4o and gpt-4o-mini.

## `mcpUrl` (type: `string`):

The URL of the MCP Server to use.

## `actors` (type: `array`):

List of Apify Actor names to be available to the agent.

## `toolTimeout` (type: `integer`):

Maximum time in seconds to wait for a tool call to complete.

## `maxSteps` (type: `integer`):

Controls the maximum number of sequential LLM calls an agent can make

## `debug` (type: `boolean`):

If enabled, Actor provides detailed information with tool calls and reasoning.

## Actor input object example

```json
{
  "prompt": "Analyze the posts of the @openai and @googledeepmind and summarize me current trends in the AI.",
  "agentName": "Helpful Assistant Agent",
  "agentInstructions": "You are a helpful assistant who aims to help users with their questions and tasks. You provide clear, accurate information and guidance while maintaining a friendly and professional attitude.",
  "modelName": "gpt-4o-mini",
  "mcpUrl": "https://actors-mcp-server.apify.actor",
  "actors": [
    "clockworks/free-tiktok-scraper"
  ],
  "toolTimeout": 300,
  "maxSteps": 3,
  "debug": false
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "prompt": "Analyze the posts of the @openai and @googledeepmind and summarize me current trends in the AI.",
    "modelName": "gpt-4o-mini",
    "mcpUrl": "https://actors-mcp-server.apify.actor",
    "actors": [
        "clockworks/free-tiktok-scraper"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("jakub.kopecky/actor-mastra-mcp-agent").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "prompt": "Analyze the posts of the @openai and @googledeepmind and summarize me current trends in the AI.",
    "modelName": "gpt-4o-mini",
    "mcpUrl": "https://actors-mcp-server.apify.actor",
    "actors": ["clockworks/free-tiktok-scraper"],
}

# Run the Actor and wait for it to finish
run = client.actor("jakub.kopecky/actor-mastra-mcp-agent").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "prompt": "Analyze the posts of the @openai and @googledeepmind and summarize me current trends in the AI.",
  "modelName": "gpt-4o-mini",
  "mcpUrl": "https://actors-mcp-server.apify.actor",
  "actors": [
    "clockworks/free-tiktok-scraper"
  ]
}' |
apify call jakub.kopecky/actor-mastra-mcp-agent --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,jakub.kopecky/actor-mastra-mcp-agent"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/DLbZOrYROuhU9YshC/builds/AdjVzyXODL7iWvbHG/openapi.json
