#!/usr/bin/env node
import * as fs from 'fs';
import { existsSync, mkdirSync } from 'fs';
import * as os2 from 'os';
import os2__default from 'os';
import * as path5 from 'path';
import path5__default, { dirname } from 'path';
import fs3 from 'fs/promises';
import { MCPServer } from '@mastra/mcp';
import { z } from 'zod';
import { fileURLToPath } from 'url';
import { getPackageInfo } from 'local-pkg';

var LOG_LEVEL_PRIORITY = {
  debug: 0,
  info: 1,
  warn: 2,
  error: 3,
  none: 4
  // none = disable all logs
};
function mapToLogLevel(level) {
  switch (level) {
    case "debug":
      return "debug";
    case "info":
    case "notice":
      return "info";
    case "warning":
      return "warn";
    case "error":
    case "critical":
    case "alert":
    case "emergency":
      return "error";
    default:
      return "info";
  }
}
var currentLogLevel = "debug";
function setLogLevel(level) {
  currentLogLevel = level;
}
function shouldLog(level) {
  const mappedLevel = mapToLogLevel(level);
  return LOG_LEVEL_PRIORITY[mappedLevel] >= LOG_LEVEL_PRIORITY[currentLogLevel];
}
var writeErrorLog = (message, data) => {
  const now = /* @__PURE__ */ new Date();
  const timestamp = now.toISOString();
  const hourTimestamp = timestamp.slice(0, 13);
  const logMessage = {
    timestamp,
    message,
    ...data ? typeof data === "object" ? data : { data } : {}
  };
  try {
    const cacheDir = path5.join(os2.homedir(), ".cache", "mastra", "mcp-docs-server-logs");
    fs.mkdirSync(cacheDir, { recursive: true });
    const logFile = path5.join(cacheDir, `${hourTimestamp}.log`);
    fs.appendFileSync(logFile, JSON.stringify(logMessage) + "\n", "utf8");
  } catch (err) {
    console.error("Failed to write to log file:", err);
  }
};
function createLogger(server2) {
  const sendLog = async (level, message, data) => {
    if (!server2) return;
    if (!shouldLog(level)) return;
    try {
      const sdkServer = server2.getServer();
      if (!sdkServer) return;
      await sdkServer.sendLoggingMessage({
        level,
        data: {
          message,
          ...data ? typeof data === "object" ? data : { data } : {}
        }
      });
    } catch (error) {
      if (error instanceof Error && (error.message === "Not connected" || error.message.includes("does not support logging") || error.message.includes("Connection closed"))) {
        return;
      }
      console.error(`Failed to send ${level} log:`, error instanceof Error ? error.message : error);
    }
  };
  return {
    debug: async (message, data) => {
      if (process.env.DEBUG || process.env.NODE_ENV === "development") {
        await sendLog("debug", message, data);
      }
    },
    info: async (message, data) => {
      await sendLog("info", message, data);
    },
    notice: async (message, data) => {
      await sendLog("notice", message, data);
    },
    warning: async (message, data) => {
      await sendLog("warning", message, data);
    },
    error: async (message, error) => {
      const errorData = error instanceof Error ? {
        message: error.message,
        stack: error.stack,
        name: error.name
      } : error;
      writeErrorLog(message, errorData);
      await sendLog("error", message, errorData);
    },
    critical: async (message, error) => {
      const errorData = error instanceof Error ? {
        message: error.message,
        stack: error.stack,
        name: error.name
      } : error;
      writeErrorLog(message, errorData);
      await sendLog("critical", message, errorData);
    },
    alert: async (message, error) => {
      const errorData = error instanceof Error ? {
        message: error.message,
        stack: error.stack,
        name: error.name
      } : error;
      writeErrorLog(message, errorData);
      await sendLog("alert", message, errorData);
    },
    emergency: async (message, error) => {
      const errorData = error instanceof Error ? {
        message: error.message,
        stack: error.stack,
        name: error.name
      } : error;
      writeErrorLog(message, errorData);
      await sendLog("emergency", message, errorData);
    }
  };
}
var logger = createLogger();

// src/prompts/migration.ts
var migrationPrompts = [
  {
    name: "upgrade-to-v1",
    version: "v1",
    description: "Get a guided migration plan for upgrading from Mastra v0.x to v1.0. Provides step-by-step instructions for handling all breaking changes.",
    arguments: [
      {
        name: "area",
        description: "Optional: Focus on a specific area (e.g., agent, tools, workflows, memory, storage, voice). The tool will check if a migration guide exists for this area and suggest alternatives if not found. If not provided, gives an overview of all changes.",
        required: false
      }
    ]
  },
  {
    name: "migration-checklist",
    version: "v1",
    description: "Get a comprehensive checklist for migrating to Mastra v1.0. Lists all breaking changes that need to be addressed."
  }
];
var migrationPromptMessages = {
  listPrompts: async () => migrationPrompts,
  getPromptMessages: async ({ name, args }) => {
    const prompt = migrationPrompts.find((p) => p.name === name);
    if (!prompt) {
      throw new Error(`Prompt not found: ${name}`);
    }
    if (name === "upgrade-to-v1") {
      return getUpgradeToV1Messages(args?.area);
    }
    if (name === "migration-checklist") {
      return getMigrationChecklistMessages();
    }
    throw new Error(`No message handler for prompt: ${name}`);
  }
};
function getUpgradeToV1Messages(area) {
  if (area) {
    return [
      {
        role: "user",
        content: {
          type: "text",
          text: `I need help migrating my Mastra ${area} code from v0.x to v1.0. Use the mastraMigration tool to:

1. If packages aren't already at the 'latest' tag, upgrade packages to the 'latest' tag and do an install of the new packages.
2. First, try to get the specific migration guide for "${area}" using path: "upgrade-to-v1/${area}"
3. If that doesn't exist, try the alternate form (singular/plural):
   - If "${area}" ends with 's', try without the 's' (e.g., "agents" \u2192 "agent")
   - If "${area}" doesn't end with 's', try adding 's' (e.g., "agent" \u2192 "agents")
4. If the guide exists, walk me through the changes step by step
5. If neither form exists, list available migration guides in "upgrade-to-v1/" and suggest which ones might be relevant to "${area}"
6. After you find the guide, collect all the codemod calls to run to codemods. These callouts are marked with "> **Codemod:**" in the docs. Run the codemods with "npx @mastra/codemod@latest <codemod-name> <path>" to automate all those changes. Afterwards, help me with any remaining manual changes needed.`
        }
      }
    ];
  }
  return [
    {
      role: "user",
      content: {
        type: "text",
        text: `I need to migrate my Mastra project from v0.x to v1.0. Use the mastraMigration tool to:

1. If packages aren't already at the 'latest' tag, upgrade packages to the 'latest' tag and do an install of the new packages.
2. First, list all available migration guides with path: "upgrade-to-v1/"
2. Give me a high-level overview of what changed in each area
3. Find relevant migration areas to focus on based on my project's codebase and confirm the list with me
4. After the areas are confirmed, check the migration guides for callouts to codemods. These callouts are marked with "> **Codemod:**" in the docs. Run the codemods with "npx @mastra/codemod@latest v1" to automate all those changes. Afterwards, help me with any remaining manual changes needed.

After the areas are confirmed, we'll go through each one systematically.`
      }
    }
  ];
}
function getMigrationChecklistMessages() {
  return [
    {
      role: "user",
      content: {
        type: "text",
        text: `Create a comprehensive migration checklist for upgrading from Mastra v0.x to v1.0. Use the mastraMigration tool to:

1. List all available migration guides (path: "upgrade-to-v1/")
2. For each guide, extract the key breaking changes
3. Present them as a checklist I can work through

Format the checklist with:
- [ ] checkbox items for each breaking change
- Brief description of what needs to change
- Reference to the specific migration guide

Group the checklist by area (Agents, Tools, Workflows, etc.) so I can tackle one area at a time.`
      }
    }
  ];
}
var mdFileCache = /* @__PURE__ */ new Map();
var __dirname$1 = dirname(fileURLToPath(import.meta.url));
function fromPackageRoot(relative) {
  return path5__default.resolve(__dirname$1, `../`, relative);
}
async function* walkMdFiles(dir) {
  if (mdFileCache.has(dir)) {
    for (const file of mdFileCache.get(dir)) yield file;
    return;
  }
  const filesInDir = [];
  const entries = await fs3.readdir(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = path5__default.join(dir, entry.name);
    if (entry.isDirectory()) {
      for await (const file of walkMdFiles(fullPath)) {
        filesInDir.push(file);
        yield file;
      }
    } else if (entry.isFile() && entry.name.endsWith(".md")) {
      filesInDir.push(fullPath);
      yield fullPath;
    }
  }
  mdFileCache.set(dir, filesInDir);
}
async function searchDocumentContent(keywords, baseDir) {
  if (keywords.length === 0) return [];
  const fileScores = /* @__PURE__ */ new Map();
  for await (const filePath of walkMdFiles(baseDir)) {
    let content;
    try {
      content = await fs3.readFile(filePath, "utf-8");
    } catch {
      continue;
    }
    const lines = content.split("\n");
    lines.forEach((lineText) => {
      const lowerLine = lineText.toLowerCase();
      for (const keyword of keywords) {
        if (lowerLine.includes(keyword.toLowerCase())) {
          const relativePath = path5__default.relative(baseDir, filePath).replace(/\\/g, "/");
          if (!fileScores.has(relativePath)) {
            fileScores.set(relativePath, {
              path: relativePath,
              keywordMatches: /* @__PURE__ */ new Set(),
              totalMatches: 0,
              titleMatches: 0,
              pathRelevance: calculatePathRelevance(relativePath, keywords)
            });
          }
          const score = fileScores.get(relativePath);
          score.keywordMatches.add(keyword);
          score.totalMatches++;
          if (lowerLine.includes("#") || lowerLine.includes("title")) {
            score.titleMatches++;
          }
        }
      }
    });
  }
  const validFiles = Array.from(fileScores.values()).sort((a, b) => calculateFinalScore(b, keywords.length) - calculateFinalScore(a, keywords.length)).slice(0, 10);
  return validFiles.map((score) => score.path);
}
function calculatePathRelevance(filePath, keywords) {
  let relevance = 0;
  const pathLower = filePath.toLowerCase();
  if (pathLower.startsWith("reference/")) relevance += 2;
  keywords.forEach((keyword) => {
    if (pathLower.includes(keyword.toLowerCase())) relevance += 3;
  });
  const highValueDirs = ["rag", "memory", "agents", "workflows"];
  if (highValueDirs.some((dir) => pathLower.includes(dir))) {
    relevance += 1;
  }
  return relevance;
}
function calculateFinalScore(score, totalKeywords) {
  const allKeywordsBonus = score.keywordMatches.size === totalKeywords ? 10 : 0;
  return score.totalMatches * 1 + score.titleMatches * 3 + score.pathRelevance * 2 + score.keywordMatches.size * 5 + allKeywordsBonus;
}
function extractKeywordsFromPath(docPath) {
  const cleanPath = docPath.replace(/\.md$/, "");
  const fileName = cleanPath.split("/").pop() || "";
  const keywords = /* @__PURE__ */ new Set();
  const splitParts = fileName.split(/[-_]|(?=[A-Z])/);
  splitParts.forEach((keyword) => {
    if (keyword.length > 2) {
      keywords.add(keyword.toLowerCase());
    }
  });
  return Array.from(keywords);
}
function normalizeKeywords(keywords) {
  return Array.from(new Set(keywords.flatMap((k) => k.split(/\s+/).filter(Boolean)).map((k) => k.toLowerCase())));
}
async function getMatchingPaths(path7, queryKeywords, baseDir) {
  const pathKeywords = extractKeywordsFromPath(path7);
  const allKeywords = normalizeKeywords([...pathKeywords, ...queryKeywords || []]);
  if (allKeywords.length === 0) {
    return "";
  }
  const suggestedPaths = await searchDocumentContent(allKeywords, baseDir);
  if (suggestedPaths.length === 0) {
    return "";
  }
  const pathList = suggestedPaths.map((path8) => `- ${path8}`).join("\n");
  return `Here are some paths that might be relevant based on your query:

${pathList}`;
}

// src/tools/course.ts
var _courseLessonSchema = z.object({
  lessonName: z.string().describe("Name of the specific lesson to start. It must match the exact lesson name.")
});
var _confirmationSchema = z.object({
  confirm: z.boolean().optional().describe("Set to true to confirm this action")
});
var courseDir = fromPackageRoot(".docs/course");
var introductionPrompt = `
This is a course to help a new user learn about Mastra, the open-source AI Agent framework built in TypeScript.
The following is the introduction content, please provide this text to the user EXACTLY as written below. Do not provide any other text or instructions:

# Welcome to the Mastra Course!

Thank you for registering for the Mastra course! This interactive guide will help you learn how to build powerful AI agents with Mastra, the open-source AI Agent framework built in TypeScript.

## Before We Begin

If you enjoy Mastra, please consider starring the GitHub repository:
https://github.com/mastra-ai/mastra

This helps the project grow and reach more developers like you!

## How This Course Works

- Each lesson is broken into multiple steps
- I'll guide you through the code examples and explanations
- You can ask questions at any time
- If you ever leave and come back, use the \`startMastraCourse\` tool to pick up where you left off. Just ask to "start the Mastra course".
- Use the \`nextMastraCourseStep\` tool to move to the next step when you're ready. Just ask to "move to the next step" when you are ready.
- Use the \`getMastraCourseStatus\` tool to check your progress. You can just ask "get my course progress".
- Use the \`clearMastraCourseHistory\` tool to reset your progress and start over. You can just ask "clear my course progress".

Type "start mastra course" and let's get started with your first lesson!
`;
var lessonPrompt = `
  This is a course to help a new user learn about Mastra, the open-source AI Agent framework built in TypeScript.
  Please help the user through the steps of the course by walking them through the content and following the course
  to write the initial version of the code for them. The goal is to show them how the code works and explain it as they go
  as the course goes on. Each lesson is broken up into steps. You should return the content of the step and ask the user
  to move to the next step when they are ready. If the step contains instructions to write code, you should write the code
  for the user when possible. You should always briefly explain the step before writing the code. Please ensure to 
  return any text in markdown blockquotes exactly as written in your response. When the user ask about their course progress or course status, make sure to include the course status URL in your response. This is important.
`;
function wrapContentInPrompt(content, _isFirstStep = false) {
  let wrappedContent = `${lessonPrompt}

Here is the content for this step: <StepContent>${content}</StepContent>`;
  return `${wrappedContent}

When you're ready to continue, use the \`nextMastraCourseStep\` tool to move to the next step.`;
}
async function getDeviceIdPath() {
  const cacheDir = path5__default.join(os2__default.homedir(), ".cache", "mastra");
  if (!existsSync(cacheDir)) {
    mkdirSync(cacheDir, { recursive: true });
  }
  return path5__default.join(cacheDir, ".device_id");
}
async function getDeviceCredentials() {
  try {
    const deviceIdPath = await getDeviceIdPath();
    if (!existsSync(deviceIdPath)) {
      return null;
    }
    const fileContent = await fs3.readFile(deviceIdPath, "utf-8");
    const parsed = JSON.parse(fileContent);
    if (typeof parsed.deviceId === "string" && typeof parsed.key === "string") {
      return { deviceId: parsed.deviceId, key: parsed.key };
    }
    return null;
  } catch {
    return null;
  }
}
async function getDeviceId() {
  const creds = await getDeviceCredentials();
  if (!creds || !creds?.deviceId) {
    return null;
  }
  return creds.deviceId;
}
async function saveDeviceCredentials(deviceId, key) {
  const deviceIdPath = await getDeviceIdPath();
  const toWrite = JSON.stringify({ deviceId, key });
  await fs3.writeFile(deviceIdPath, toWrite, "utf-8");
  await fs3.chmod(deviceIdPath, 384);
}
async function registerUser(email) {
  const response = await fetch("https://mastra.ai/api/course/register", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ email })
  });
  if (!response.ok) {
    throw new Error(`Registration failed with status ${response.status}: ${response.statusText}`);
  }
  return response.json();
}
async function readCourseStep(lessonName, stepName, _isFirstStep = false) {
  const lessonDirs = await fs3.readdir(courseDir);
  const lessonDir = lessonDirs.find((dir) => dir.replace(/^\d+-/, "") === lessonName);
  if (!lessonDir) {
    throw new Error(`Lesson "${lessonName}" not found.`);
  }
  const lessonPath = path5__default.join(courseDir, lessonDir);
  const files = await fs3.readdir(lessonPath);
  const stepFile = files.find((f) => f.endsWith(".md") && f.replace(/^\d+-/, "").replace(".md", "") === stepName);
  if (!stepFile) {
    throw new Error(`Step "${stepName}" not found in lesson "${lessonName}".`);
  }
  const filePath = path5__default.join(courseDir, lessonDir, stepFile);
  try {
    const content = await fs3.readFile(filePath, "utf-8");
    return wrapContentInPrompt(content);
  } catch (error) {
    throw new Error(`Failed to read step "${stepName}" in lesson "${lessonName}": ${error}`);
  }
}
async function updateCourseStateOnServer(deviceId, state) {
  const creds = await getDeviceCredentials();
  if (!creds) {
    throw new Error("Device credentials not found.");
  }
  const response = await fetch("https://mastra.ai/api/course/update", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-mastra-course-key": creds.key
    },
    body: JSON.stringify({
      id: creds.deviceId,
      state
    })
  });
  if (!response.ok) {
    throw new Error(`Course state update failed with status ${response.status}: ${response.statusText}`);
  }
}
async function saveCourseState(state, deviceId) {
  if (!deviceId) {
    throw new Error("Cannot save course state: User is not registered");
  }
  const statePath = await getCourseStatePath();
  try {
    await fs3.writeFile(statePath, JSON.stringify(state, null, 2), "utf-8");
    try {
      const creds = await getDeviceCredentials();
      if (!creds) throw new Error("Device credentials not found");
      await updateCourseStateOnServer(creds.deviceId, state);
    } catch {
    }
  } catch (error) {
    throw new Error(`Failed to save course state: ${error}`);
  }
}
async function getCourseStatePath() {
  const stateDirPath = path5__default.join(os2__default.homedir(), ".cache", "mastra", "course");
  if (!existsSync(stateDirPath)) {
    mkdirSync(stateDirPath, { recursive: true });
  }
  return path5__default.join(stateDirPath, "state.json");
}
async function loadCourseState() {
  const statePath = await getCourseStatePath();
  try {
    if (existsSync(statePath)) {
      const stateData = await fs3.readFile(statePath, "utf-8");
      return JSON.parse(stateData);
    }
  } catch (error) {
    throw new Error(`Failed to load course state: ${error}`);
  }
  return null;
}
async function scanCourseContent() {
  const lessonDirs = await fs3.readdir(courseDir);
  const lessons = await Promise.all(
    lessonDirs.filter((dir) => !dir.startsWith(".")).sort((a, b) => a.localeCompare(b)).map(async (lessonDir) => {
      const lessonPath = path5__default.join(courseDir, lessonDir);
      const lessonStats = await fs3.stat(lessonPath);
      if (!lessonStats.isDirectory()) return null;
      const lessonName = lessonDir.replace(/^\d+-/, "");
      const stepFiles = (await fs3.readdir(lessonPath)).filter((file) => file.endsWith(".md")).sort((a, b) => a.localeCompare(b));
      const steps = await Promise.all(
        stepFiles.map(async (file) => {
          const stepName = file.replace(/^\d+-/, "").replace(".md", "");
          return {
            name: stepName,
            status: 0
            // Default: not started
          };
        })
      );
      return {
        name: lessonName,
        status: 0,
        // Default: not started
        steps: steps.filter(Boolean)
      };
    })
  );
  const validLessons = lessons.filter((lesson) => lesson !== null);
  return {
    currentLesson: validLessons.length > 0 ? validLessons[0]?.name ?? "" : "",
    lessons: validLessons
  };
}
async function mergeCourseStates(currentState, newState) {
  const existingLessonMap = new Map(currentState.lessons.map((lesson) => [lesson.name, lesson]));
  const mergedLessons = newState.lessons.map((newLesson) => {
    const existingLesson = existingLessonMap.get(newLesson.name);
    if (!existingLesson) {
      return newLesson;
    }
    const existingStepMap = new Map(existingLesson.steps.map((step) => [step.name, step]));
    const mergedSteps = newLesson.steps.map((newStep) => {
      const existingStep = existingStepMap.get(newStep.name);
      if (existingStep) {
        return {
          ...newStep,
          status: existingStep.status
        };
      }
      return newStep;
    });
    let lessonStatus = existingLesson.status;
    if (mergedSteps.every((step) => step.status === 2)) {
      lessonStatus = 2;
    } else if (mergedSteps.some((step) => step.status > 0)) {
      lessonStatus = 1;
    }
    return {
      ...newLesson,
      status: lessonStatus,
      steps: mergedSteps
    };
  });
  let currentLesson = currentState.currentLesson;
  if (!mergedLessons.some((lesson) => lesson.name === currentLesson) && mergedLessons.length > 0) {
    currentLesson = mergedLessons[0]?.name ?? "";
  }
  return {
    currentLesson,
    lessons: mergedLessons
  };
}
var startMastraCourse = {
  name: "startMastraCourse",
  description: "[\u{1F393} COURSE] Starts the Mastra Course. If the user is not registered, they will be prompted to register first. Otherwise, it will start at the first lesson or pick up where they last left off. ALWAYS ask the user for their email address if they are not registered. DO NOT assume their email address, they must confirm their email and that they want to register.",
  parameters: z.object({
    email: z.string().email().optional().describe("Email address for registration if not already registered. ")
  }),
  execute: async (args) => {
    try {
      const creds = await getDeviceCredentials();
      const registered = creds !== null;
      let deviceId = creds?.deviceId ?? null;
      if (!registered) {
        if (!args.email) {
          return "To start the Mastra Course, you need to register first. Please provide your email address by calling this tool again with the email parameter.";
        }
        try {
          const response = await registerUser(args.email);
          if (response.success) {
            await saveDeviceCredentials(response.id, response.key);
            deviceId = response.id;
          } else {
            return `Registration failed: ${response.message}. Please try again with a valid email address.`;
          }
        } catch (error) {
          return `Failed to register: ${error instanceof Error ? error.message : String(error)}. Please try again later.`;
        }
      }
      let courseState = await loadCourseState();
      let statusMessage = "";
      const latestCourseState = await scanCourseContent();
      if (!latestCourseState.lessons.length) {
        return "No course content found. Please make sure the course content is properly set up in the .docs/course/lessons directory.";
      }
      if (courseState) {
        const previousState = JSON.parse(JSON.stringify(courseState));
        courseState = await mergeCourseStates(courseState, latestCourseState);
        const newLessons = latestCourseState.lessons.filter(
          (newLesson) => !previousState.lessons.some((oldLesson) => oldLesson.name === newLesson.name)
        );
        if (newLessons.length > 0) {
          statusMessage = `\u{1F4DA} Course content has been updated! ${newLessons.length} new lesson(s) have been added:
`;
          statusMessage += newLessons.map((lesson) => `- ${lesson.name}`).join("\n");
          statusMessage += "\n\n";
        }
        await saveCourseState(courseState, deviceId);
      } else {
        courseState = latestCourseState;
        await saveCourseState(courseState, deviceId);
        if (!registered && args.email) {
          return introductionPrompt;
        }
      }
      const currentLessonName = courseState.currentLesson;
      const currentLesson = courseState.lessons.find((lesson) => lesson.name === currentLessonName);
      if (!currentLesson) {
        return "Error: Current lesson not found in course content. Please try again or reset your course progress.";
      }
      const currentStep = currentLesson.steps.find((step) => step.status !== 2);
      if (!currentStep && currentLesson.status !== 2) {
        currentLesson.status = 2;
        await saveCourseState(courseState, deviceId);
        const nextLesson = courseState.lessons.find((lesson) => lesson.status !== 2 && lesson.name !== currentLessonName);
        if (nextLesson) {
          courseState.currentLesson = nextLesson.name;
          await saveCourseState(courseState, deviceId);
          return `${statusMessage}\u{1F389} You've completed the "${currentLessonName}" lesson!

Moving on to the next lesson: "${nextLesson.name}".

Use the \`nextMastraCourseStep\` tool to start the first step of this lesson.`;
        } else {
          return `${statusMessage}\u{1F389} Congratulations! You've completed all available lessons in the Mastra Course!

If you'd like to review any lesson, use the \`startMastraCourseLesson\` tool with the lesson name.`;
        }
      }
      if (!currentStep) {
        return `${statusMessage}Error: No incomplete steps found in the current lesson. Please try another lesson or reset your course progress.`;
      }
      currentStep.status = 1;
      if (currentLesson.status === 0) {
        currentLesson.status = 1;
      }
      await saveCourseState(courseState, deviceId);
      const stepContent = await readCourseStep(currentLessonName, currentStep.name);
      return `\u{1F4D8} Lesson: ${currentLessonName}
\u{1F4DD} Step: ${currentStep.name}

${stepContent}

When you've completed this step, use the \`nextMastraCourseStep\` tool to continue.`;
    } catch (error) {
      return `Error starting the Mastra course: ${error instanceof Error ? error.message : String(error)}`;
    }
  }
};
var getMastraCourseStatus = {
  name: "getMastraCourseStatus",
  description: "[\u{1F393} COURSE] Gets the current status of the Mastra Course, including which lessons and steps have been completed",
  parameters: z.object({}),
  execute: async (_args) => {
    try {
      const deviceId = await getDeviceId();
      if (deviceId === null) {
        return "You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.";
      }
      const courseState = await loadCourseState();
      if (!courseState) {
        return "No course progress found. Please start the course first using the `startMastraCourse` tool.";
      }
      const latestCourseState = await scanCourseContent();
      if (!latestCourseState.lessons.length) {
        return "No course content found. Please make sure the course content is properly set up in the .docs/course/lessons directory.";
      }
      const mergedState = await mergeCourseStates(courseState, latestCourseState);
      let statusReport = "# Mastra Course Progress\n\n";
      const totalLessons = mergedState.lessons.length;
      const completedLessons = mergedState.lessons.filter((lesson) => lesson.status === 2).length;
      mergedState.lessons.filter((lesson) => lesson.status === 1).length;
      const totalSteps = mergedState.lessons.reduce((sum, lesson) => sum + lesson.steps.length, 0);
      const completedSteps = mergedState.lessons.reduce(
        (sum, lesson) => sum + lesson.steps.filter((step) => step.status === 2).length,
        0
      );
      statusReport += `## Overall Progress
`;
      statusReport += `- Course status Url: **https://mastra.ai/course/${deviceId}**
`;
      statusReport += `- Current Lesson: **${mergedState.currentLesson}**
`;
      statusReport += `- Lessons: ${completedLessons}/${totalLessons} completed (${Math.round(completedLessons / totalLessons * 100)}%)
`;
      statusReport += `- Steps: ${completedSteps}/${totalSteps} completed (${Math.round(completedSteps / totalSteps * 100)}%)

`;
      statusReport += `## Lesson Details

`;
      mergedState.lessons.forEach((lesson, lessonIndex) => {
        let lessonStatusIcon = "\u2B1C";
        if (lesson.status === 1) lessonStatusIcon = "\u{1F536}";
        if (lesson.status === 2) lessonStatusIcon = "\u2705";
        const isCurrent = lesson.name === mergedState.currentLesson;
        const lessonPrefix = isCurrent ? "\u{1F449} " : "";
        statusReport += `### ${lessonPrefix}${lessonIndex + 1}. ${lessonStatusIcon} ${lesson.name}

`;
        lesson.steps.forEach((step, stepIndex) => {
          let stepStatusIcon = "\u2B1C";
          if (step.status === 1) stepStatusIcon = "\u{1F536}";
          if (step.status === 2) stepStatusIcon = "\u2705";
          statusReport += `- ${stepStatusIcon} Step ${stepIndex + 1}: ${step.name}
`;
        });
        statusReport += "\n";
      });
      statusReport += `## Navigation

`;
      statusReport += `- To continue the course: \`nextMastraCourseStep\`
`;
      statusReport += `- To start a specific lesson: \`startMastraCourseLesson\`
`;
      statusReport += `- To reset progress: \`clearMastraCourseHistory\`
`;
      return `Course Status: ${statusReport}

Course status url: https://mastra.ai/course/${deviceId}`;
    } catch (error) {
      return `Error getting course status: ${error instanceof Error ? error.message : String(error)}`;
    }
  }
};
var startMastraCourseLesson = {
  name: "startMastraCourseLesson",
  description: "[\u{1F393} COURSE] Starts a specific lesson in the Mastra Course. If the lesson has been started before, it will resume from the first incomplete step",
  parameters: _courseLessonSchema,
  execute: async (args) => {
    try {
      const deviceId = await getDeviceId();
      if (deviceId === null) {
        return "You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.";
      }
      let courseState = await loadCourseState();
      if (!courseState) {
        return "No course progress found. Please start the course first using the `startMastraCourse` tool.";
      }
      const targetLessonName = args.lessonName;
      const targetLesson = courseState.lessons.find((lesson) => lesson.name === targetLessonName);
      if (!targetLesson) {
        const availableLessons = courseState.lessons.map((lesson, index) => `${index + 1}. ${lesson.name}`).join("\n");
        return `Lesson "${targetLessonName}" not found. Available lessons:
${availableLessons}`;
      }
      courseState.currentLesson = targetLesson.name;
      const firstIncompleteStep = targetLesson.steps.find((step) => step.status !== 2) || targetLesson.steps[0];
      if (!firstIncompleteStep) {
        return `The lesson "${targetLesson.name}" does not have any steps.`;
      }
      firstIncompleteStep.status = 1;
      if (targetLesson.status === 0) {
        targetLesson.status = 1;
      }
      await saveCourseState(courseState, deviceId);
      const stepContent = await readCourseStep(targetLesson.name, firstIncompleteStep.name);
      return `\u{1F4D8} Starting Lesson: ${targetLesson.name}
\u{1F4DD} Step: ${firstIncompleteStep.name}

${stepContent}

When you've completed this step, use the \`nextMastraCourseStep\` tool to continue.`;
    } catch (error) {
      return `Error starting course lesson: ${error instanceof Error ? error.message : String(error)}`;
    }
  }
};
var nextMastraCourseStep = {
  name: "nextMastraCourseStep",
  description: "[\u{1F393} COURSE] Advances to the next step in the current Mastra Course lesson. If all steps in the current lesson are completed, it will move to the next lesson",
  parameters: z.object({}),
  execute: async (_args) => {
    try {
      const deviceId = await getDeviceId();
      if (deviceId === null) {
        return "You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.";
      }
      const courseState = await loadCourseState();
      if (!courseState) {
        return "No course progress found. Please start the course first using the `startMastraCourse` tool.";
      }
      const currentLessonName = courseState.currentLesson;
      const currentLesson = courseState.lessons.find((lesson) => lesson.name === currentLessonName);
      if (!currentLesson) {
        return "Error: Current lesson not found in course content. Please try again or reset your course progress.";
      }
      const currentStepIndex = currentLesson.steps.findIndex((step) => step.status === 1);
      if (currentStepIndex === -1) {
        return "No step is currently in progress. Please start a step first using the `startMastraCourse` tool.";
      }
      if (currentLesson.steps[currentStepIndex]?.status) {
        currentLesson.steps[currentStepIndex].status = 2;
      }
      const nextStepIndex = currentLesson.steps.findIndex(
        (step, index) => index > currentStepIndex && step.status !== 2
      );
      if (nextStepIndex !== -1) {
        if (currentLesson.steps[nextStepIndex]) {
          currentLesson.steps[nextStepIndex].status = 1;
        }
        await saveCourseState(courseState, deviceId);
        const nextStep = currentLesson.steps[nextStepIndex];
        const stepContent = await readCourseStep(currentLessonName, nextStep?.name ?? "Unknown Step");
        return `\u{1F389} Step "${currentLesson.steps[currentStepIndex]?.name ?? "Unknown Step"}" completed!

\u{1F4D8} Continuing Lesson: ${currentLessonName}
\u{1F4DD} Next Step: ${nextStep?.name ?? "Unknown Step"}

${stepContent}

When you've completed this step, use the \`nextMastraCourseStep\` tool to continue.`;
      }
      currentLesson.status = 2;
      const currentLessonIndex = courseState.lessons.findIndex((lesson) => lesson.name === currentLessonName);
      const nextLesson = courseState.lessons.find((lesson, index) => index > currentLessonIndex && lesson.status !== 2);
      if (nextLesson) {
        courseState.currentLesson = nextLesson.name;
        if (nextLesson.steps.length > 0 && nextLesson.steps[0]) {
          nextLesson.steps[0].status = 1;
        }
        nextLesson.status = 1;
        await saveCourseState(courseState, deviceId);
        const firstStep = nextLesson.steps[0];
        const stepContent = await readCourseStep(nextLesson.name, firstStep?.name ?? "Unknown Step");
        return `\u{1F389} Congratulations! You've completed the "${currentLessonName}" lesson!

\u{1F4D8} Starting New Lesson: ${nextLesson.name}
\u{1F4DD} First Step: ${firstStep?.name ?? "Unknown Step"}

${stepContent}

When you've completed this step, use the \`nextMastraCourseStep\` tool to continue.`;
      }
      await saveCourseState(courseState, deviceId);
      return `\u{1F389} Congratulations! You've completed all available lessons in the Mastra Course!

If you'd like to review any lesson, use the \`startMastraCourseLesson\` tool with the lesson name.`;
    } catch (error) {
      return `Error advancing to the next course step: ${error instanceof Error ? error.message : String(error)}`;
    }
  }
};
var clearMastraCourseHistory = {
  name: "clearMastraCourseHistory",
  description: "[\u{1F393} COURSE] Clears all Mastra Course progress history and starts over from the beginning. This action cannot be undone",
  parameters: _confirmationSchema,
  execute: async (args) => {
    try {
      const deviceId = await getDeviceId();
      if (deviceId === null) {
        return "You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.";
      }
      if (!args.confirm) {
        return "\u26A0\uFE0F This action will delete all your course progress and cannot be undone. To proceed, please run this tool again with the confirm parameter set to true.";
      }
      const statePath = await getCourseStatePath();
      if (!existsSync(statePath)) {
        return "No course progress found. Nothing to clear.";
      }
      await fs3.unlink(statePath);
      return "\u{1F9F9} Course progress has been cleared. You can restart the Mastra course from the beginning.";
    } catch (error) {
      return `Error clearing course history: ${error instanceof Error ? error.message : String(error)}`;
    }
  }
};
var docsBaseDir = fromPackageRoot(".docs/");
async function listDirContents(dirPath) {
  try {
    void logger.debug("Listing directory contents", { path: dirPath });
    const entries = await fs3.readdir(dirPath, { withFileTypes: true });
    const dirs = [];
    const files = [];
    for (const entry of entries) {
      if (entry.isDirectory()) {
        dirs.push(entry.name + "/");
      } else if (entry.isFile() && entry.name.endsWith(".md")) {
        files.push(entry.name.replace(/\.md$/, ""));
      }
    }
    return {
      dirs: dirs.sort(),
      files: files.sort()
    };
  } catch (error) {
    void logger.error("Failed to list directory contents", { path: dirPath, error });
    throw error;
  }
}
async function readDocsContent(docPath, queryKeywords) {
  const basePath = path5__default.resolve(docsBaseDir);
  const fullPath = path5__default.resolve(path5__default.join(basePath, docPath));
  const relativePath = path5__default.relative(basePath, fullPath);
  if (relativePath.startsWith("..") || path5__default.isAbsolute(relativePath)) {
    void logger.error("Path traversal attempt detected", { path: docPath, resolvedPath: fullPath });
    return { found: false, isSecurityViolation: true };
  }
  void logger.debug("Reading docs content", { path: fullPath });
  try {
    const stats = await fs3.stat(fullPath);
    if (stats.isDirectory()) {
      const indexMdPath = path5__default.join(fullPath, "index.md");
      try {
        const content2 = await fs3.readFile(indexMdPath, "utf-8");
        return { found: true, content: content2, isSecurityViolation: false };
      } catch {
      }
      const { dirs, files } = await listDirContents(fullPath);
      const listing = [`Directory contents of ${docPath || "/"}:`, ""];
      if (dirs.length > 0) {
        listing.push("Subdirectories:");
        listing.push(...dirs.map((d) => `- ${docPath ? `${docPath}/${d}` : d}`));
        listing.push("");
      }
      if (files.length > 0) {
        listing.push("Available documentation paths:");
        listing.push(...files.map((f) => `- ${docPath ? `${docPath}/${f}` : f}`));
        listing.push("");
      }
      if (dirs.length === 0 && files.length === 0) {
        listing.push("No documentation available in this directory.");
      }
      const contentBasedSuggestions = await getMatchingPaths(docPath, queryKeywords, docsBaseDir);
      const suggestions = contentBasedSuggestions ? ["---", "", contentBasedSuggestions, ""].join("\n") : "";
      return { found: true, content: listing.join("\n") + suggestions, isSecurityViolation: false };
    }
    const content = await fs3.readFile(fullPath, "utf-8");
    return { found: true, content, isSecurityViolation: false };
  } catch (error) {
    if (error.code === "ENOENT") {
      try {
        const mdPath = fullPath + ".md";
        const content = await fs3.readFile(mdPath, "utf-8");
        return { found: true, content, isSecurityViolation: false };
      } catch {
        return { found: false, isSecurityViolation: false };
      }
    }
    throw error;
  }
}
async function findNearestDirectory(docPath, availablePaths2) {
  void logger.debug("Finding nearest directory", { path: docPath });
  const parts = docPath.split("/");
  while (parts.length > 0) {
    const testPath = parts.join("/");
    try {
      const fullPath = path5__default.join(docsBaseDir, testPath);
      const stats = await fs3.stat(fullPath);
      if (stats.isDirectory()) {
        const { dirs, files } = await listDirContents(fullPath);
        const listing = [
          `Path "${docPath}" not found.`,
          `Here are the available paths in "${testPath}":`,
          ""
        ];
        if (dirs.length > 0) {
          listing.push("Directories:");
          listing.push(...dirs.map((d) => `- ${testPath}/${d}`));
          listing.push("");
        }
        if (files.length > 0) {
          listing.push("Files:");
          listing.push(...files.map((f) => `- ${testPath}/${f}`));
        }
        return listing.join("\n");
      }
    } catch {
      void logger.debug("Directory not found, trying parent", { parent: parts.slice(0, -1).join("/") });
    }
    parts.pop();
  }
  return [`Path "${docPath}" not found.`, "Here are all available paths:", "", availablePaths2].join("\n");
}
async function getAvailablePaths() {
  const { dirs, files } = await listDirContents(docsBaseDir);
  let referenceDirs = [];
  if (dirs.includes("reference/")) {
    const { dirs: refDirs } = await listDirContents(path5__default.join(docsBaseDir, "reference"));
    referenceDirs = refDirs.map((d) => `reference/${d}`);
  }
  return [
    "Available top-level paths:",
    "",
    "Directories:",
    ...dirs.map((d) => `- ${d}`),
    "",
    referenceDirs.length > 0 ? "Reference subdirectories:" : "",
    ...referenceDirs.map((d) => `- ${d}`),
    "",
    files.length > 0 ? "Files:" : "",
    ...files.map((f) => `- ${f}`)
  ].filter(Boolean).join("\n");
}
var availablePaths = await getAvailablePaths();
var docsInputSchema = z.object({
  paths: z.array(z.string()).min(1).describe(`One or more documentation paths to fetch
Available paths:
${availablePaths}`),
  queryKeywords: z.array(z.string()).optional().describe(
    "Keywords from user query to use for matching documentation. Each keyword should be a single word or short phrase; any whitespace-separated keywords will be split automatically."
  )
});
var docsTool = {
  name: "mastraDocs",
  description: `[\u{1F310} REMOTE] Get Mastra documentation.
    Request paths to explore the docs. References contain API docs.
    Other paths contain guides. The user doesn't know about files and directories.
    You can also use keywords from the user query to find relevant documentation, but prioritize paths.
    This is your internal knowledge the user can't read.
    If the user asks about a feature check general docs as well as reference docs for that feature.
    Ex: with workflows check in docs/workflows and in reference/workflows.
    Provide code examples so the user understands.
    IMPORTANT: Be concise with your answers. The user will ask for more info.
    If packages need to be installed, provide the pnpm command to install them.
    Ex. if you see \`import { X } from "@mastra/$PACKAGE_NAME"\` in an example, show an install command.
    Always install latest tag, not alpha unless requested. If you scaffold a new project it may be in a subdir.
    When displaying results, always mention which file path contains the information so users know where this documentation lives.`,
  parameters: docsInputSchema,
  execute: async (args) => {
    void logger.debug("Executing mastraDocs tool", { args });
    try {
      const queryKeywords = args.queryKeywords ?? [];
      const results = await Promise.all(
        args.paths.map(async (docPath) => {
          try {
            const result = await readDocsContent(docPath, queryKeywords);
            if (result.found) {
              return {
                path: docPath,
                content: result.content,
                error: null
              };
            }
            if (result.isSecurityViolation) {
              return {
                path: docPath,
                content: null,
                error: "Invalid path"
              };
            }
            const directorySuggestions = await findNearestDirectory(docPath, availablePaths);
            const contentBasedSuggestions = await getMatchingPaths(docPath, queryKeywords, docsBaseDir);
            return {
              path: docPath,
              content: null,
              error: [directorySuggestions, contentBasedSuggestions].join("\n\n")
            };
          } catch (error) {
            void logger.warning(`Failed to read content for path: ${docPath}`, error);
            return {
              path: docPath,
              content: null,
              error: error instanceof Error ? error.message : "Unknown error"
            };
          }
        })
      );
      const output = results.map((result) => {
        if (result.error) {
          return `## ${result.path}

${result.error}

---
`;
        }
        return `## ${result.path}

${result.content}

---
`;
      }).join("\n");
      return output;
    } catch (error) {
      void logger.error("Failed to execute mastraDocs tool", error);
      throw error;
    }
  }
};
var packageCache = /* @__PURE__ */ new Map();
var sourceMapCache = /* @__PURE__ */ new Map();
var packageInfoCache = /* @__PURE__ */ new Map();
var KNOWN_MASTRA_PACKAGES = [
  "@mastra/core",
  "@mastra/cli",
  "@mastra/memory",
  "@mastra/rag",
  "@mastra/evals",
  "@mastra/mcp",
  "@mastra/server",
  "@mastra/deployer",
  "@mastra/agent-builder",
  "@mastra/auth",
  "@mastra/fastembed",
  "@mastra/loggers",
  "@mastra/schema-compat",
  "@mastra/codemod"
];
async function getPackageRootPath(packageName, projectPath) {
  const cacheKey = `${packageName}:${projectPath}`;
  if (packageInfoCache.has(cacheKey)) {
    return packageInfoCache.get(cacheKey);
  }
  try {
    const info = await getPackageInfo(packageName, {
      paths: [path5__default.join(projectPath, "node_modules")]
    });
    if (info?.rootPath) {
      const result = { rootPath: info.rootPath, version: info.version || "unknown" };
      packageInfoCache.set(cacheKey, result);
      void logger.debug("Resolved package with local-pkg", { packageName, projectPath, ...result });
      return result;
    }
  } catch (err) {
    void logger.debug("Package not found or error resolving", {
      packageName,
      projectPath,
      error: err instanceof Error ? err.message : String(err)
    });
  }
  packageInfoCache.set(cacheKey, null);
  return null;
}
async function getInstalledMastraPackages(projectPath) {
  const cacheKey = projectPath;
  if (packageCache.has(cacheKey)) {
    void logger.debug("Using cached package list", { count: packageCache.get(cacheKey).length });
    return packageCache.get(cacheKey);
  }
  void logger.debug("Scanning for @mastra packages using local-pkg", { projectPath });
  const packages = [];
  const packagesWithoutDocs = [];
  for (const packageName of KNOWN_MASTRA_PACKAGES) {
    const packageInfo = await getPackageRootPath(packageName, projectPath);
    if (packageInfo) {
      const docsPath = path5__default.join(packageInfo.rootPath, "dist", "docs");
      try {
        const stats = await fs3.stat(docsPath);
        if (stats.isDirectory()) {
          packages.push(packageName);
          void logger.debug("Found package with embedded docs", { package: packageName });
        } else {
          packagesWithoutDocs.push(packageName);
        }
      } catch {
        packagesWithoutDocs.push(packageName);
      }
    }
  }
  const result = packages.sort();
  packageCache.set(cacheKey, result);
  void logger.info("Package scan complete", {
    packagesWithDocs: result.length,
    packagesWithoutDocs: packagesWithoutDocs.length,
    packages: result
  });
  return result;
}
async function readSourceMap(packageName, projectPath) {
  const cacheKey = `${packageName}:${projectPath}`;
  if (sourceMapCache.has(cacheKey)) return sourceMapCache.get(cacheKey);
  try {
    const packageInfo = await getPackageRootPath(packageName, projectPath);
    if (!packageInfo) {
      sourceMapCache.set(cacheKey, null);
      return null;
    }
    const sourceMapPath = path5__default.join(packageInfo.rootPath, "dist", "docs", "SOURCE_MAP.json");
    const content = await fs3.readFile(sourceMapPath, "utf-8");
    const sourceMap = JSON.parse(content);
    sourceMapCache.set(cacheKey, sourceMap);
    return sourceMap;
  } catch {
    sourceMapCache.set(cacheKey, null);
    return null;
  }
}
var getMastraHelpTool = {
  name: "getMastraHelp",
  description: `\u{1F680} START HERE - Complete guide to Mastra documentation tools.

    This MCP server provides TWO documentation sources:

    ## \u{1F4E6} LOCAL PACKAGE DOCS (Recommended for Development)
    SOURCE: Your installed @mastra packages in node_modules
    VERSION: Matches your installed code exactly

    ADVANTAGES:
    - \u2705 Version-matched to your code
    - \u2705 Complete TypeScript type definitions
    - \u2705 Works offline
    - \u2705 SOURCE_MAP.json with exact exports

    TOOLS: listMastraPackages, getMastraExports, getMastraExportDetails, readMastraDocs, searchMastraDocs
    USE WHEN: Writing code, implementing features, checking APIs, debugging

    ## \u{1F310} REMOTE WEBSITE DOCS (For Latest Info & Learning)
    SOURCE: mastra.ai website
    VERSION: Latest published documentation

    ADVANTAGES:
    - \u2705 Always up-to-date
    - \u2705 Blog posts and announcements
    - \u2705 Migration guides
    - \u2705 Curated examples

    TOOLS: mastraDocs, mastraBlog, mastraExamples, mastraChanges, mastraMigration
    USE WHEN: Learning concepts, checking latest features, migration help

    ## \u{1F393} INTERACTIVE COURSE
    TOOLS: startMastraCourse, getMastraCourseStatus, etc.
    USE WHEN: User wants guided learning experience

    ---

    RECOMMENDED WORKFLOW:
    1. For coding: listMastraPackages \u2192 getMastraExports \u2192 getMastraExportDetails
    2. For learning: mastraDocs
    3. Version mismatch: mastraChanges \u2192 mastraMigration

    This tool shows you which packages are installed and provides detailed guidance on using all available documentation tools.`,
  parameters: z.object({
    projectPath: z.string().describe("Absolute path to your project root (we will search upward for node_modules with Mastra packages)")
  }),
  execute: async (args) => {
    void logger.debug("Executing getMastraHelp tool", { projectPath: args.projectPath });
    const packages = await getInstalledMastraPackages(args.projectPath);
    if (packages.length === 0) {
      return `No Mastra packages with embedded documentation found in your project.

To use these tools, install Mastra packages like:
- npm install @mastra/core
- npm install @mastra/memory
- npm install @mastra/rag

Then rebuild/reinstall to generate embedded docs.`;
    }
    return `# Mastra Documentation System - Complete Guide

This MCP server provides **TWO** documentation sources. Choose based on your needs:

---

## \u{1F4E6} LOCAL PACKAGE DOCS (Your Installed Packages)

Found ${packages.length} installed package(s) with embedded documentation:
${packages.map((pkg) => `- ${pkg}`).join("\n")}

**SOURCE**: Your node_modules (matches installed code version)
**USE WHEN**: Writing code, implementing features, debugging, checking APIs

### Available LOCAL Tools:

**1. listMastraPackages** - List installed packages
   Returns: Packages with embedded docs

**2. getMastraExports** - Explore package API surface
   Example: See all exports from @mastra/core (Agent, Tool, Workflow, etc.)
   Returns: List of exports with source file locations

**3. getMastraExportDetails** - Get type definitions & code
   Example: Get full TypeScript types for Agent class
   Returns: Complete type definitions and optionally implementation source

**4. readMastraDocs** - Read comprehensive guides
   Example: Read documentation about agents, tools, workflows, memory
   Returns: Topic-based guides and examples from your installed version

**5. searchMastraDocs** - Search local documentation
   Example: Search for "memory processors" or "semantic recall"
   Returns: Relevant excerpts from your installed docs

### Typical LOCAL Workflow:
1. listMastraPackages \u2192 see what's installed
2. getMastraExports \u2192 explore package API
3. getMastraExportDetails \u2192 get type definitions
4. readMastraDocs \u2192 learn concepts
5. searchMastraDocs \u2192 find specific info

---

## \u{1F310} REMOTE WEBSITE DOCS (mastra.ai)

**SOURCE**: https://mastra.ai (latest published documentation)
**USE WHEN**: Learning new concepts, checking latest features, migration guides

### Available REMOTE Tools:

**mastraDocs** - Browse official documentation
   Latest guides, references, and tutorials

**mastraBlog** - Read blog posts and announcements
   News, features, changelogs

**mastraExamples** - Get curated code examples
   Full example applications

**mastraChanges** - View package changelogs
   See what's new in each version

**mastraMigration** - Get migration guides
   Upgrade between versions

\u26A0\uFE0F **Version Note**: Remote docs show latest published version. For API reference matching YOUR code, use LOCAL tools above.

---

## \u{1F393} INTERACTIVE COURSE

**startMastraCourse**, **getMastraCourseStatus**, **startMastraCourseLesson**, **nextMastraCourseStep**, **clearMastraCourseHistory**

Guided learning experience with hands-on exercises.

---

## Quick Start Recommendations

**If you're writing code**: Use LOCAL tools
   \u2192 Start with listMastraPackages

**If you're learning**: Use REMOTE tools
   \u2192 Start with mastraDocs

**If version differs**: Check changes
   \u2192 mastraChanges \u2192 mastraMigration`;
  }
};
var listInstalledPackagesTool = {
  name: "listMastraPackages",
  description: `[\u{1F4E6} LOCAL PACKAGES] Discover which Mastra packages are installed and have documentation available.

    Use this when you need to:
    - See what Mastra packages you can work with
    - Start exploring Mastra documentation
    - Check if a specific package is available

    Returns: List of @mastra/* packages (core, memory, rag, etc.) with embedded docs.
    Next step: Use getMastraExports to explore a specific package's API.`,
  parameters: z.object({
    projectPath: z.string().describe("Absolute path to your project root (we will search upward for node_modules with Mastra packages)")
  }),
  execute: async (args) => {
    void logger.debug("Executing listInstalledMastraPackages tool", {
      projectPath: args.projectPath,
      cwd: process.cwd(),
      env: {
        PWD: process.env.PWD,
        HOME: process.env.HOME
      }
    });
    const packages = await getInstalledMastraPackages(args.projectPath);
    if (packages.length === 0) {
      return `No @mastra/* packages with embedded docs found in your project.

Install Mastra packages to get started:
- npm install @mastra/core
- npm install @mastra/memory
- npm install @mastra/rag`;
    }
    return [
      `# Installed Mastra Packages`,
      "",
      `Found ${packages.length} package(s) with embedded documentation:`,
      "",
      ...packages.map((pkg) => `- ${pkg}`),
      "",
      "## Next Steps",
      "",
      "1. Use **getMastraExports** with a package name to see all available APIs",
      "2. Use **readMastraDocs** with a package name to browse topic guides",
      "3. Use **searchMastraDocs** to find specific information"
    ].join("\n");
  }
};
var readSourceMapTool = {
  name: "getMastraExports",
  description: `[\u{1F4E6} LOCAL PACKAGES] Explore the complete API surface of a Mastra package - see all classes, functions, types, and constants.

    Use this when you need to:
    - Discover what APIs a Mastra package provides (Agent, Tool, Workflow, etc.)
    - See all available classes and functions before implementing
    - Find the right export for your use case
    - Understand package structure and organization

    Returns: List of all exports with their source file locations.
    Next step: Use getMastraExportDetails to get full type definitions and code for a specific export.`,
  parameters: z.object({
    package: z.string().describe('Package name to explore (e.g., "@mastra/core", "@mastra/memory", "@mastra/rag")'),
    projectPath: z.string().describe("Absolute path to your project root (we will search upward for node_modules)"),
    filter: z.string().optional().describe('Optional: filter exports by name (case-insensitive, e.g., "Agent", "create", "Tool")')
  }),
  execute: async (args) => {
    void logger.debug("Executing readMastraSourceMap tool", { args });
    const sourceMap = await readSourceMap(args.package, args.projectPath);
    if (!sourceMap) return `No SOURCE_MAP.json found for ${args.package}.`;
    let exports$1 = Object.entries(sourceMap.exports);
    if (args.filter) {
      const filterLower = args.filter.toLowerCase();
      exports$1 = exports$1.filter(([name]) => name.toLowerCase().includes(filterLower));
    }
    if (exports$1.length === 0) {
      return args.filter ? `No exports matching "${args.filter}" in ${args.package}.

Try running without a filter to see all available exports.` : `No exports found in ${args.package}.`;
    }
    return [
      `# ${sourceMap.package} v${sourceMap.version} - API Exports`,
      "",
      `Found ${exports$1.length} export(s)${args.filter ? ` matching "${args.filter}"` : ""}:`,
      "",
      ...exports$1.map(([name, info]) => {
        const line = info.line ? `:${info.line}` : "";
        return `- **${name}**: \`${info.implementation}${line}\``;
      }),
      "",
      "## Next Steps",
      "",
      "- Use **getMastraExportDetails** with an export name to see full type definitions and code",
      "- Use **readMastraDocs** to read conceptual guides and examples",
      "- Use **searchMastraDocs** to find specific topics or patterns"
    ].join("\n");
  }
};
var findExportTool = {
  name: "getMastraExportDetails",
  description: `[\u{1F4E6} LOCAL PACKAGES] Get complete API reference for a specific Mastra export - type definitions, interfaces, and optionally source code.

    Use this when you need to:
    - Understand how to use a specific Mastra class or function (Agent, Tool, Workflow, etc.)
    - See TypeScript type definitions and interfaces
    - Look up method signatures and parameters
    - Read implementation code and examples
    - Understand constructor options and configuration

    Returns: Full TypeScript type definitions and optionally implementation source code.
    Example: Get details on the Agent class to see how to create and configure agents.`,
  parameters: z.object({
    package: z.string().describe('Package name (e.g., "@mastra/core", "@mastra/memory")'),
    exportName: z.string().describe('Exact export name to look up (e.g., "Agent", "createTool", "Workflow")'),
    includeTypes: z.boolean().optional().default(true).describe("Include TypeScript type definitions (recommended: true)"),
    includeImplementation: z.boolean().optional().default(false).describe("Include source code implementation (useful for understanding internals)"),
    implementationLines: z.number().optional().default(50).describe("Number of lines of implementation code to show (default: 50)"),
    projectPath: z.string().describe("Absolute path to your project root (we will search upward for node_modules)")
  }),
  execute: async (args) => {
    void logger.debug("Executing findMastraExport tool", { args });
    const sourceMap = await readSourceMap(args.package, args.projectPath);
    if (!sourceMap) return `No SOURCE_MAP.json found for ${args.package}.`;
    const exportInfo = sourceMap.exports[args.exportName];
    if (!exportInfo) {
      const match = Object.entries(sourceMap.exports).find(
        ([name]) => name.toLowerCase() === args.exportName.toLowerCase()
      );
      if (match) {
        return `Export "${args.exportName}" not found. Did you mean "${match[0]}"?

Run getMastraExports with package="${args.package}" to see all available exports.`;
      }
      return `Export "${args.exportName}" not found in ${args.package}.

Run getMastraExports with package="${args.package}" to see all available exports.`;
    }
    const packageInfo = await getPackageRootPath(args.package, args.projectPath);
    if (!packageInfo) {
      return `Package ${args.package} not found. Make sure it's installed.`;
    }
    const output = [`# ${args.exportName} (${args.package})`, ""];
    if (args.includeTypes !== false) {
      try {
        const typesPath = path5__default.join(packageInfo.rootPath, exportInfo.types);
        const typesContent = await fs3.readFile(typesPath, "utf-8");
        output.push("## Type Definition", "", `\`${exportInfo.types}\``, "", "```typescript");
        const lines = typesContent.split("\n");
        let startLine = lines.findIndex((line) => line.includes(args.exportName));
        if (startLine === -1) {
          output.push(typesContent.slice(0, 2e3));
        } else {
          startLine = Math.max(0, startLine - 2);
          let endLine = Math.min(lines.length, startLine + 50);
          output.push(lines.slice(startLine, endLine).join("\n"));
        }
        output.push("```", "");
      } catch {
        output.push("## Type Definition", "", `Could not read: ${exportInfo.types}`, "");
      }
    }
    if (args.includeImplementation) {
      try {
        const implPath = path5__default.join(packageInfo.rootPath, exportInfo.implementation);
        const implContent = await fs3.readFile(implPath, "utf-8");
        const lines = implContent.split("\n");
        const numLines = args.implementationLines || 50;
        output.push("## Implementation", "");
        output.push(`\`${exportInfo.implementation}\`${exportInfo.line ? ` (line ${exportInfo.line})` : ""}`);
        output.push("", "```javascript");
        const startLine = exportInfo.line ? Math.max(0, exportInfo.line - 1) : 0;
        const endLine = Math.min(lines.length, startLine + numLines);
        output.push(lines.slice(startLine, endLine).join("\n"));
        if (endLine < lines.length) output.push(`// ... ${lines.length - endLine} more lines`);
        output.push("```", "");
      } catch {
        output.push("## Implementation", "", `Could not read: ${exportInfo.implementation}`, "");
      }
    }
    output.push(
      "## Next Steps",
      "",
      "- Use **readMastraDocs** to see practical guides and examples",
      "- Use **searchMastraDocs** to find usage patterns and best practices",
      "- Use **getMastraExports** to explore related APIs"
    );
    return output.join("\n");
  }
};
var readEmbeddedDocsTool = {
  name: "readMastraDocs",
  description: `[\u{1F4E6} LOCAL PACKAGES] Read comprehensive guides and documentation on Mastra concepts, patterns, and implementation examples.

    Use this when you need to:
    - Learn how to implement Mastra features (agents, tools, workflows, memory, RAG, etc.)
    - Understand Mastra architecture and design patterns
    - See practical code examples and tutorials
    - Read getting started guides and best practices
    - Understand how different components work together

    Returns: Topic-based documentation with explanations, examples, and usage patterns.
    Available topics: agents, tools, workflows, memory, rag, integrations, deployment, and more.`,
  parameters: z.object({
    package: z.string().describe('Package name to read docs from (e.g., "@mastra/core", "@mastra/memory")'),
    topic: z.string().optional().describe(
      'Optional: topic folder to read (e.g., "agents", "tools", "workflows"). Omit to list all available topics.'
    ),
    file: z.string().optional().describe('Optional: specific documentation file within the topic (e.g., "01-overview.md")'),
    projectPath: z.string().describe("Absolute path to your project root (we will search upward for node_modules)")
  }),
  execute: async (args) => {
    void logger.debug("Executing readMastraEmbeddedDocs tool", { args });
    const packageInfo = await getPackageRootPath(args.package, args.projectPath);
    if (!packageInfo) {
      return `Package ${args.package} not found. Make sure it's installed.`;
    }
    const docsPath = path5__default.join(packageInfo.rootPath, "dist", "docs");
    try {
      await fs3.stat(docsPath);
    } catch {
      return `No embedded docs found for ${args.package}.

Make sure the package is installed and has documentation generated.`;
    }
    if (!args.topic) {
      const entries = await fs3.readdir(docsPath, { withFileTypes: true });
      const topics = entries.filter((e) => e.isDirectory()).map((e) => e.name);
      const files = entries.filter((e) => e.isFile()).map((e) => e.name);
      return [
        `# ${args.package} - Available Documentation`,
        "",
        "## Root Files",
        ...files.map((f) => `- ${f}`),
        "",
        "## Documentation Topics",
        ...topics.map((t) => `- **${t}/** - Run readMastraDocs with topic="${t}" to read`),
        "",
        "## Next Steps",
        "",
        "- Choose a topic and run **readMastraDocs** with the topic parameter",
        "- Use **searchMastraDocs** to search for specific information",
        "- Use **getMastraExports** to see available APIs"
      ].join("\n");
    }
    const topicPath = path5__default.join(docsPath, args.topic);
    if (args.file) {
      try {
        const content = await fs3.readFile(path5__default.join(topicPath, args.file), "utf-8");
        return `# ${args.package}/${args.topic}/${args.file}

${content}

## Next Steps

- Use **getMastraExportDetails** to see API references for specific classes/functions mentioned
- Use **searchMastraDocs** to find related topics
- Use **getMastraExports** to explore available APIs`;
      } catch {
        return `File not found: ${args.topic}/${args.file}

Run readMastraDocs with package="${args.package}" and topic="${args.topic}" (without file parameter) to see available files.`;
      }
    }
    try {
      const entries = await fs3.readdir(topicPath, { withFileTypes: true });
      const files = entries.filter((e) => e.isFile() && e.name.endsWith(".md")).sort();
      if (files.length === 0) {
        return `No markdown files in ${args.topic}/

Run readMastraDocs with package="${args.package}" (without topic parameter) to see available topics.`;
      }
      const contents = [`# ${args.package} - ${args.topic}`, ""];
      for (const file of files) {
        const content = await fs3.readFile(path5__default.join(topicPath, file.name), "utf-8");
        contents.push(`## ${file.name}`, "", content, "", "---", "");
      }
      contents.push(
        "",
        "## Next Steps",
        "",
        "- Use **getMastraExportDetails** to see API references for specific classes/functions mentioned above",
        "- Use **searchMastraDocs** to find related information",
        "- Use **getMastraExports** to explore the complete API surface"
      );
      return contents.join("\n");
    } catch {
      return `Topic not found: ${args.topic}

Run readMastraDocs with package="${args.package}" (without topic parameter) to see available topics.`;
    }
  }
};
var searchEmbeddedDocsTool = {
  name: "searchMastraDocs",
  description: `[\u{1F4E6} LOCAL PACKAGES] Search across all Mastra documentation to find specific information, patterns, or examples.

    Use this when you need to:
    - Find specific topics or concepts quickly (e.g., "memory processors", "tool composition")
    - Locate examples of specific features or patterns
    - Search for error messages or troubleshooting info
    - Find mentions of specific APIs or configuration options
    - Discover where a feature is documented

    Returns: Relevant documentation excerpts with file paths, ranked by relevance.
    Tip: Use specific terms for better results (e.g., "agent memory" vs "memory").`,
  parameters: z.object({
    query: z.string().describe('What to search for (case-insensitive, e.g., "workflow steps", "vector store", "authentication")'),
    package: z.string().optional().describe('Optional: limit search to a specific package (e.g., "@mastra/core"). Omit to search all packages.'),
    maxResults: z.number().optional().default(10).describe("Optional: maximum number of results to return (default: 10)"),
    projectPath: z.string().describe("Absolute path to your project root (we will search upward for node_modules)")
  }),
  execute: async (args) => {
    void logger.debug("Executing searchMastraEmbeddedDocs tool", { args });
    const packages = args.package ? [args.package] : await getInstalledMastraPackages(args.projectPath);
    if (packages.length === 0) return "No Mastra packages found.";
    const queryLower = args.query.toLowerCase();
    const results = [];
    for (const pkg of packages) {
      const packageInfo = await getPackageRootPath(pkg, args.projectPath);
      if (!packageInfo) continue;
      const docsPath = path5__default.join(packageInfo.rootPath, "dist", "docs");
      try {
        const findFiles = async (dir) => {
          const entries = await fs3.readdir(dir, { withFileTypes: true });
          const files = [];
          for (const entry of entries) {
            const fullPath = path5__default.join(dir, entry.name);
            if (entry.isDirectory()) files.push(...await findFiles(fullPath));
            else if (entry.name.endsWith(".md")) files.push(fullPath);
          }
          return files;
        };
        for (const file of await findFiles(docsPath)) {
          const content = await fs3.readFile(file, "utf-8");
          if (!content.toLowerCase().includes(queryLower)) continue;
          const lines = content.split("\n");
          for (let i = 0; i < lines.length; i++) {
            if (lines[i]?.toLowerCase().includes(queryLower)) {
              const start = Math.max(0, i - 1);
              const end = Math.min(lines.length, i + 3);
              const excerpt = lines.slice(start, end).join("\n").slice(0, 300);
              const contentLower = content.toLowerCase();
              const occurrences = contentLower.split(queryLower).length - 1;
              results.push({
                pkg,
                file: path5__default.relative(docsPath, file),
                excerpt,
                score: occurrences
              });
              break;
            }
          }
        }
      } catch {
      }
    }
    results.sort((a, b) => b.score - a.score);
    const topResults = results.slice(0, args.maxResults || 10);
    if (topResults.length === 0) {
      return `No results found for "${args.query}".

Try:
- Using different search terms
- Searching for broader topics
- Using **listMastraPackages** to see available packages
- Using **readMastraDocs** to browse documentation by topic`;
    }
    return [
      `# Search Results: "${args.query}"`,
      "",
      `Found ${results.length} result(s), showing top ${topResults.length}:`,
      "",
      ...topResults.map((r, i) => `## ${i + 1}. ${r.pkg} - ${r.file}

\`\`\`
${r.excerpt}
\`\`\`
`),
      "",
      "## Next Steps",
      "",
      "- Use **readMastraDocs** with a package and topic to read full documentation",
      "- Use **getMastraExportDetails** to see API details for mentioned classes/functions",
      "- Refine your search with more specific terms if needed"
    ].join("\n");
  }
};
var embeddedDocsTools = {
  getMastraHelp: getMastraHelpTool,
  listMastraPackages: listInstalledPackagesTool,
  getMastraExports: readSourceMapTool,
  getMastraExportDetails: findExportTool,
  readMastraDocs: readEmbeddedDocsTool,
  searchMastraDocs: searchEmbeddedDocsTool
};
var migrationsBaseDir = fromPackageRoot(".docs/guides/migrations");
function parseSections(content) {
  const lines = content.split("\n");
  const sections = [];
  let currentSection = null;
  let inFrontmatter = false;
  let contentStarted = false;
  for (let index = 0; index < lines.length; index++) {
    const line = lines[index];
    if (index === 0 && line === "---") {
      inFrontmatter = true;
      continue;
    }
    if (inFrontmatter && line === "---") {
      inFrontmatter = false;
      continue;
    }
    if (inFrontmatter) continue;
    contentStarted = true;
    const headingMatch = line?.match(/^(#{2,3})\s+(.+)$/);
    if (headingMatch && contentStarted) {
      if (currentSection) {
        currentSection.endLine = index - 1;
        sections.push(currentSection);
      }
      const level = headingMatch[1]?.length ?? 0;
      currentSection = {
        title: headingMatch[2] || "Untitled",
        level,
        content: line + "\n",
        startLine: index,
        endLine: index
      };
    } else if (currentSection) {
      currentSection.content += line + "\n";
    }
  }
  if (currentSection) {
    currentSection.endLine = lines.length - 1;
    sections.push(currentSection);
  }
  return sections;
}
async function discoverMigrations(baseDir, relativePath = "") {
  const migrations = [];
  const fullPath = path5__default.join(baseDir, relativePath);
  try {
    const entries = await fs3.readdir(fullPath, { withFileTypes: true });
    for (const entry of entries) {
      const entryRelativePath = path5__default.join(relativePath, entry.name);
      if (entry.isDirectory()) {
        migrations.push({
          path: entryRelativePath,
          type: "directory"
        });
        const subMigrations = await discoverMigrations(baseDir, entryRelativePath);
        migrations.push(...subMigrations);
      } else if (entry.isFile() && entry.name.endsWith(".md")) {
        const cleanName = entry.name.replace(/\.md$/, "");
        migrations.push({
          path: relativePath ? path5__default.join(relativePath, cleanName) : cleanName,
          type: "file"
        });
      }
    }
  } catch (error) {
    void logger.error("Failed to discover migrations", { path: fullPath, error });
  }
  return migrations;
}
async function listDirectoryContents(dirPath = "") {
  try {
    const fullPath = path5__default.join(migrationsBaseDir, dirPath);
    const resolvedPath = path5__default.resolve(fullPath);
    const resolvedBaseDir = path5__default.resolve(migrationsBaseDir);
    if (!resolvedPath.startsWith(resolvedBaseDir)) {
      return "Invalid path";
    }
    const entries = await fs3.readdir(fullPath, { withFileTypes: true });
    const directories = [];
    const files = [];
    for (const entry of entries) {
      if (entry.isDirectory()) {
        directories.push(entry.name);
      } else if (entry.isFile() && entry.name.endsWith(".md")) {
        files.push(entry.name.replace(/\.md$/, ""));
      }
    }
    const output = [];
    const currentPath = dirPath || "migrations";
    output.push(`# ${currentPath}`);
    output.push("");
    if (directories.length > 0) {
      output.push("**Directories:**");
      directories.sort().forEach((dir) => {
        const nextPath = dirPath ? `${dirPath}/${dir}` : dir;
        output.push(`- **${dir}/** - Explore with \`{ path: "${nextPath}/" }\``);
      });
      output.push("");
    }
    if (files.length > 0) {
      output.push("**Migration Guides:**");
      files.sort().forEach((file) => {
        const filePath = dirPath ? `${dirPath}/${file}` : file;
        output.push(`- **${file}** - Get with \`{ path: "${filePath}" }\``);
      });
      output.push("");
    }
    if (directories.length === 0 && files.length === 0) {
      output.push("No migrations found in this directory.");
    }
    output.push("---");
    output.push("");
    output.push("**Actions:**");
    output.push("- Navigate to a directory by setting `path` to directory name with trailing `/`");
    output.push("- View a migration guide by setting `path` to the guide name");
    output.push("- List sections in a guide with `listSections: true`");
    output.push("- Search all guides with `queryKeywords`");
    return output.join("\n");
  } catch (error) {
    if (error.code === "ENOENT") {
      return `Directory "${dirPath}" not found. Use \`{}\` to see top-level migrations.`;
    }
    throw error;
  }
}
async function readMigrationContent(migrationPath) {
  try {
    const cleanPath = migrationPath.replace(/\.(mdx|md)$/, "");
    const filePath = path5__default.join(migrationsBaseDir, cleanPath + ".md");
    const resolvedPath = path5__default.resolve(filePath);
    const resolvedBaseDir = path5__default.resolve(migrationsBaseDir);
    if (!resolvedPath.startsWith(resolvedBaseDir)) {
      void logger.error("Path traversal attempt detected");
      return null;
    }
    const content = await fs3.readFile(filePath, "utf-8");
    return content;
  } catch (error) {
    void logger.error("Failed to read migration", { path: migrationPath, error });
    return null;
  }
}
async function getSectionHeaders(migrationPath) {
  const content = await readMigrationContent(migrationPath);
  if (!content) return [];
  const sections = parseSections(content);
  return sections.map((s) => ({ title: s.title, level: s.level }));
}
async function getSections(migrationPath, sectionTitles) {
  const content = await readMigrationContent(migrationPath);
  if (!content) {
    const availableMigrations = await discoverMigrations(migrationsBaseDir);
    const paths = availableMigrations.filter((m) => m.type === "file").map((m) => `- ${m.path}`);
    return `Migration "${migrationPath}" not found.

Available migrations:
${paths.join("\n")}`;
  }
  if (!sectionTitles || sectionTitles.length === 0) {
    return content;
  }
  const sections = parseSections(content);
  const requestedSections = sections.filter(
    (s) => sectionTitles.some((title) => s.title.toLowerCase().includes(title.toLowerCase()))
  );
  if (requestedSections.length === 0) {
    const availableHeaders = sections.map((s) => `${"#".repeat(s.level)} ${s.title}`).join("\n");
    return `Requested sections not found in "${migrationPath}".

Available sections:
${availableHeaders}`;
  }
  return requestedSections.map((s) => s.content).join("\n---\n\n");
}
var initialMigrations = await discoverMigrations(migrationsBaseDir);
var migrationFiles = initialMigrations.filter((m) => m.type === "file");
var migrationsListing = migrationFiles.length > 0 ? "\n\nExample migration paths:\n" + migrationFiles.slice(0, 5).map((m) => `- ${m.path}`).join("\n") + "\n..." : "\n\nNo migrations available. Run the documentation preparation script first.";
var migrationInputSchema = z.object({
  path: z.string().optional().describe(
    'Path to the migration guide (e.g., "upgrade-to-v1/agent", "agentnetwork"). If not provided, lists all available migrations.' + migrationsListing
  ),
  sections: z.array(z.string()).optional().describe(
    "Specific section titles to fetch from the migration guide. If not provided, returns the entire guide. Use this after exploring section headers."
  ),
  listSections: z.boolean().optional().describe("Set to true to list all section headers in a migration guide without fetching full content."),
  queryKeywords: z.array(z.string()).optional().describe("Keywords to search across all migration guides. Use this to find guides related to specific topics.")
});
var migrationTool = {
  name: "mastraMigration",
  description: `[\u{1F310} REMOTE] Get migration guidance for Mastra version upgrades and breaking changes.

This tool works like a file browser - navigate through directories to find migration guides:

**Step 1: List top-level migrations**
- Call with no parameters: \`{}\`
- Shows all top-level migration guides and directories

**Step 2: Navigate into a directory**
- Add trailing slash to explore: \`{ path: "upgrade-to-v1/" }\`
- Lists all migration guides in that directory

**Step 3: View a migration guide**
- Without trailing slash: \`{ path: "upgrade-to-v1/agent" }\`
- Returns the full migration guide content

**Step 4: Explore guide sections (optional)**
- List sections: \`{ path: "upgrade-to-v1/agent", listSections: true }\`
- Get specific sections: \`{ path: "upgrade-to-v1/agent", sections: ["Voice methods"] }\`

**Alternative: Search by keywords**
- \`{ queryKeywords: ["RuntimeContext", "pagination"] }\`

**Examples:**
1. List top-level: \`{}\`
2. Navigate to upgrade-to-v1: \`{ path: "upgrade-to-v1/" }\`
3. Get agent guide: \`{ path: "upgrade-to-v1/agent" }\`
4. List guide sections: \`{ path: "upgrade-to-v1/agent", listSections: true }\`
5. Search: \`{ queryKeywords: ["RuntimeContext"] }\`

**Tip:** Paths ending with \`/\` list directory contents. Paths without \`/\` fetch the migration guide.`,
  parameters: migrationInputSchema,
  execute: async (args) => {
    void logger.debug("Executing mastraMigration tool", { args });
    try {
      if (args.queryKeywords && args.queryKeywords.length > 0) {
        const suggestions = await getMatchingPaths("", args.queryKeywords, migrationsBaseDir);
        return [
          "# Migration Guide Search Results",
          "",
          suggestions || "No migration guides found matching your keywords.",
          "",
          "---",
          "",
          "To see all available migrations, call with no parameters."
        ].join("\n");
      }
      if (args.path) {
        if (args.path.endsWith("/")) {
          const dirPath = args.path.slice(0, -1);
          return await listDirectoryContents(dirPath);
        }
        if (args.listSections) {
          const headers = await getSectionHeaders(args.path);
          if (headers.length === 0) {
            return await listDirectoryContents();
          }
          return [
            `# ${args.path} - Section Headers`,
            "",
            "Available sections in this migration guide:",
            "",
            ...headers.map((h) => `${"#".repeat(h.level)} ${h.title}`),
            "",
            "---",
            "",
            'To get specific sections, provide their titles in the "sections" parameter.'
          ].join("\n");
        }
        const content = await getSections(args.path, args.sections);
        return `# ${args.path}

${content}`;
      }
      return await listDirectoryContents();
    } catch (error) {
      void logger.error("Failed to execute mastraMigration tool", error);
      throw error;
    }
  }
};

// src/index.ts
var server;
server = new MCPServer({
  name: "Mastra Documentation Server",
  version: JSON.parse(await fs3.readFile(fromPackageRoot(`package.json`), "utf8")).version,
  tools: {
    mastraDocs: docsTool,
    mastraMigration: migrationTool,
    startMastraCourse,
    getMastraCourseStatus,
    startMastraCourseLesson,
    nextMastraCourseStep,
    clearMastraCourseHistory,
    // Embedded docs tools for reading docs from installed packages
    ...embeddedDocsTools
  },
  prompts: migrationPromptMessages
});
Object.assign(logger, createLogger(server));
async function runServer() {
  try {
    await server.startStdio();
    void logger.info("Started Mastra Docs MCP Server");
  } catch (error) {
    void logger.error("Failed to start server", error);
    process.exit(1);
  }
}

// src/stdio.ts
function parseLogLevel() {
  const args = process.argv.slice(2);
  const logLevelIndex = args.indexOf("--log-level");
  if (logLevelIndex === -1 || logLevelIndex === args.length - 1) {
    return void 0;
  }
  const level = args[logLevelIndex + 1];
  const validLevels = ["debug", "info", "warn", "error", "none"];
  if (validLevels.includes(level)) {
    return level;
  }
  console.error(`Invalid log level: ${level}. Valid levels: ${validLevels.join(", ")}`);
  return void 0;
}
var logLevel = parseLogLevel();
if (logLevel) {
  setLogLevel(logLevel);
}
runServer().catch((error) => {
  const errorMessage = "Fatal error running server";
  console.error(errorMessage, error);
  writeErrorLog(errorMessage, {
    error: error instanceof Error ? {
      message: error.message,
      stack: error.stack,
      name: error.name
    } : error
  });
  process.exit(1);
});
//# sourceMappingURL=stdio.js.map
//# sourceMappingURL=stdio.js.map