
Mastra.ai MCP Agent
Pricing
Pay per event
Go to Store

Mastra.ai MCP Agent
🤖 AI agent using mastra.ai with Apify MCP Server. 🚀 Runs queries via OpenAI models, taps Apify Actors for web data, and outputs to datasets. 🛠️
0.0 (0)
Pricing
Pay per event
0
Total users
16
Monthly users
15
Runs succeeded
67%
Last modified
17 days ago
.dockerignore
# github.github
# configurations.idea.vscode
# crawlee and apify storage foldersapify_storagecrawlee_storagestorage
# installed filesnode_modules
# git folder.git
# dist folderdist
.editorconfig
root = true
[*]indent_style = spaceindent_size = 4charset = utf-8trim_trailing_whitespace = trueinsert_final_newline = trueend_of_line = lf
.eslintrc
{ "root": true, "env": { "es2022": true, // Update from es2020 "node": true }, "extends": [ "@apify/eslint-config-ts" ], "parserOptions": { "project": "./tsconfig.json", "ecmaVersion": 2022 // Match ES2022 }, "ignorePatterns": [ "node_modules", "dist", "**/*.d.ts" ], "rules": { "@typescript-eslint/no-unused-vars": ["error"], // Enforce unused vars "import/order": ["error", { "alphabetize": { "order": "asc" } }], // Sort imports "@typescript-eslint/space-before-function-paren": "off", // Disable the invalid rule "space-before-function-paren": ["error", "always"] // Use ESLint’s rule instead }}
.gitignore
# Actor local inputinput.json
# This file tells Git which files shouldn't be added to source control
.idea.vscodestorageapify_storagecrawlee_storagenode_modulesdisttsconfig.tsbuildinfo
# Added by Apify CLI.venv
.prettierrc
{ "tabWidth": 4, "singleQuote": true, "semi": true}
LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2025 Apify Technologies s.r.o.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
package.json
{ "name": "actor-mastra-mcp", "version": "0.0.1", "type": "module", "description": "Mastra AI Agent with Apify MCP Server.", "engines": { "node": ">=18.0.0" }, "dependencies": { "@ai-sdk/openai": "^1.2.5", "@mastra/core": "^0.4.4", "@mastra/mcp": "^0.3.5", "apify": "^3.3.2", "exit-hook": "^4.0.0", "mastra": "^0.2.8", "zod": "^3.24.2" }, "devDependencies": { "@apify/eslint-config-ts": "^0.3.0", "@apify/tsconfig": "^0.1.0", "@types/json-schema": "^7.0.15", "@types/node": "^22.13.10", "@typescript-eslint/eslint-plugin": "^8.26.1", "@typescript-eslint/parser": "^8.26.1", "eslint": "^8.57.1", "prettier": "^3.5.3", "tsx": "^4.19.3", "typescript": "^5.8.2" }, "scripts": { "start": "npm run start:dev", "start:prod": "node dist/main.js", "start:dev": "tsx src/main.ts", "build": "tsc", "test": "echo \"Error: oops, the Actor has no tests yet, sad!\" && exit 1", "format": "prettier --write \"src/**/*.{ts,js,json}\" && eslint ./src --ext .ts --fix", "lint": "eslint ./src --ext .ts", "lint:fix": "eslint ./src --ext .ts --fix" }, "author": "It's not you it's me", "license": "ISC"}
tsconfig.json
{ "extends": "@apify/tsconfig", "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "target": "ES2022", "outDir": "dist", "skipLibCheck": true, "strict": true, // Enable all strict options "noUnusedLocals": true, // Catch unused variables "lib": [] // Remove DOM unless needed; Node globals are sufficient }, "include": [ "./src/**/*" ]}
.actor/Dockerfile
# Specify the base Docker image. You can read more about# the available images at https://docs.apify.com/sdk/js/docs/guides/docker-images# You can also use any other image from Docker Hub.FROM apify/actor-node:22 AS builder
# Copy just package.json and package-lock.json# to speed up the build using Docker layer cache.COPY package*.json ./
# Install all dependencies. Don't audit to speed up the installation.RUN npm install --include=dev --audit=false
# Next, copy the source files using the user set# in the base image.COPY . ./
# Install all dependencies and build the project.# Don't audit to speed up the installation.RUN npm run build
# Create final imageFROM apify/actor-node:22
# Create and run as a non-root user.RUN adduser -h /home/apify -D apify
# Copy just package.json and package-lock.json# to speed up the build using Docker layer cache.COPY package*.json ./
# Install NPM packages, skip optional and development dependencies to# keep the image small. Avoid logging too much and print the dependency# tree for debuggingRUN npm --quiet set progress=false \ && npm install --omit=dev --omit=optional \ && echo "Installed NPM packages:" \ && (npm list --omit=dev --all || true) \ && echo "Node.js version:" \ && node --version \ && echo "NPM version:" \ && npm --version \ && rm -r ~/.npm
# Copy built JS files from builder imageCOPY /usr/src/app/dist ./dist
# Next, copy the remaining files and directories with the source code.# Since we do this after NPM install, quick build will be really fast# for most source file changes.COPY . ./
USER apify
# Run the image.CMD npm run start:prod --silent
.actor/actor.json
{ "actorSpecification": 1, "name": "actor-mastra-mcp-agent", "title": "Mastra MCP agent", "description": "Mastra MCP agent", "version": "0.0", "buildTag": "latest", "storages": { "dataset": "./dataset_schema.json" }, "meta": { "templateId": "ts-mastraai" }, "input": "./input_schema.json", "dockerfile": "./Dockerfile"}
.actor/dataset_schema.json
{ "actorSpecification": 1, "views": { "overview": { "title": "Overview", "transformation": { "fields": ["prompt", "response"] }, "display": { "component": "table", "properties": { "prompt": { "label": "Prompt", "format": "text" }, "response": { "label": "Response", "format": "text" } } } } }}
.actor/input_schema.json
{ "title": "Mastra Agent TypeScript", "type": "object", "schemaVersion": 1, "properties": { "prompt": { "title": "Prompt", "type": "string", "description": "Prompt for the agent.", "editor": "textfield", "prefill": "Analyze the posts of the @openai and @googledeepmind and summarize me current trends in the AI." }, "agentName": { "title": "Agent name", "type": "string", "description": "Name of the agent.", "editor": "textfield", "default": "Helpful Assistant Agent" }, "agentInstructions": { "title": "Agent instructions", "type": "string", "description": "Instructions for the agent. Defines who the agent is and what it does.", "editor": "textarea", "default": "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": { "title": "OpenAI model", "type": "string", "description": "The OpenAI model to use. Currently supported models are gpt-4o and gpt-4o-mini.", "enum": [ "gpt-4o", "gpt-4o-mini" ], "default": "gpt-4o-mini", "prefill": "gpt-4o-mini" }, "mcpUrl": { "title": "MCP Server URL", "type": "string", "description": "The URL of the MCP Server to use.", "editor": "textfield", "default": "https://actors-mcp-server.apify.actor", "prefill": "https://actors-mcp-server.apify.actor" }, "actors": { "title": "Actors included", "type": "array", "editor": "stringList", "description": "List of Apify Actor names to be available to the agent.", "prefill": [ "clockworks/free-tiktok-scraper" ], "default": [] }, "toolTimeout": { "title": "MCP tool call timeout (s)", "type": "integer", "description": "Maximum time in seconds to wait for a tool call to complete.", "default": 300 }, "maxSteps": { "title": "Maximum steps for tool calls", "type": "integer", "description": "Controls the maximum number of sequential LLM calls an agent can make", "default": 3 }, "debug": { "title": "Debug", "type": "boolean", "description": "If enabled, Actor provides detailed information with tool calls and reasoning.", "editor": "checkbox", "default": false } }, "required": ["prompt", "modelName", "actors"]}
.actor/pay_per_event.json
{ "actor-start": { "eventTitle": "Price for Actor start", "eventDescription": "Flat fee for starting an Actor run.", "eventPriceUsd": 0.1 }, "task-completed": { "eventTitle": "Price for completing the task", "eventDescription": "Flat fee for completing the task.", "eventPriceUsd": 0.4 }}
src/const.ts
1export const MCP_SERVER_URL_BASE = process.env.MCP_SERVER_URL_BASE || 'https://actors-mcp-server.apify.actor';
src/main.ts
1// Apify SDK - toolkit for building Apify Actors (Read more at https://docs.apify.com/sdk/js/)2import { openai } from '@ai-sdk/openai';3import { Agent } from '@mastra/core/agent';4import { Actor, log, LogLevel } from 'apify';5import { gracefulExit } from 'exit-hook';6import { createMCPClient, startMCPServer, stopMCPServer } from './mcp.js';7import { getApifyToken } from './utils.js';8
9// this is an ESM project, and as such, it requires you to specify extensions in your relative imports10// read more about this here: https://nodejs.org/docs/latest-v18.x/api/esm.html#mandatory-file-extensions11// note that we need to use `.js` even when inside TS files12// import { router } from './routes.js';13
14// Actor input schema15interface Input {16 prompt: string;17 agentName: string;18 agentInstructions: string;19 modelName: string;20 debug: boolean;21 actors: string[];22 toolTimeout: number;23 maxSteps: number;24 mcpUrl: string;25}26
27async function main (): Promise<number> {28 // The init() call configures the Actor for its environment. It's recommended to start every Actor with an init()29 await Actor.init();30
31 /**32 * Actor code33 */34
35 // Charge for Actor start36 await Actor.charge({ eventName: 'actor-start' });37
38 // Handle input39 const {40 prompt,41 agentName,42 agentInstructions,43 modelName,44 debug = false,45 mcpUrl,46 actors,47 toolTimeout,48 maxSteps,49 } = (await Actor.getInput()) as Input;50 if (!prompt) throw new Error('An agent prompt is required.');51 if (!actors || actors.length === 0) throw new Error('At least one Apify Actor name is required.');52 if (debug) log.setLevel(LogLevel.DEBUG);53
54 // Create an MCP server55 const apifyToken = getApifyToken();56 const timeoutMillis = toolTimeout * 1000;57 const mcpClient = createMCPClient(mcpUrl, apifyToken, timeoutMillis);58
59 let mcpRunId = '';60 try {61 mcpRunId = await startMCPServer(mcpUrl, apifyToken, actors);62 // Connect to MCP server63 log.info('Connecting to MCP server...');64 await mcpClient.connect();65
66 // Gracefully handle process exits67 process.on('exit', async () => {68 await mcpClient.disconnect();69 await stopMCPServer(mcpRunId);70 });71 // Fetch tools72 const tools = await mcpClient.tools();73 log.debug(`Tools: ${JSON.stringify(tools)}`);74
75 // Create the agent76 log.debug(77 `Creating agent: ${agentName} (${modelName}) with instructions: ${agentInstructions}`,78 );79 const agent = new Agent({80 name: agentName,81 instructions: agentInstructions,82 model: openai(modelName),83 tools,84 });85
86 // Enrich the query87 const enrichedPrompt = `${prompt}\n\nCurrent date and time: ${new Date().toISOString()}`;88 log.info(`Prompting the agent with the following query: ${enrichedPrompt}`);89
90 // Query the agent and get the response91 const response = await agent.generate(92 [93 {94 role: 'user',95 content: enrichedPrompt,96 },97 ],98 {99 maxSteps,100 onStepFinish: (step: string) => {101 log.info('Step completed:', { message: step.slice(0, 100) });102 },103 },104 );105
106 log.info(`Agent response: ${response.text}`);107 log.info(`Tokens used total: ${response.usage.totalTokens}`);108 log.info(`Prompt tokens used: ${response.usage.promptTokens}`);109 log.info(`Completion tokens used: ${response.usage.completionTokens}`);110
111 // Charge for the task completion112 log.info('Charging for task completion...');113 await Actor.charge({ eventName: 'task-completed' });114
115 // Push results into the dataset116 log.info('Pushing results into the dataset...');117 await Actor.pushData({118 prompt: enrichedPrompt,119 response: response.text,120 });121 } catch (error) {122 log.error(123 `Actor failed with error: ${error instanceof Error ? error.stack : error}`,124 );125
126 // Always disconnect when done127 await mcpClient.disconnect();128 if (mcpRunId) await stopMCPServer(mcpRunId);129 await Actor.fail({130 statusMessage: 'Actor failed with an error, see logs',131 exit: false,132 });133 return 1;134 }135
136 // Always disconnect when done137 await mcpClient.disconnect();138 if (mcpRunId) await stopMCPServer(mcpRunId);139
140 // Gracefully exit the Actor process. It's recommended to quit all Actors with an exit()141 // do not call process.exit() to wait for async operations to complete142 await Actor.exit({ exit: false });143 return 0;144}145
146const exitCode = await main();147gracefulExit(exitCode);
src/mcp.ts
1import { MastraMCPClient } from '@mastra/mcp';2import { ApifyClient, log } from 'apify';3import { getApifyToken } from './utils.js';4
5/**6 * Starts the MCP server with optional Actor specification7 * @param {string} mcpUrl - The MCP server URL8 * @param {string} apifyToken - The Apify API token for authentication9 * @param {string[]} [actors] - Optional array of Actor names to be included in the server10 * @returns {Promise<string>} The run ID of the MCP server11 */12export async function startMCPServer (13 mcpUrl: string,14 apifyToken: string,15 actors: string[],16): Promise<string> {17 const url = `${mcpUrl}?actors=${actors.join(',')}`;18 log.info(`Starting MCP server with url: ${url}`);19
20 const response = await fetch(url, {21 headers: {22 Authorization: `Bearer ${apifyToken}`,23 },24 });25 const json = (await response.json()) as { data: { id: string } };26 return json.data.id;27}28/**29 * Stops the running MCP server30 * @returns {Promise<void>}31 */32export async function stopMCPServer (runId: string): Promise<void> {33 log.info('Stopping MCP server...');34
35 const token = getApifyToken();36 const apifyClient = new ApifyClient({ token });37
38 const run = apifyClient.run(runId);39 if ((await run.get())?.status === 'RUNNING') await run.abort();40}41
42/**43 * Creates an MCP client instance44 * @param {string} mcpUrl - The MCP server URL45 * @param {string} apifyToken - The Apify API token for authentication46 * @param {number} [timeout=300_000] - The timeout in milliseconds for the client47 * @returns {MastraMCPClient} MCP client instance48 */49export function createMCPClient (50 mcpUrl: string,51 apifyToken: string,52 timeout: number = 300_000,53): MastraMCPClient {54 return new MastraMCPClient({55 name: 'apify-client',56 server: {57 url: new URL(`${mcpUrl}/sse`),58 requestInit: {59 headers: {60 Authorization: `Bearer ${apifyToken}`,61 },62 },63 eventSourceInit: {64 // The EventSource package augments EventSourceInit with a "fetch" parameter.65 // You can use this to set additional headers on the outgoing request.66 // Based on this example: https://github.com/modelcontextprotocol/typescript-sdk/issues/11867 async fetch (input: Request | URL | string, init?: RequestInit) {68 const headers = new Headers(init?.headers || {});69 headers.set(70 'authorization',71 `Bearer ${process.env.APIFY_TOKEN}`,72 );73 return fetch(input, { ...init, headers });74 },75 },76 },77 timeout,78 });79}
src/utils.ts
1export function getApifyToken (): string {2 if (!process.env.APIFY_TOKEN) {3 throw new Error('APIFY_TOKEN environment variable must be set');4 }5 return process.env.APIFY_TOKEN;6}
.github/workflows/deploy_actor.yml
name: Deploy Actor to Apify
on: push: branches: - main
jobs: deploy-to-apify: runs-on: ubuntu-latest
steps: - name: Checkout sources uses: actions/checkout@v4
- name: Set up Node.js uses: actions/setup-node@v4 with: node-version: 22
- name: Push to Apify uses: apify/push-actor-action@master with: token: ${{ secrets.APIFY_TOKEN }}