@mastra/mcp-docs-server 1.1.13 โ 1.1.14-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/docs/deployment/studio.md +9 -24
- package/.docs/docs/getting-started/studio.md +28 -16
- package/.docs/docs/observability/tracing/exporters/braintrust.md +15 -0
- package/.docs/docs/server/auth.md +6 -7
- package/.docs/docs/server/custom-api-routes.md +56 -0
- package/.docs/docs/server/mastra-server.md +2 -2
- package/.docs/guides/deployment/cloudflare.md +1 -1
- package/.docs/models/gateways/openrouter.md +4 -1
- package/.docs/models/gateways/vercel.md +7 -1
- package/.docs/models/index.md +1 -1
- package/.docs/models/providers/anthropic.md +2 -2
- package/.docs/models/providers/baseten.md +12 -13
- package/.docs/models/providers/chutes.md +5 -5
- package/.docs/models/providers/deepinfra.md +30 -23
- package/.docs/models/providers/google.md +1 -1
- package/.docs/models/providers/kilo.md +342 -272
- package/.docs/models/providers/nano-gpt.md +36 -36
- package/.docs/models/providers/nebius.md +3 -2
- package/.docs/models/providers/perplexity-agent.md +19 -18
- package/.docs/models/providers/synthetic.md +1 -1
- package/.docs/models/providers/vultr.md +17 -12
- package/.docs/models/providers/zai-coding-plan.md +3 -2
- package/.docs/models/providers/zai.md +3 -2
- package/.docs/reference/agents/generate.md +2 -0
- package/.docs/reference/agents/network.md +2 -0
- package/.docs/reference/ai-sdk/chat-route.md +4 -0
- package/.docs/reference/configuration.md +4 -2
- package/.docs/reference/deployer/cloudflare.md +12 -1
- package/.docs/reference/processors/unicode-normalizer.md +1 -1
- package/.docs/reference/streaming/agents/stream.md +2 -0
- package/.docs/reference/workflows/run-methods/restart.md +2 -0
- package/.docs/reference/workflows/run-methods/resume.md +2 -0
- package/.docs/reference/workflows/run-methods/start.md +2 -0
- package/.docs/reference/workflows/run-methods/timeTravel.md +2 -0
- package/CHANGELOG.md +15 -0
- package/dist/prompts/migration.d.ts.map +1 -1
- package/dist/stdio.js.map +1 -1
- package/package.json +8 -8
package/dist/stdio.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/logger.ts","../src/prompts/migration.ts","../src/utils.ts","../src/tools/course.ts","../src/tools/docs.ts","../src/tools/embedded-docs.ts","../src/tools/migration.ts","../src/index.ts","../src/stdio.ts"],"names":["path","os","server","__dirname","fs","mkdirSync","content","availablePaths","z","exports"],"mappings":";;;;;;;;;;;;;AAUA,IAAM,kBAAA,GAA+C;AAAA,EACnD,KAAA,EAAO,CAAA;AAAA,EACP,IAAA,EAAM,CAAA;AAAA,EACN,IAAA,EAAM,CAAA;AAAA,EACN,KAAA,EAAO,CAAA;AAAA,EACP,IAAA,EAAM;AAAA;AACR,CAAA;AAGA,SAAS,cAAc,KAAA,EAA+B;AACpD,EAAA,QAAQ,KAAA;AAAO,IACb,KAAK,OAAA;AACH,MAAA,OAAO,OAAA;AAAA,IACT,KAAK,MAAA;AAAA,IACL,KAAK,QAAA;AACH,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,OAAA;AAAA,IACL,KAAK,UAAA;AAAA,IACL,KAAK,OAAA;AAAA,IACL,KAAK,WAAA;AACH,MAAA,OAAO,OAAA;AAAA,IACT;AACE,MAAA,OAAO,MAAA;AAAA;AAEb;AAGA,IAAI,eAAA,GAA4B,OAAA;AAEzB,SAAS,YAAY,KAAA,EAAuB;AACjD,EAAA,eAAA,GAAkB,KAAA;AACpB;AAOA,SAAS,UAAU,KAAA,EAA8B;AAC/C,EAAA,MAAM,WAAA,GAAc,cAAc,KAAK,CAAA;AACvC,EAAA,OAAO,kBAAA,CAAmB,WAAW,CAAA,IAAK,kBAAA,CAAmB,eAAe,CAAA;AAC9E;AAcO,IAAM,aAAA,GAAgB,CAAC,OAAA,EAAiB,IAAA,KAAe;AAC5D,EAAA,MAAM,GAAA,uBAAU,IAAA,EAAK;AACrB,EAAA,MAAM,SAAA,GAAY,IAA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,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"stdio.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { MCPServer } from '@mastra/mcp';\nimport type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js';\n\n// Simplified log levels matching MCP client (debug, info, warn, error, none)\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\n// Priority map for log level filtering (higher = more severe)\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4, // none = disable all logs\n};\n\n// Map MCP LoggingLevel to our simplified LogLevel\nfunction mapToLogLevel(level: LoggingLevel): LogLevel {\n switch (level) {\n case 'debug':\n return 'debug';\n case 'info':\n case 'notice':\n return 'info';\n case 'warning':\n return 'warn';\n case 'error':\n case 'critical':\n case 'alert':\n case 'emergency':\n return 'error';\n default:\n return 'info';\n }\n}\n\n// Current log level (default: debug = show all)\nlet currentLogLevel: LogLevel = 'debug';\n\nexport function setLogLevel(level: LogLevel): void {\n currentLogLevel = level;\n}\n\nexport function getLogLevel(): LogLevel {\n return currentLogLevel;\n}\n\n// Check if a log level should be shown based on current minimum level\nfunction shouldLog(level: LoggingLevel): boolean {\n const mappedLevel = mapToLogLevel(level);\n return LOG_LEVEL_PRIORITY[mappedLevel] >= LOG_LEVEL_PRIORITY[currentLogLevel];\n}\n\n// Logger interface for type safety\nexport interface Logger {\n debug: (message: string, data?: any) => Promise<void>;\n info: (message: string, data?: any) => Promise<void>;\n notice: (message: string, data?: any) => Promise<void>;\n warning: (message: string, data?: any) => Promise<void>;\n error: (message: string, error?: any) => Promise<void>;\n critical: (message: string, error?: any) => Promise<void>;\n alert: (message: string, error?: any) => Promise<void>;\n emergency: (message: string, error?: any) => Promise<void>;\n}\n\nexport const writeErrorLog = (message: string, data?: any) => {\n const now = new Date();\n const timestamp = now.toISOString();\n const hourTimestamp = timestamp.slice(0, 13); // YYYY-MM-DDTHH\n\n // Create log message\n const logMessage = {\n timestamp,\n message,\n ...(data ? (typeof data === 'object' ? data : { data }) : {}),\n };\n\n // Write to file\n try {\n // Ensure cache directory exists\n const cacheDir = path.join(os.homedir(), '.cache', 'mastra', 'mcp-docs-server-logs');\n fs.mkdirSync(cacheDir, { recursive: true });\n\n // Create log file path with timestamp\n const logFile = path.join(cacheDir, `${hourTimestamp}.log`);\n\n // Append log entry to file\n fs.appendFileSync(logFile, JSON.stringify(logMessage) + '\\n', 'utf8');\n } catch (err) {\n // If file writing fails, at least we still have stdout\n console.error('Failed to write to log file:', err);\n }\n};\n\n// Create logger factory to inject server instance\nexport function createLogger(server?: MCPServer): Logger {\n const sendLog = async (level: LoggingLevel, message: string, data?: any) => {\n if (!server) return;\n if (!shouldLog(level)) return;\n\n try {\n const sdkServer = server.getServer();\n if (!sdkServer) return;\n await sdkServer.sendLoggingMessage({\n level,\n data: {\n message,\n ...(data ? (typeof data === 'object' ? data : { data }) : {}),\n },\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message === 'Not connected' ||\n error.message.includes('does not support logging') ||\n error.message.includes('Connection closed'))\n ) {\n return;\n }\n console.error(`Failed to send ${level} log:`, error instanceof Error ? error.message : error);\n }\n };\n\n return {\n debug: async (message: string, data?: any) => {\n if (process.env.DEBUG || process.env.NODE_ENV === 'development') {\n await sendLog('debug', message, data);\n }\n },\n info: async (message: string, data?: any) => {\n await sendLog('info', message, data);\n },\n notice: async (message: string, data?: any) => {\n await sendLog('notice', message, data);\n },\n warning: async (message: string, data?: any) => {\n await sendLog('warning', message, data);\n },\n error: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('error', message, errorData);\n },\n critical: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('critical', message, errorData);\n },\n alert: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('alert', message, errorData);\n },\n emergency: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('emergency', message, errorData);\n },\n };\n}\n\n// Create a default logger instance\nexport const logger = createLogger();\n","import type { MCPServerPrompts } from '@mastra/mcp';\nimport type { Prompt, PromptMessage } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * Migration prompts provide guided workflows for upgrading Mastra versions.\n * These prompts help users systematically work through breaking changes.\n */\nconst migrationPrompts: Prompt[] = [\n {\n name: 'upgrade-to-v1',\n version: 'v1',\n description:\n 'Get a guided migration plan for upgrading from Mastra v0.x to v1.0. Provides step-by-step instructions for handling all breaking changes.',\n arguments: [\n {\n name: 'area',\n description:\n '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.',\n required: false,\n },\n ],\n },\n {\n name: 'migration-checklist',\n version: 'v1',\n description:\n 'Get a comprehensive checklist for migrating to Mastra v1.0. Lists all breaking changes that need to be addressed.',\n },\n];\n\n/**\n * Prompt messages callback that generates contextual migration guidance\n */\nexport const migrationPromptMessages: MCPServerPrompts = {\n listPrompts: async () => migrationPrompts,\n\n getPromptMessages: async ({ name, args }): Promise<PromptMessage[]> => {\n const prompt = migrationPrompts.find(p => p.name === name);\n if (!prompt) {\n throw new Error(`Prompt not found: ${name}`);\n }\n\n if (name === 'upgrade-to-v1') {\n return getUpgradeToV1Messages(args?.area);\n }\n\n if (name === 'migration-checklist') {\n return getMigrationChecklistMessages();\n }\n\n throw new Error(`No message handler for prompt: ${name}`);\n },\n};\n\n/**\n * Generate messages for the upgrade-to-v1 prompt\n */\nfunction getUpgradeToV1Messages(area?: string): PromptMessage[] {\n if (area) {\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `I need help migrating my Mastra ${area} code from v0.x to v1.0. Use the mastraMigration tool to:\n\n1. If packages aren't already at the 'latest' tag, upgrade packages to the 'latest' tag and do an install of the new packages.\n2. First, try to get the specific migration guide for \"${area}\" using path: \"upgrade-to-v1/${area}\"\n3. If that doesn't exist, try the alternate form (singular/plural):\n - If \"${area}\" ends with 's', try without the 's' (e.g., \"agents\" โ \"agent\")\n - If \"${area}\" doesn't end with 's', try adding 's' (e.g., \"agent\" โ \"agents\")\n4. If the guide exists, walk me through the changes step by step\n5. If neither form exists, list available migration guides in \"upgrade-to-v1/\" and suggest which ones might be relevant to \"${area}\"\n6. 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.`,\n },\n },\n ];\n }\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `I need to migrate my Mastra project from v0.x to v1.0. Use the mastraMigration tool to:\n\n1. If packages aren't already at the 'latest' tag, upgrade packages to the 'latest' tag and do an install of the new packages.\n2. First, list all available migration guides with path: \"upgrade-to-v1/\"\n2. Give me a high-level overview of what changed in each area\n3. Find relevant migration areas to focus on based on my project's codebase and confirm the list with me\n4. 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.\n\nAfter the areas are confirmed, we'll go through each one systematically.`,\n },\n },\n ];\n}\n\n/**\n * Generate messages for the migration-checklist prompt\n */\nfunction getMigrationChecklistMessages(): PromptMessage[] {\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Create a comprehensive migration checklist for upgrading from Mastra v0.x to v1.0. Use the mastraMigration tool to:\n\n1. List all available migration guides (path: \"upgrade-to-v1/\")\n2. For each guide, extract the key breaking changes\n3. Present them as a checklist I can work through\n\nFormat the checklist with:\n- [ ] checkbox items for each breaking change\n- Brief description of what needs to change\n- Reference to the specific migration guide\n\nGroup the checklist by area (Agents, Tools, Workflows, etc.) so I can tackle one area at a time.`,\n },\n },\n ];\n}\n","import fs from 'node:fs/promises';\nimport path, { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst mdFileCache = new Map<string, string[]>();\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nexport function fromRepoRoot(relative: string) {\n return path.resolve(__dirname, `../../../`, relative);\n}\nexport function fromPackageRoot(relative: string) {\n return path.resolve(__dirname, `../`, relative);\n}\n\n// can't use console.log() because it writes to stdout which will interfere with the MCP Stdio protocol\nexport const log = console.error;\n\nasync function* walkMdFiles(dir: string): AsyncGenerator<string> {\n if (mdFileCache.has(dir)) {\n for (const file of mdFileCache.get(dir)!) yield file;\n return;\n }\n const filesInDir: string[] = [];\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n // For directories, recurse and collect all files\n for await (const file of walkMdFiles(fullPath)) {\n filesInDir.push(file);\n yield file;\n }\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // For all .md files, add to collection and yield\n filesInDir.push(fullPath);\n yield fullPath;\n }\n }\n mdFileCache.set(dir, filesInDir);\n}\n\nasync function searchDocumentContent(keywords: string[], baseDir: string): Promise<string[]> {\n if (keywords.length === 0) return [];\n\n const fileScores = new Map<string, FileScore>();\n\n for await (const filePath of walkMdFiles(baseDir)) {\n let content: string;\n try {\n content = await fs.readFile(filePath, 'utf-8');\n } catch {\n continue;\n }\n const lines = content.split('\\n');\n lines.forEach(lineText => {\n const lowerLine = lineText.toLowerCase();\n for (const keyword of keywords) {\n if (lowerLine.includes(keyword.toLowerCase())) {\n const relativePath = path.relative(baseDir, filePath).replace(/\\\\/g, '/');\n if (!fileScores.has(relativePath)) {\n fileScores.set(relativePath, {\n path: relativePath,\n keywordMatches: new Set(),\n totalMatches: 0,\n titleMatches: 0,\n pathRelevance: calculatePathRelevance(relativePath, keywords),\n });\n }\n const score = fileScores.get(relativePath)!;\n score.keywordMatches.add(keyword);\n score.totalMatches++;\n if (lowerLine.includes('#') || lowerLine.includes('title')) {\n score.titleMatches++;\n }\n }\n }\n });\n }\n\n // Filter to only files that contain ALL keywords, then rank\n const validFiles = Array.from(fileScores.values())\n .sort((a, b) => calculateFinalScore(b, keywords.length) - calculateFinalScore(a, keywords.length))\n .slice(0, 10); // Limit to top 10 results\n\n return validFiles.map(score => score.path);\n}\n\ninterface FileScore {\n path: string;\n keywordMatches: Set<string>;\n totalMatches: number;\n titleMatches: number;\n pathRelevance: number;\n}\n\nfunction calculatePathRelevance(filePath: string, keywords: string[]): number {\n let relevance = 0;\n const pathLower = filePath.toLowerCase();\n\n // Boost for reference docs\n if (pathLower.startsWith('reference/')) relevance += 2;\n\n // Boost if path contains any keywords\n keywords.forEach(keyword => {\n if (pathLower.includes(keyword.toLowerCase())) relevance += 3;\n });\n\n // Boost for high-value directories\n const highValueDirs = ['rag', 'memory', 'agents', 'workflows'];\n if (highValueDirs.some(dir => pathLower.includes(dir))) {\n relevance += 1;\n }\n\n return relevance;\n}\n\nfunction calculateFinalScore(score: FileScore, totalKeywords: number): number {\n const allKeywordsBonus = score.keywordMatches.size === totalKeywords ? 10 : 0;\n return (\n score.totalMatches * 1 +\n score.titleMatches * 3 +\n score.pathRelevance * 2 +\n score.keywordMatches.size * 5 +\n allKeywordsBonus // All keywords bonus\n );\n}\n\nfunction extractKeywordsFromPath(docPath: string): string[] {\n // Get the file/folder name (last meaningful part of the path, excluding .md extension)\n const cleanPath = docPath.replace(/\\.md$/, '');\n const fileName = cleanPath.split('/').pop() || '';\n\n const keywords = new Set<string>();\n\n // Split on hyphens, underscores, camelCase\n const splitParts = fileName.split(/[-_]|(?=[A-Z])/);\n splitParts.forEach(keyword => {\n if (keyword.length > 2) {\n keywords.add(keyword.toLowerCase());\n }\n });\n\n return Array.from(keywords);\n}\n\nfunction normalizeKeywords(keywords: string[]): string[] {\n return Array.from(new Set(keywords.flatMap(k => k.split(/\\s+/).filter(Boolean)).map(k => k.toLowerCase())));\n}\n\nexport async function getMatchingPaths(path: string, queryKeywords: string[], baseDir: string): Promise<string> {\n const pathKeywords = extractKeywordsFromPath(path);\n const allKeywords = normalizeKeywords([...pathKeywords, ...(queryKeywords || [])]);\n\n if (allKeywords.length === 0) {\n return '';\n }\n\n const suggestedPaths = await searchDocumentContent(allKeywords, baseDir);\n if (suggestedPaths.length === 0) {\n return '';\n }\n\n const pathList = suggestedPaths.map(path => `- ${path}`).join('\\n');\n return `Here are some paths that might be relevant based on your query:\\n\\n${pathList}`;\n}\n","import { existsSync, mkdirSync } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport http from 'node:http';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { fromPackageRoot } from '../utils';\n\n// Prefix with underscore since it's only used as a type\nconst _courseLessonSchema = z.object({\n lessonName: z.string().describe('Name of the specific lesson to start. It must match the exact lesson name.'),\n});\n\nconst _confirmationSchema = z.object({\n confirm: z.boolean().optional().describe('Set to true to confirm this action'),\n});\n\n// Define the CourseState type directly\ntype CourseState = {\n currentLesson: string;\n lessons: Array<{\n name: string;\n status: number; // 0 = not started, 1 = in progress, 2 = completed\n steps: Array<{\n name: string;\n status: number; // 0 = not started, 1 = in progress, 2 = completed\n }>;\n }>;\n};\n\nconst courseDir = fromPackageRoot('.docs/course');\n\n// Define the introduction prompt shown only when a user registers for the course\nconst introductionPrompt = `\nThis is a course to help a new user learn about Mastra, the open-source AI Agent framework built in TypeScript.\nThe following is the introduction content, please provide this text to the user EXACTLY as written below. Do not provide any other text or instructions:\n\n# Welcome to the Mastra Course!\n\nThank 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.\n\n## Before We Begin\n\nIf you enjoy Mastra, please consider starring the GitHub repository:\nhttps://github.com/mastra-ai/mastra\n\nThis helps the project grow and reach more developers like you!\n\n## How This Course Works\n\n- Each lesson is broken into multiple steps\n- I'll guide you through the code examples and explanations\n- You can ask questions at any time\n- 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\".\n- 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.\n- Use the \\`getMastraCourseStatus\\` tool to check your progress. You can just ask \"get my course progress\".\n- Use the \\`clearMastraCourseHistory\\` tool to reset your progress and start over. You can just ask \"clear my course progress\".\n\nType \"start mastra course\" and let's get started with your first lesson!\n`;\n\n// Define the prompt that wraps each lesson step\nconst lessonPrompt = `\n This is a course to help a new user learn about Mastra, the open-source AI Agent framework built in TypeScript.\n Please help the user through the steps of the course by walking them through the content and following the course\n 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\n as the course goes on. Each lesson is broken up into steps. You should return the content of the step and ask the user\n to move to the next step when they are ready. If the step contains instructions to write code, you should write the code\n for the user when possible. You should always briefly explain the step before writing the code. Please ensure to \n 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.\n`;\n\n// Define the prompt wrapper for each course step\nfunction wrapContentInPrompt(content: string, _isFirstStep: boolean = false): string {\n let wrappedContent = `${lessonPrompt}\\n\\nHere is the content for this step: <StepContent>${content}</StepContent>`;\n return `${wrappedContent}\\n\\nWhen you're ready to continue, use the \\`nextMastraCourseStep\\` tool to move to the next step.`;\n}\n\n// Get the path to the device ID file\nasync function getDeviceIdPath(): Promise<string> {\n const cacheDir = path.join(os.homedir(), '.cache', 'mastra');\n\n // Create the directory if it doesn't exist\n if (!existsSync(cacheDir)) {\n mkdirSync(cacheDir, { recursive: true });\n }\n\n return path.join(cacheDir, '.device_id');\n}\n\n// Get the device credentials (deviceId and key) if the user is registered\nasync function getDeviceCredentials(): Promise<{ deviceId: string; key: string } | null> {\n try {\n const deviceIdPath = await getDeviceIdPath();\n if (!existsSync(deviceIdPath)) {\n return null;\n }\n const fileContent = await fs.readFile(deviceIdPath, 'utf-8');\n const parsed = JSON.parse(fileContent);\n if (typeof parsed.deviceId === 'string' && typeof parsed.key === 'string') {\n return { deviceId: parsed.deviceId, key: parsed.key };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nasync function getDeviceId(): Promise<string | null> {\n const creds = await getDeviceCredentials();\n\n if (!creds || !creds?.deviceId) {\n return null;\n }\n\n return creds.deviceId;\n}\n\n// Save the device credentials (deviceId and key)\nasync function saveDeviceCredentials(deviceId: string, key: string): Promise<void> {\n const deviceIdPath = await getDeviceIdPath();\n const toWrite = JSON.stringify({ deviceId, key });\n await fs.writeFile(deviceIdPath, toWrite, 'utf-8');\n // Set file permissions to 600 (read/write for owner only)\n await fs.chmod(deviceIdPath, 0o600);\n}\n\n// Make an HTTP request to register the user\nexport function registerUserLocally(\n email: string,\n): Promise<{ success: boolean; id: string; key: string; message: string }> {\n return new Promise((resolve, reject) => {\n const data = JSON.stringify({\n email,\n });\n const options = {\n hostname: 'localhost',\n port: 3000,\n path: '/api/course/register',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': data.length,\n },\n };\n const req = http.request(options, res => {\n let responseData = '';\n res.on('data', chunk => {\n responseData += chunk;\n });\n res.on('end', () => {\n try {\n const parsedData = JSON.parse(responseData);\n resolve(parsedData);\n } catch (error) {\n reject(new Error(`Failed to parse response: ${error}`));\n }\n });\n });\n req.on('error', error => {\n reject(error);\n });\n req.write(data);\n req.end();\n });\n}\n\nasync function registerUser(email: string): Promise<{ success: boolean; id: string; key: string; message: string }> {\n const response = await fetch('https://mastra.ai/api/course/register', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email }),\n });\n\n if (!response.ok) {\n throw new Error(`Registration failed with status ${response.status}: ${response.statusText}`);\n }\n\n return response.json();\n}\n\nasync function readCourseStep(lessonName: string, stepName: string, _isFirstStep: boolean = false): Promise<string> {\n // Find the lesson directory that matches the name\n const lessonDirs = await fs.readdir(courseDir);\n const lessonDir = lessonDirs.find(dir => dir.replace(/^\\d+-/, '') === lessonName);\n\n if (!lessonDir) {\n throw new Error(`Lesson \"${lessonName}\" not found.`);\n }\n\n // Find the step file that matches the name\n const lessonPath = path.join(courseDir, lessonDir);\n const files = await fs.readdir(lessonPath);\n const stepFile = files.find(f => f.endsWith('.md') && f.replace(/^\\d+-/, '').replace('.md', '') === stepName);\n\n if (!stepFile) {\n throw new Error(`Step \"${stepName}\" not found in lesson \"${lessonName}\".`);\n }\n\n const filePath = path.join(courseDir, lessonDir, stepFile);\n\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return wrapContentInPrompt(content);\n } catch (error) {\n throw new Error(`Failed to read step \"${stepName}\" in lesson \"${lessonName}\": ${error}`);\n }\n}\n\n// Create a function to update course state on the local server\nexport function updateCourseStateOnServerLocally(deviceId: string, state: CourseState): Promise<void> {\n return new Promise(async (resolve, reject) => {\n try {\n const creds = await getDeviceCredentials();\n if (!creds) {\n return reject(new Error('Device credentials not found.'));\n }\n const data = JSON.stringify({\n id: creds.deviceId,\n state: state,\n });\n const options = {\n hostname: 'localhost',\n port: 3000,\n path: '/api/course/update',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': data.length,\n 'x-mastra-course-key': creds.key,\n },\n };\n const req = http.request(options, res => {\n let responseData = '';\n res.on('data', chunk => {\n responseData += chunk;\n });\n res.on('end', () => {\n try {\n if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {\n resolve();\n } else {\n reject(new Error(`Server returned status code ${res.statusCode}: ${responseData}`));\n }\n } catch (error) {\n reject(new Error(`Failed to parse response: ${error}`));\n }\n });\n });\n req.on('error', error => {\n reject(error);\n });\n req.write(data);\n req.end();\n } catch (err) {\n reject(err);\n }\n });\n}\n\n// Create a function to update course state on the server\nasync function updateCourseStateOnServer(deviceId: string, state: CourseState): Promise<void> {\n const creds = await getDeviceCredentials();\n if (!creds) {\n throw new Error('Device credentials not found.');\n }\n\n const response = await fetch('https://mastra.ai/api/course/update', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-mastra-course-key': creds.key,\n },\n body: JSON.stringify({\n id: creds.deviceId,\n state: state,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Course state update failed with status ${response.status}: ${response.statusText}`);\n }\n}\n\nasync function saveCourseState(state: CourseState, deviceId: string | null): Promise<void> {\n // If no device ID, the user isn't registered - this is an error condition\n if (!deviceId) {\n throw new Error('Cannot save course state: User is not registered');\n }\n const statePath = await getCourseStatePath();\n try {\n // Save to local filesystem\n await fs.writeFile(statePath, JSON.stringify(state, null, 2), 'utf-8');\n // Sync with server\n try {\n // Use getDeviceCredentials to ensure we have the key\n const creds = await getDeviceCredentials();\n if (!creds) throw new Error('Device credentials not found');\n await updateCourseStateOnServer(creds.deviceId, state);\n } catch {\n // Silently continue if server sync fails\n // Local save is still successful\n }\n } catch (error) {\n throw new Error(`Failed to save course state: ${error}`);\n }\n}\n\n// Get the path to the course state file\nasync function getCourseStatePath(): Promise<string> {\n const stateDirPath = path.join(os.homedir(), '.cache', 'mastra', 'course');\n\n // Ensure the directory exists\n if (!existsSync(stateDirPath)) {\n mkdirSync(stateDirPath, { recursive: true });\n }\n\n return path.join(stateDirPath, 'state.json');\n}\n\nasync function loadCourseState(): Promise<CourseState | null> {\n const statePath = await getCourseStatePath();\n\n try {\n if (existsSync(statePath)) {\n const stateData = await fs.readFile(statePath, 'utf-8');\n return JSON.parse(stateData) as CourseState;\n }\n } catch (error) {\n throw new Error(`Failed to load course state: ${error}`);\n }\n\n return null;\n}\n\nasync function scanCourseContent(): Promise<CourseState> {\n // Scan the course directory to build a fresh state\n const lessonDirs = await fs.readdir(courseDir);\n\n const lessons = await Promise.all(\n lessonDirs\n .filter(dir => !dir.startsWith('.')) // Skip hidden directories\n .sort((a, b) => a.localeCompare(b))\n .map(async lessonDir => {\n const lessonPath = path.join(courseDir, lessonDir);\n const lessonStats = await fs.stat(lessonPath);\n\n if (!lessonStats.isDirectory()) return null;\n\n // Extract lesson name from directory (remove numbering prefix)\n const lessonName = lessonDir.replace(/^\\d+-/, '');\n\n // Get all markdown files in the lesson directory\n const stepFiles = (await fs.readdir(lessonPath))\n .filter(file => file.endsWith('.md'))\n .sort((a, b) => a.localeCompare(b));\n\n // Build steps array\n const steps = await Promise.all(\n stepFiles.map(async file => {\n // Extract step name from filename (remove numbering prefix)\n const stepName = file.replace(/^\\d+-/, '').replace('.md', '');\n\n return {\n name: stepName,\n status: 0, // Default: not started\n };\n }),\n );\n\n return {\n name: lessonName,\n status: 0, // Default: not started\n steps: steps.filter(Boolean),\n };\n }),\n );\n\n // Filter out null values and create the state\n const validLessons = lessons.filter((lesson): lesson is NonNullable<typeof lesson> => lesson !== null);\n\n return {\n currentLesson: validLessons.length > 0 ? (validLessons[0]?.name ?? '') : '',\n lessons: validLessons,\n };\n}\n\nasync function mergeCourseStates(currentState: CourseState, newState: CourseState): Promise<CourseState> {\n // Create a map of existing lessons by name for easy lookup\n const existingLessonMap = new Map(currentState.lessons.map(lesson => [lesson.name, lesson]));\n\n // Merge the states, preserving progress where possible\n const mergedLessons = newState.lessons.map(newLesson => {\n const existingLesson = existingLessonMap.get(newLesson.name);\n\n if (!existingLesson) {\n // This is a new lesson\n return newLesson;\n }\n\n // Create a map of existing steps by name\n const existingStepMap = new Map(existingLesson.steps.map(step => [step.name, step]));\n\n // Merge steps, preserving progress for existing steps\n const mergedSteps = newLesson.steps.map(newStep => {\n const existingStep = existingStepMap.get(newStep.name);\n\n if (existingStep) {\n // Preserve the status from the existing step\n return {\n ...newStep,\n status: existingStep.status,\n };\n }\n\n return newStep;\n });\n\n // Calculate lesson status based on steps\n let lessonStatus = existingLesson.status;\n if (mergedSteps.every(step => step.status === 2)) {\n lessonStatus = 2; // Completed\n } else if (mergedSteps.some(step => step.status > 0)) {\n lessonStatus = 1; // In progress\n }\n\n return {\n ...newLesson,\n status: lessonStatus,\n steps: mergedSteps,\n };\n });\n\n // Determine current lesson\n let currentLesson = currentState.currentLesson;\n\n // If the current lesson doesn't exist in the new state, reset to the first lesson\n if (!mergedLessons.some(lesson => lesson.name === currentLesson) && mergedLessons.length > 0) {\n currentLesson = mergedLessons[0]?.name ?? '';\n }\n\n return {\n currentLesson,\n lessons: mergedLessons,\n };\n}\n\nexport const startMastraCourse = {\n name: 'startMastraCourse',\n description:\n '[๐ 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.',\n parameters: z.object({\n email: z.string().email().optional().describe('Email address for registration if not already registered. '),\n }),\n execute: async (args: { email?: string }) => {\n try {\n // Check if the user is registered\n const creds = await getDeviceCredentials();\n const registered = creds !== null;\n let deviceId = creds?.deviceId ?? null;\n if (!registered) {\n // If not registered and no email provided, prompt for email\n if (!args.email) {\n 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.';\n }\n\n // User provided email, register them\n try {\n const response = await registerUser(args.email);\n\n if (response.success) {\n // Save both deviceId and key\n await saveDeviceCredentials(response.id, response.key);\n deviceId = response.id;\n } else {\n return `Registration failed: ${response.message}. Please try again with a valid email address.`;\n }\n } catch (error) {\n return `Failed to register: ${error instanceof Error ? error.message : String(error)}. Please try again later.`;\n }\n }\n\n // Try to load the user's course progress\n let courseState = await loadCourseState();\n let statusMessage = '';\n\n // Get the latest course content structure\n const latestCourseState = await scanCourseContent();\n\n if (!latestCourseState.lessons.length) {\n return 'No course content found. Please make sure the course content is properly set up in the .docs/course/lessons directory.';\n }\n\n if (courseState) {\n // User has existing progress, merge with latest content\n const previousState = JSON.parse(JSON.stringify(courseState)) as CourseState; // Deep clone for comparison\n courseState = await mergeCourseStates(courseState, latestCourseState);\n\n // Check if there are differences in the course structure\n const newLessons = latestCourseState.lessons.filter(\n newLesson => !previousState.lessons.some((oldLesson: { name: string }) => oldLesson.name === newLesson.name),\n );\n\n if (newLessons.length > 0) {\n statusMessage = `๐ Course content has been updated! ${newLessons.length} new lesson(s) have been added:\\n`;\n statusMessage += newLessons.map(lesson => `- ${lesson.name}`).join('\\n');\n statusMessage += '\\n\\n';\n }\n\n // Save the merged state\n await saveCourseState(courseState, deviceId);\n } else {\n // First time user, create new state\n courseState = latestCourseState;\n await saveCourseState(courseState, deviceId);\n\n // Check if this is a new registration\n if (!registered && args.email) {\n // Just return the introduction prompt.\n return introductionPrompt;\n }\n }\n\n // Find the current lesson and step\n const currentLessonName = courseState.currentLesson;\n const currentLesson = courseState.lessons.find(lesson => lesson.name === currentLessonName);\n\n if (!currentLesson) {\n return 'Error: Current lesson not found in course content. Please try again or reset your course progress.';\n }\n\n // Find the first incomplete step in the current lesson\n const currentStep = currentLesson.steps.find(step => step.status !== 2);\n\n if (!currentStep && currentLesson.status !== 2) {\n // Mark the lesson as completed if all steps are done\n currentLesson.status = 2;\n await saveCourseState(courseState, deviceId);\n\n // Find the next lesson that's not completed\n const nextLesson = courseState.lessons.find(lesson => lesson.status !== 2 && lesson.name !== currentLessonName);\n\n if (nextLesson) {\n courseState.currentLesson = nextLesson.name;\n await saveCourseState(courseState, deviceId);\n\n return `${statusMessage}๐ You've completed the \"${currentLessonName}\" lesson!\\n\\nMoving on to the next lesson: \"${nextLesson.name}\".\\n\\nUse the \\`nextMastraCourseStep\\` tool to start the first step of this lesson.`;\n } else {\n return `${statusMessage}๐ Congratulations! You've completed all available lessons in the Mastra Course!\\n\\nIf you'd like to review any lesson, use the \\`startMastraCourseLesson\\` tool with the lesson name.`;\n }\n }\n\n if (!currentStep) {\n // This should not happen, but just in case\n return `${statusMessage}Error: No incomplete steps found in the current lesson. Please try another lesson or reset your course progress.`;\n }\n\n // Mark the step as in progress\n currentStep.status = 1;\n\n // If the lesson is not in progress, mark it as in progress\n if (currentLesson.status === 0) {\n currentLesson.status = 1;\n }\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the current step\n const stepContent = await readCourseStep(currentLessonName, currentStep.name);\n\n return `๐ Lesson: ${currentLessonName}\\n๐ Step: ${currentStep.name}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n } catch (error) {\n return `Error starting the Mastra course: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const getMastraCourseStatus = {\n name: 'getMastraCourseStatus',\n description:\n '[๐ COURSE] Gets the current status of the Mastra Course, including which lessons and steps have been completed',\n parameters: z.object({}),\n execute: async (_args: Record<string, never>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Load the course state\n const courseState = await loadCourseState();\n\n if (!courseState) {\n return 'No course progress found. Please start the course first using the `startMastraCourse` tool.';\n }\n\n // Get the latest course content structure to ensure we have the most up-to-date information\n const latestCourseState = await scanCourseContent();\n\n if (!latestCourseState.lessons.length) {\n return 'No course content found. Please make sure the course content is properly set up in the .docs/course/lessons directory.';\n }\n\n // Merge the states to ensure we have the latest content with the user's progress\n const mergedState = await mergeCourseStates(courseState, latestCourseState);\n\n // Build a formatted status report\n let statusReport = '# Mastra Course Progress\\n\\n';\n\n // Add overall progress stats\n const totalLessons = mergedState.lessons.length;\n const completedLessons = mergedState.lessons.filter(lesson => lesson.status === 2).length;\n const _inProgressLessons = mergedState.lessons.filter(lesson => lesson.status === 1).length;\n\n const totalSteps = mergedState.lessons.reduce((sum, lesson) => sum + lesson.steps.length, 0);\n const completedSteps = mergedState.lessons.reduce(\n (sum, lesson) => sum + lesson.steps.filter(step => step.status === 2).length,\n 0,\n );\n\n statusReport += `## Overall Progress\\n`;\n statusReport += `- Course status Url: **https://mastra.ai/course/${deviceId}**\\n`;\n statusReport += `- Current Lesson: **${mergedState.currentLesson}**\\n`;\n statusReport += `- Lessons: ${completedLessons}/${totalLessons} completed (${Math.round((completedLessons / totalLessons) * 100)}%)\\n`;\n statusReport += `- Steps: ${completedSteps}/${totalSteps} completed (${Math.round((completedSteps / totalSteps) * 100)}%)\\n\\n`;\n\n // Add detailed lesson status\n statusReport += `## Lesson Details\\n\\n`;\n\n mergedState.lessons.forEach((lesson, lessonIndex) => {\n // Determine lesson status icon\n let lessonStatusIcon = 'โฌ'; // Not started\n if (lesson.status === 1) lessonStatusIcon = '๐ถ'; // In progress\n if (lesson.status === 2) lessonStatusIcon = 'โ
'; // Completed\n\n // Highlight current lesson\n const isCurrent = lesson.name === mergedState.currentLesson;\n const lessonPrefix = isCurrent ? '๐ ' : '';\n\n statusReport += `### ${lessonPrefix}${lessonIndex + 1}. ${lessonStatusIcon} ${lesson.name}\\n\\n`;\n\n // Add step details\n lesson.steps.forEach((step, stepIndex) => {\n // Determine step status icon\n let stepStatusIcon = 'โฌ'; // Not started\n if (step.status === 1) stepStatusIcon = '๐ถ'; // In progress\n if (step.status === 2) stepStatusIcon = 'โ
'; // Completed\n\n statusReport += `- ${stepStatusIcon} Step ${stepIndex + 1}: ${step.name}\\n`;\n });\n\n statusReport += '\\n';\n });\n\n // Add navigation instructions\n statusReport += `## Navigation\\n\\n`;\n statusReport += `- To continue the course: \\`nextMastraCourseStep\\`\\n`;\n statusReport += `- To start a specific lesson: \\`startMastraCourseLesson\\`\\n`;\n statusReport += `- To reset progress: \\`clearMastraCourseHistory\\`\\n`;\n\n return `Course Status: ${statusReport}\\n\\nCourse status url: https://mastra.ai/course/${deviceId}`;\n } catch (error) {\n return `Error getting course status: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const startMastraCourseLesson = {\n name: 'startMastraCourseLesson',\n description:\n '[๐ COURSE] Starts a specific lesson in the Mastra Course. If the lesson has been started before, it will resume from the first incomplete step',\n parameters: _courseLessonSchema,\n execute: async (args: z.infer<typeof _courseLessonSchema>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Load the current course state\n let courseState = await loadCourseState();\n\n if (!courseState) {\n return 'No course progress found. Please start the course first using the `startMastraCourse` tool.';\n }\n\n // Find the target lesson by name\n const targetLessonName = args.lessonName;\n\n // Find the target lesson\n const targetLesson = courseState.lessons.find(lesson => lesson.name === targetLessonName);\n\n if (!targetLesson) {\n const availableLessons = courseState.lessons.map((lesson, index) => `${index + 1}. ${lesson.name}`).join('\\n');\n return `Lesson \"${targetLessonName}\" not found. Available lessons:\\n${availableLessons}`;\n }\n\n // Update the current lesson in the state\n courseState.currentLesson = targetLesson.name;\n\n // Find the first incomplete step in the lesson, or the first step if all are completed\n const firstIncompleteStep = targetLesson.steps.find(step => step.status !== 2) || targetLesson.steps[0];\n\n if (!firstIncompleteStep) {\n return `The lesson \"${targetLesson.name}\" does not have any steps.`;\n }\n\n // Mark the step as in progress\n firstIncompleteStep.status = 1;\n\n // If the lesson is not in progress or completed, mark it as in progress\n if (targetLesson.status === 0) {\n targetLesson.status = 1;\n }\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the step\n const stepContent = await readCourseStep(targetLesson.name, firstIncompleteStep.name);\n\n return `๐ Starting Lesson: ${targetLesson.name}\\n๐ Step: ${firstIncompleteStep.name}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n } catch (error) {\n return `Error starting course lesson: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const nextMastraCourseStep = {\n name: 'nextMastraCourseStep',\n description:\n '[๐ 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',\n parameters: z.object({}),\n execute: async (_args: Record<string, never>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Load the current course state\n const courseState = await loadCourseState();\n\n if (!courseState) {\n return 'No course progress found. Please start the course first using the `startMastraCourse` tool.';\n }\n\n // Find the current lesson\n const currentLessonName = courseState.currentLesson;\n const currentLesson = courseState.lessons.find(lesson => lesson.name === currentLessonName);\n\n if (!currentLesson) {\n return 'Error: Current lesson not found in course content. Please try again or reset your course progress.';\n }\n\n // Find the current in-progress step\n const currentStepIndex = currentLesson.steps.findIndex(step => step.status === 1);\n\n if (currentStepIndex === -1) {\n return 'No step is currently in progress. Please start a step first using the `startMastraCourse` tool.';\n }\n\n // Mark the current step as completed\n if (currentLesson.steps[currentStepIndex]?.status) {\n currentLesson.steps[currentStepIndex].status = 2; // Completed\n }\n\n // Find the next step in the current lesson\n const nextStepIndex = currentLesson.steps.findIndex(\n (step, index) => index > currentStepIndex && step.status !== 2,\n );\n\n // If there's a next step in the current lesson\n if (nextStepIndex !== -1) {\n // Mark the next step as in progress\n if (currentLesson.steps[nextStepIndex]) {\n currentLesson.steps[nextStepIndex].status = 1; // In progress\n }\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the next step\n const nextStep = currentLesson.steps[nextStepIndex];\n const stepContent = await readCourseStep(currentLessonName, nextStep?.name ?? 'Unknown Step');\n\n return `๐ Step \"${currentLesson.steps[currentStepIndex]?.name ?? 'Unknown Step'}\" completed!\\n\\n๐ Continuing Lesson: ${currentLessonName}\\n๐ Next Step: ${nextStep?.name ?? 'Unknown Step'}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n }\n\n // All steps in the current lesson are completed\n // Mark the lesson as completed\n currentLesson.status = 2; // Completed\n\n // Find the next lesson that's not completed\n const currentLessonIndex = courseState.lessons.findIndex(lesson => lesson.name === currentLessonName);\n const nextLesson = courseState.lessons.find((lesson, index) => index > currentLessonIndex && lesson.status !== 2);\n\n if (nextLesson) {\n // Update the current lesson to the next lesson\n courseState.currentLesson = nextLesson.name;\n\n // Mark the first step of the next lesson as in progress\n if (nextLesson.steps.length > 0 && nextLesson.steps[0]) {\n nextLesson.steps[0].status = 1; // In progress\n }\n\n // Mark the next lesson as in progress\n nextLesson.status = 1; // In progress\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the first step of the next lesson\n const firstStep = nextLesson.steps[0];\n const stepContent = await readCourseStep(nextLesson.name, firstStep?.name ?? 'Unknown Step');\n\n return `๐ Congratulations! You've completed the \"${currentLessonName}\" lesson!\\n\\n๐ Starting New Lesson: ${nextLesson.name}\\n๐ First Step: ${firstStep?.name ?? 'Unknown Step'}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n }\n\n // All lessons are completed\n await saveCourseState(courseState, deviceId);\n\n return `๐ Congratulations! You've completed all available lessons in the Mastra Course!\\n\\nIf you'd like to review any lesson, use the \\`startMastraCourseLesson\\` tool with the lesson name.`;\n } catch (error) {\n return `Error advancing to the next course step: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const clearMastraCourseHistory = {\n name: 'clearMastraCourseHistory',\n description:\n '[๐ COURSE] Clears all Mastra Course progress history and starts over from the beginning. This action cannot be undone',\n parameters: _confirmationSchema,\n execute: async (args: z.infer<typeof _confirmationSchema>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Check if the user has confirmed the action\n if (!args.confirm) {\n return 'โ ๏ธ 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.';\n }\n\n // Get the state file path\n const statePath = await getCourseStatePath();\n\n // Check if the state file exists\n if (!existsSync(statePath)) {\n return 'No course progress found. Nothing to clear.';\n }\n\n // Delete the state file\n await fs.unlink(statePath);\n\n return '๐งน Course progress has been cleared. You can restart the Mastra course from the beginning.';\n } catch (error) {\n return `Error clearing course history: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { logger } from '../logger';\nimport { fromPackageRoot, getMatchingPaths } from '../utils';\n\nconst docsBaseDir = fromPackageRoot('.docs/');\n\ntype ReadDocsResult =\n | { found: true; content: string; isSecurityViolation: boolean }\n | { found: false; isSecurityViolation: boolean };\n\n// Helper function to list contents of a directory\nasync function listDirContents(dirPath: string): Promise<{ dirs: string[]; files: string[] }> {\n try {\n void logger.debug(`Listing directory contents: ${dirPath}`);\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n const dirs: string[] = [];\n const files: string[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n dirs.push(entry.name + '/');\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // List all .md files (remove .md extension for cleaner display)\n files.push(entry.name.replace(/\\.md$/, ''));\n }\n }\n\n return {\n dirs: dirs.sort(),\n files: files.sort(),\n };\n } catch (error) {\n void logger.error(`Failed to list directory contents: ${dirPath}`, error);\n throw error;\n }\n}\n\n// Helper function to read documentation content from a path\nasync function readDocsContent(docPath: string, queryKeywords: string[]): Promise<ReadDocsResult> {\n const fullPath = path.resolve(path.join(docsBaseDir, docPath));\n if (!fullPath.startsWith(path.resolve(docsBaseDir))) {\n void logger.error(`Path traversal attempt detected`);\n return { found: false, isSecurityViolation: true };\n }\n void logger.debug(`Reading docs content from: ${fullPath}`);\n\n // Try multiple approaches to find the content:\n // 1. Try as a direct file path (with .md extension)\n // 2. Try as a directory with index.md\n // 3. Try as a file path by appending .md\n\n try {\n const stats = await fs.stat(fullPath);\n\n if (stats.isDirectory()) {\n // It's a directory - check for index.md (for category roots)\n const indexMdPath = path.join(fullPath, 'index.md');\n try {\n const content = await fs.readFile(indexMdPath, 'utf-8');\n return { found: true, content, isSecurityViolation: false };\n } catch {\n // No index.md, show directory listing\n }\n\n // List directory contents (subdirs and .md files)\n const { dirs, files } = await listDirContents(fullPath);\n const listing: string[] = [`Directory contents of ${docPath || '/'}:`, ''];\n\n if (dirs.length > 0) {\n listing.push('Subdirectories:');\n listing.push(...dirs.map(d => `- ${docPath ? `${docPath}/${d}` : d}`));\n listing.push('');\n }\n\n if (files.length > 0) {\n listing.push('Available documentation paths:');\n listing.push(...files.map(f => `- ${docPath ? `${docPath}/${f}` : f}`));\n listing.push('');\n }\n\n if (dirs.length === 0 && files.length === 0) {\n listing.push('No documentation available in this directory.');\n }\n\n // Add content-based suggestions when query keywords are provided\n const contentBasedSuggestions = await getMatchingPaths(docPath, queryKeywords, docsBaseDir);\n const suggestions = contentBasedSuggestions ? ['---', '', contentBasedSuggestions, ''].join('\\n') : '';\n\n return { found: true, content: listing.join('\\n') + suggestions, isSecurityViolation: false };\n }\n\n // It's a file - read it directly\n const content = await fs.readFile(fullPath, 'utf-8');\n return { found: true, content, isSecurityViolation: false };\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n // Path doesn't exist as-is, try adding .md extension\n try {\n const mdPath = fullPath + '.md';\n const content = await fs.readFile(mdPath, 'utf-8');\n return { found: true, content, isSecurityViolation: false };\n } catch {\n // Still not found\n return { found: false, isSecurityViolation: false };\n }\n }\n // Unexpected error: rethrow\n throw error;\n }\n}\n\n// Helper function to find nearest existing directory and its contents\nasync function findNearestDirectory(docPath: string, availablePaths: string): Promise<string> {\n void logger.debug(`Finding nearest directory for: ${docPath}`);\n // Split path into parts and try each parent directory\n const parts = docPath.split('/');\n\n while (parts.length > 0) {\n const testPath = parts.join('/');\n try {\n const fullPath = path.join(docsBaseDir, testPath);\n const stats = await fs.stat(fullPath);\n\n if (stats.isDirectory()) {\n const { dirs, files } = await listDirContents(fullPath);\n const listing: string[] = [\n `Path \"${docPath}\" not found.`,\n `Here are the available paths in \"${testPath}\":`,\n '',\n ];\n\n if (dirs.length > 0) {\n listing.push('Directories:');\n listing.push(...dirs.map(d => `- ${testPath}/${d}`));\n listing.push('');\n }\n\n if (files.length > 0) {\n listing.push('Files:');\n listing.push(...files.map(f => `- ${testPath}/${f}`));\n }\n\n return listing.join('\\n');\n }\n } catch {\n // Directory doesn't exist, try parent\n void logger.debug(`Directory not found, trying parent: ${parts.slice(0, -1).join('/')}`);\n }\n parts.pop();\n }\n\n // If no parent directories found, return root listing\n return [`Path \"${docPath}\" not found.`, 'Here are all available paths:', '', availablePaths].join('\\n');\n}\n\n// Get initial directory listing for the description\nasync function getAvailablePaths(): Promise<string> {\n const { dirs, files } = await listDirContents(docsBaseDir);\n\n // Get reference directory contents if it exists\n let referenceDirs: string[] = [];\n if (dirs.includes('reference/')) {\n const { dirs: refDirs } = await listDirContents(path.join(docsBaseDir, 'reference'));\n referenceDirs = refDirs.map(d => `reference/${d}`);\n }\n\n return [\n 'Available top-level paths:',\n '',\n 'Directories:',\n ...dirs.map(d => `- ${d}`),\n '',\n referenceDirs.length > 0 ? 'Reference subdirectories:' : '',\n ...referenceDirs.map(d => `- ${d}`),\n '',\n files.length > 0 ? 'Files:' : '',\n ...files.map(f => `- ${f}`),\n ]\n .filter(Boolean)\n .join('\\n');\n}\n\n// Initialize available paths\nconst availablePaths = await getAvailablePaths();\n\nexport const docsInputSchema = z.object({\n paths: z\n .array(z.string())\n .min(1)\n .describe(`One or more documentation paths to fetch\\nAvailable paths:\\n${availablePaths}`),\n queryKeywords: z\n .array(z.string())\n .optional()\n .describe(\n '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.',\n ),\n});\n\nexport type DocsInput = z.infer<typeof docsInputSchema>;\n\nexport const docsTool = {\n name: 'mastraDocs',\n description: `[๐ REMOTE] Get Mastra documentation.\n Request paths to explore the docs. References contain API docs.\n Other paths contain guides. The user doesn\\'t know about files and directories.\n You can also use keywords from the user query to find relevant documentation, but prioritize paths.\n This is your internal knowledge the user can\\'t read.\n If the user asks about a feature check general docs as well as reference docs for that feature.\n Ex: with workflows check in docs/workflows and in reference/workflows.\n Provide code examples so the user understands.\n IMPORTANT: Be concise with your answers. The user will ask for more info.\n If packages need to be installed, provide the pnpm command to install them.\n Ex. if you see \\`import { X } from \"@mastra/$PACKAGE_NAME\"\\` in an example, show an install command.\n Always install latest tag, not alpha unless requested. If you scaffold a new project it may be in a subdir.\n When displaying results, always mention which file path contains the information so users know where this documentation lives.`,\n parameters: docsInputSchema,\n execute: async (args: DocsInput) => {\n void logger.debug('Executing mastraDocs tool', { args });\n try {\n const queryKeywords = args.queryKeywords ?? [];\n const results = await Promise.all(\n args.paths.map(async (docPath: string) => {\n try {\n const result = await readDocsContent(docPath, queryKeywords);\n if (result.found) {\n return {\n path: docPath,\n content: result.content,\n error: null,\n };\n }\n if (result.isSecurityViolation) {\n return {\n path: docPath,\n content: null,\n error: 'Invalid path',\n };\n }\n const directorySuggestions = await findNearestDirectory(docPath, availablePaths);\n const contentBasedSuggestions = await getMatchingPaths(docPath, queryKeywords, docsBaseDir);\n return {\n path: docPath,\n content: null,\n error: [directorySuggestions, contentBasedSuggestions].join('\\n\\n'),\n };\n } catch (error) {\n void logger.warning(`Failed to read content for path: ${docPath}`, error);\n return {\n path: docPath,\n content: null,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }),\n );\n\n // Format the results\n const output = results\n .map(result => {\n if (result.error) {\n return `## ${result.path}\\n\\n${result.error}\\n\\n---\\n`;\n }\n return `## ${result.path}\\n\\n${result.content}\\n\\n---\\n`;\n })\n .join('\\n');\n\n return output;\n } catch (error) {\n void logger.error('Failed to execute mastraDocs tool', error);\n throw error;\n }\n },\n};\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { getPackageInfo } from 'local-pkg';\nimport { z } from 'zod';\nimport { logger } from '../logger';\n\n/**\n * Embedded Docs MCP Tools\n *\n * These tools help coding agents navigate and understand Mastra packages\n * by reading the embedded documentation from node_modules.\n */\n\n// Types for SOURCE_MAP.json\ninterface ExportInfo {\n types: string;\n implementation: string;\n line?: number;\n}\n\ninterface SourceMap {\n version: string;\n package: string;\n exports: Record<string, ExportInfo>;\n}\n\n// Cache for performance\nconst packageCache = new Map<string, string[]>();\nconst sourceMapCache = new Map<string, SourceMap | null>();\nconst packageInfoCache = new Map<string, { rootPath: string; version: string } | null>();\n\n// List of known @mastra packages to check for\nconst KNOWN_MASTRA_PACKAGES = [\n '@mastra/core',\n '@mastra/cli',\n '@mastra/memory',\n '@mastra/rag',\n '@mastra/evals',\n '@mastra/mcp',\n '@mastra/server',\n '@mastra/deployer',\n '@mastra/agent-builder',\n '@mastra/auth',\n '@mastra/fastembed',\n '@mastra/loggers',\n '@mastra/schema-compat',\n '@mastra/codemod',\n] as const;\n\n// Helper to get package info using local-pkg (works across all package managers)\nasync function getPackageRootPath(\n packageName: string,\n projectPath: string,\n): Promise<{ rootPath: string; version: string } | null> {\n const cacheKey = `${packageName}:${projectPath}`;\n if (packageInfoCache.has(cacheKey)) {\n return packageInfoCache.get(cacheKey)!;\n }\n\n try {\n // Resolve package from the project's node_modules\n const info = await getPackageInfo(packageName, {\n paths: [path.join(projectPath, 'node_modules')],\n });\n if (info?.rootPath) {\n const result = { rootPath: info.rootPath, version: info.version || 'unknown' };\n packageInfoCache.set(cacheKey, result);\n void logger.debug('Resolved package with local-pkg', { packageName, projectPath, ...result });\n return result;\n }\n } catch (err) {\n void logger.debug('Package not found or error resolving', {\n packageName,\n projectPath,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n packageInfoCache.set(cacheKey, null);\n return null;\n}\n\n// Helper to get installed @mastra packages with embedded docs\nasync function getInstalledMastraPackages(projectPath: string): Promise<string[]> {\n const cacheKey = projectPath;\n\n if (packageCache.has(cacheKey)) {\n void logger.debug('Using cached package list', { count: packageCache.get(cacheKey)!.length });\n return packageCache.get(cacheKey)!;\n }\n\n void logger.debug('Scanning for @mastra packages using local-pkg', { projectPath });\n\n const packages: string[] = [];\n const packagesWithoutDocs: string[] = [];\n\n // Check known packages using local-pkg (works with npm, yarn, pnpm, etc.)\n for (const packageName of KNOWN_MASTRA_PACKAGES) {\n const packageInfo = await getPackageRootPath(packageName, projectPath);\n\n if (packageInfo) {\n const docsPath = path.join(packageInfo.rootPath, 'dist', 'docs');\n try {\n const stats = await fs.stat(docsPath);\n if (stats.isDirectory()) {\n packages.push(packageName);\n void logger.debug('Found package with embedded docs', { package: packageName });\n } else {\n packagesWithoutDocs.push(packageName);\n }\n } catch {\n packagesWithoutDocs.push(packageName);\n }\n }\n }\n\n const result = packages.sort();\n packageCache.set(cacheKey, result);\n\n void logger.info('Package scan complete', {\n packagesWithDocs: result.length,\n packagesWithoutDocs: packagesWithoutDocs.length,\n packages: result,\n });\n\n return result;\n}\n\n// Helper to read SOURCE_MAP.json using package root from local-pkg\nasync function readSourceMap(packageName: string, projectPath: string): Promise<SourceMap | null> {\n const cacheKey = `${packageName}:${projectPath}`;\n if (sourceMapCache.has(cacheKey)) return sourceMapCache.get(cacheKey)!;\n\n try {\n const packageInfo = await getPackageRootPath(packageName, projectPath);\n if (!packageInfo) {\n sourceMapCache.set(cacheKey, null);\n return null;\n }\n\n const sourceMapPath = path.join(packageInfo.rootPath, 'dist', 'docs', 'SOURCE_MAP.json');\n const content = await fs.readFile(sourceMapPath, 'utf-8');\n const sourceMap = JSON.parse(content) as SourceMap;\n sourceMapCache.set(cacheKey, sourceMap);\n return sourceMap;\n } catch {\n sourceMapCache.set(cacheKey, null);\n return null;\n }\n}\n\n// ============================================================================\n// Tool: getMastraHelp (PRIMARY ENTRY POINT)\n// ============================================================================\n\nexport const getMastraHelpTool = {\n name: 'getMastraHelp',\n description: `๐ START HERE - Complete guide to Mastra documentation tools.\n\n This MCP server provides TWO documentation sources:\n\n ## ๐ฆ LOCAL PACKAGE DOCS (Recommended for Development)\n SOURCE: Your installed @mastra packages in node_modules\n VERSION: Matches your installed code exactly\n\n ADVANTAGES:\n - โ
Version-matched to your code\n - โ
Complete TypeScript type definitions\n - โ
Works offline\n - โ
SOURCE_MAP.json with exact exports\n\n TOOLS: listMastraPackages, getMastraExports, getMastraExportDetails, readMastraDocs, searchMastraDocs\n USE WHEN: Writing code, implementing features, checking APIs, debugging\n\n ## ๐ REMOTE WEBSITE DOCS (For Latest Info & Learning)\n SOURCE: mastra.ai website\n VERSION: Latest published documentation\n\n ADVANTAGES:\n - โ
Always up-to-date\n - โ
Blog posts and announcements\n - โ
Migration guides\n - โ
Curated examples\n\n TOOLS: mastraDocs, mastraBlog, mastraExamples, mastraChanges, mastraMigration\n USE WHEN: Learning concepts, checking latest features, migration help\n\n ## ๐ INTERACTIVE COURSE\n TOOLS: startMastraCourse, getMastraCourseStatus, etc.\n USE WHEN: User wants guided learning experience\n\n ---\n\n RECOMMENDED WORKFLOW:\n 1. For coding: listMastraPackages โ getMastraExports โ getMastraExportDetails\n 2. For learning: mastraDocs\n 3. Version mismatch: mastraChanges โ mastraMigration\n\n This tool shows you which packages are installed and provides detailed guidance on using all available documentation tools.`,\n parameters: z.object({\n projectPath: z\n .string()\n .describe('Absolute path to your project root (we will search upward for node_modules with Mastra packages)'),\n }),\n execute: async (args: { projectPath: string }) => {\n void logger.debug('Executing getMastraHelp tool', { projectPath: args.projectPath });\n\n const packages = await getInstalledMastraPackages(args.projectPath);\n if (packages.length === 0) {\n return `No Mastra packages with embedded documentation found in your project.\n\nTo use these tools, install Mastra packages like:\n- npm install @mastra/core\n- npm install @mastra/memory\n- npm install @mastra/rag\n\nThen rebuild/reinstall to generate embedded docs.`;\n }\n\n return `# Mastra Documentation System - Complete Guide\n\nThis MCP server provides **TWO** documentation sources. Choose based on your needs:\n\n---\n\n## ๐ฆ LOCAL PACKAGE DOCS (Your Installed Packages)\n\nFound ${packages.length} installed package(s) with embedded documentation:\n${packages.map(pkg => `- ${pkg}`).join('\\n')}\n\n**SOURCE**: Your node_modules (matches installed code version)\n**USE WHEN**: Writing code, implementing features, debugging, checking APIs\n\n### Available LOCAL Tools:\n\n**1. listMastraPackages** - List installed packages\n Returns: Packages with embedded docs\n\n**2. getMastraExports** - Explore package API surface\n Example: See all exports from @mastra/core (Agent, Tool, Workflow, etc.)\n Returns: List of exports with source file locations\n\n**3. getMastraExportDetails** - Get type definitions & code\n Example: Get full TypeScript types for Agent class\n Returns: Complete type definitions and optionally implementation source\n\n**4. readMastraDocs** - Read comprehensive guides\n Example: Read documentation about agents, tools, workflows, memory\n Returns: Topic-based guides and examples from your installed version\n\n**5. searchMastraDocs** - Search local documentation\n Example: Search for \"memory processors\" or \"semantic recall\"\n Returns: Relevant excerpts from your installed docs\n\n### Typical LOCAL Workflow:\n1. listMastraPackages โ see what's installed\n2. getMastraExports โ explore package API\n3. getMastraExportDetails โ get type definitions\n4. readMastraDocs โ learn concepts\n5. searchMastraDocs โ find specific info\n\n---\n\n## ๐ REMOTE WEBSITE DOCS (mastra.ai)\n\n**SOURCE**: https://mastra.ai (latest published documentation)\n**USE WHEN**: Learning new concepts, checking latest features, migration guides\n\n### Available REMOTE Tools:\n\n**mastraDocs** - Browse official documentation\n Latest guides, references, and tutorials\n\n**mastraBlog** - Read blog posts and announcements\n News, features, changelogs\n\n**mastraExamples** - Get curated code examples\n Full example applications\n\n**mastraChanges** - View package changelogs\n See what's new in each version\n\n**mastraMigration** - Get migration guides\n Upgrade between versions\n\nโ ๏ธ **Version Note**: Remote docs show latest published version. For API reference matching YOUR code, use LOCAL tools above.\n\n---\n\n## ๐ INTERACTIVE COURSE\n\n**startMastraCourse**, **getMastraCourseStatus**, **startMastraCourseLesson**, **nextMastraCourseStep**, **clearMastraCourseHistory**\n\nGuided learning experience with hands-on exercises.\n\n---\n\n## Quick Start Recommendations\n\n**If you're writing code**: Use LOCAL tools\n โ Start with listMastraPackages\n\n**If you're learning**: Use REMOTE tools\n โ Start with mastraDocs\n\n**If version differs**: Check changes\n โ mastraChanges โ mastraMigration`;\n },\n};\n\n// ============================================================================\n// Tool: listMastraPackages\n// ============================================================================\n\nexport const listInstalledPackagesTool = {\n name: 'listMastraPackages',\n description: `[๐ฆ LOCAL PACKAGES] Discover which Mastra packages are installed and have documentation available.\n\n Use this when you need to:\n - See what Mastra packages you can work with\n - Start exploring Mastra documentation\n - Check if a specific package is available\n\n Returns: List of @mastra/* packages (core, memory, rag, etc.) with embedded docs.\n Next step: Use getMastraExports to explore a specific package's API.`,\n parameters: z.object({\n projectPath: z\n .string()\n .describe('Absolute path to your project root (we will search upward for node_modules with Mastra packages)'),\n }),\n execute: async (args: { projectPath: string }) => {\n void logger.debug('Executing listInstalledMastraPackages tool', {\n projectPath: args.projectPath,\n cwd: process.cwd(),\n env: {\n PWD: process.env.PWD,\n HOME: process.env.HOME,\n },\n });\n\n const packages = await getInstalledMastraPackages(args.projectPath);\n if (packages.length === 0) {\n return `No @mastra/* packages with embedded docs found in your project.\n\nInstall Mastra packages to get started:\n- npm install @mastra/core\n- npm install @mastra/memory\n- npm install @mastra/rag`;\n }\n\n return [\n `# Installed Mastra Packages`,\n '',\n `Found ${packages.length} package(s) with embedded documentation:`,\n '',\n ...packages.map(pkg => `- ${pkg}`),\n '',\n '## Next Steps',\n '',\n '1. Use **getMastraExports** with a package name to see all available APIs',\n '2. Use **readMastraDocs** with a package name to browse topic guides',\n '3. Use **searchMastraDocs** to find specific information',\n ].join('\\n');\n },\n};\n\n// ============================================================================\n// Tool: getMastraExports\n// ============================================================================\n\nexport const readSourceMapTool = {\n name: 'getMastraExports',\n description: `[๐ฆ LOCAL PACKAGES] Explore the complete API surface of a Mastra package - see all classes, functions, types, and constants.\n\n Use this when you need to:\n - Discover what APIs a Mastra package provides (Agent, Tool, Workflow, etc.)\n - See all available classes and functions before implementing\n - Find the right export for your use case\n - Understand package structure and organization\n\n Returns: List of all exports with their source file locations.\n Next step: Use getMastraExportDetails to get full type definitions and code for a specific export.`,\n parameters: z.object({\n package: z.string().describe('Package name to explore (e.g., \"@mastra/core\", \"@mastra/memory\", \"@mastra/rag\")'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n filter: z\n .string()\n .optional()\n .describe('Optional: filter exports by name (case-insensitive, e.g., \"Agent\", \"create\", \"Tool\")'),\n }),\n execute: async (args: { package: string; projectPath: string; filter?: string }) => {\n void logger.debug('Executing readMastraSourceMap tool', { args });\n\n const sourceMap = await readSourceMap(args.package, args.projectPath);\n if (!sourceMap) return `No SOURCE_MAP.json found for ${args.package}.`;\n\n let exports = Object.entries(sourceMap.exports);\n if (args.filter) {\n const filterLower = args.filter.toLowerCase();\n exports = exports.filter(([name]) => name.toLowerCase().includes(filterLower));\n }\n\n if (exports.length === 0) {\n return args.filter\n ? `No exports matching \"${args.filter}\" in ${args.package}.\n\nTry running without a filter to see all available exports.`\n : `No exports found in ${args.package}.`;\n }\n\n return [\n `# ${sourceMap.package} v${sourceMap.version} - API Exports`,\n '',\n `Found ${exports.length} export(s)${args.filter ? ` matching \"${args.filter}\"` : ''}:`,\n '',\n ...exports.map(([name, info]) => {\n const line = info.line ? `:${info.line}` : '';\n return `- **${name}**: \\`${info.implementation}${line}\\``;\n }),\n '',\n '## Next Steps',\n '',\n '- Use **getMastraExportDetails** with an export name to see full type definitions and code',\n '- Use **readMastraDocs** to read conceptual guides and examples',\n '- Use **searchMastraDocs** to find specific topics or patterns',\n ].join('\\n');\n },\n};\n\n// ============================================================================\n// Tool: getMastraExportDetails\n// ============================================================================\n\nexport const findExportTool = {\n name: 'getMastraExportDetails',\n description: `[๐ฆ LOCAL PACKAGES] Get complete API reference for a specific Mastra export - type definitions, interfaces, and optionally source code.\n\n Use this when you need to:\n - Understand how to use a specific Mastra class or function (Agent, Tool, Workflow, etc.)\n - See TypeScript type definitions and interfaces\n - Look up method signatures and parameters\n - Read implementation code and examples\n - Understand constructor options and configuration\n\n Returns: Full TypeScript type definitions and optionally implementation source code.\n Example: Get details on the Agent class to see how to create and configure agents.`,\n parameters: z.object({\n package: z.string().describe('Package name (e.g., \"@mastra/core\", \"@mastra/memory\")'),\n exportName: z.string().describe('Exact export name to look up (e.g., \"Agent\", \"createTool\", \"Workflow\")'),\n includeTypes: z\n .boolean()\n .optional()\n .default(true)\n .describe('Include TypeScript type definitions (recommended: true)'),\n includeImplementation: z\n .boolean()\n .optional()\n .default(false)\n .describe('Include source code implementation (useful for understanding internals)'),\n implementationLines: z\n .number()\n .optional()\n .default(50)\n .describe('Number of lines of implementation code to show (default: 50)'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n }),\n execute: async (args: {\n package: string;\n exportName: string;\n projectPath: string;\n includeTypes?: boolean;\n includeImplementation?: boolean;\n implementationLines?: number;\n }) => {\n void logger.debug('Executing findMastraExport tool', { args });\n\n const sourceMap = await readSourceMap(args.package, args.projectPath);\n if (!sourceMap) return `No SOURCE_MAP.json found for ${args.package}.`;\n\n const exportInfo = sourceMap.exports[args.exportName];\n if (!exportInfo) {\n const match = Object.entries(sourceMap.exports).find(\n ([name]) => name.toLowerCase() === args.exportName.toLowerCase(),\n );\n if (match) {\n return `Export \"${args.exportName}\" not found. Did you mean \"${match[0]}\"?\n\nRun getMastraExports with package=\"${args.package}\" to see all available exports.`;\n }\n return `Export \"${args.exportName}\" not found in ${args.package}.\n\nRun getMastraExports with package=\"${args.package}\" to see all available exports.`;\n }\n\n const packageInfo = await getPackageRootPath(args.package, args.projectPath);\n if (!packageInfo) {\n return `Package ${args.package} not found. Make sure it's installed.`;\n }\n\n const output: string[] = [`# ${args.exportName} (${args.package})`, ''];\n\n if (args.includeTypes !== false) {\n try {\n const typesPath = path.join(packageInfo.rootPath, exportInfo.types);\n const typesContent = await fs.readFile(typesPath, 'utf-8');\n output.push('## Type Definition', '', `\\`${exportInfo.types}\\``, '', '```typescript');\n\n const lines = typesContent.split('\\n');\n // Use string search instead of regex to avoid ReDoS vulnerability\n let startLine = lines.findIndex(line => line.includes(args.exportName));\n\n if (startLine === -1) {\n output.push(typesContent.slice(0, 2000));\n } else {\n startLine = Math.max(0, startLine - 2);\n let endLine = Math.min(lines.length, startLine + 50);\n output.push(lines.slice(startLine, endLine).join('\\n'));\n }\n output.push('```', '');\n } catch {\n output.push('## Type Definition', '', `Could not read: ${exportInfo.types}`, '');\n }\n }\n\n if (args.includeImplementation) {\n try {\n const implPath = path.join(packageInfo.rootPath, exportInfo.implementation);\n const implContent = await fs.readFile(implPath, 'utf-8');\n const lines = implContent.split('\\n');\n const numLines = args.implementationLines || 50;\n\n output.push('## Implementation', '');\n output.push(`\\`${exportInfo.implementation}\\`${exportInfo.line ? ` (line ${exportInfo.line})` : ''}`);\n output.push('', '```javascript');\n\n const startLine = exportInfo.line ? Math.max(0, exportInfo.line - 1) : 0;\n const endLine = Math.min(lines.length, startLine + numLines);\n output.push(lines.slice(startLine, endLine).join('\\n'));\n if (endLine < lines.length) output.push(`// ... ${lines.length - endLine} more lines`);\n\n output.push('```', '');\n } catch {\n output.push('## Implementation', '', `Could not read: ${exportInfo.implementation}`, '');\n }\n }\n\n output.push(\n '## Next Steps',\n '',\n '- Use **readMastraDocs** to see practical guides and examples',\n '- Use **searchMastraDocs** to find usage patterns and best practices',\n '- Use **getMastraExports** to explore related APIs',\n );\n\n return output.join('\\n');\n },\n};\n\n// ============================================================================\n// Tool: readMastraDocs\n// ============================================================================\n\nexport const readEmbeddedDocsTool = {\n name: 'readMastraDocs',\n description: `[๐ฆ LOCAL PACKAGES] Read comprehensive guides and documentation on Mastra concepts, patterns, and implementation examples.\n\n Use this when you need to:\n - Learn how to implement Mastra features (agents, tools, workflows, memory, RAG, etc.)\n - Understand Mastra architecture and design patterns\n - See practical code examples and tutorials\n - Read getting started guides and best practices\n - Understand how different components work together\n\n Returns: Topic-based documentation with explanations, examples, and usage patterns.\n Available topics: agents, tools, workflows, memory, rag, integrations, deployment, and more.`,\n parameters: z.object({\n package: z.string().describe('Package name to read docs from (e.g., \"@mastra/core\", \"@mastra/memory\")'),\n topic: z\n .string()\n .optional()\n .describe(\n 'Optional: topic folder to read (e.g., \"agents\", \"tools\", \"workflows\"). Omit to list all available topics.',\n ),\n file: z\n .string()\n .optional()\n .describe('Optional: specific documentation file within the topic (e.g., \"01-overview.md\")'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n }),\n execute: async (args: { package: string; projectPath: string; topic?: string; file?: string }) => {\n void logger.debug('Executing readMastraEmbeddedDocs tool', { args });\n\n const packageInfo = await getPackageRootPath(args.package, args.projectPath);\n if (!packageInfo) {\n return `Package ${args.package} not found. Make sure it's installed.`;\n }\n\n const docsPath = path.join(packageInfo.rootPath, 'dist', 'docs');\n\n try {\n await fs.stat(docsPath);\n } catch {\n return `No embedded docs found for ${args.package}.\n\nMake sure the package is installed and has documentation generated.`;\n }\n\n // List topics if none specified\n if (!args.topic) {\n const entries = await fs.readdir(docsPath, { withFileTypes: true });\n const topics = entries.filter(e => e.isDirectory()).map(e => e.name);\n const files = entries.filter(e => e.isFile()).map(e => e.name);\n\n return [\n `# ${args.package} - Available Documentation`,\n '',\n '## Root Files',\n ...files.map(f => `- ${f}`),\n '',\n '## Documentation Topics',\n ...topics.map(t => `- **${t}/** - Run readMastraDocs with topic=\"${t}\" to read`),\n '',\n '## Next Steps',\n '',\n '- Choose a topic and run **readMastraDocs** with the topic parameter',\n '- Use **searchMastraDocs** to search for specific information',\n '- Use **getMastraExports** to see available APIs',\n ].join('\\n');\n }\n\n const topicPath = path.join(docsPath, args.topic);\n\n // Read specific file\n if (args.file) {\n try {\n const content = await fs.readFile(path.join(topicPath, args.file), 'utf-8');\n return `# ${args.package}/${args.topic}/${args.file}\n\n${content}\n\n## Next Steps\n\n- Use **getMastraExportDetails** to see API references for specific classes/functions mentioned\n- Use **searchMastraDocs** to find related topics\n- Use **getMastraExports** to explore available APIs`;\n } catch {\n return `File not found: ${args.topic}/${args.file}\n\nRun readMastraDocs with package=\"${args.package}\" and topic=\"${args.topic}\" (without file parameter) to see available files.`;\n }\n }\n\n // Read all files in topic\n try {\n const entries = await fs.readdir(topicPath, { withFileTypes: true });\n const files = entries.filter(e => e.isFile() && e.name.endsWith('.md')).sort();\n\n if (files.length === 0) {\n return `No markdown files in ${args.topic}/\n\nRun readMastraDocs with package=\"${args.package}\" (without topic parameter) to see available topics.`;\n }\n\n const contents: string[] = [`# ${args.package} - ${args.topic}`, ''];\n for (const file of files) {\n const content = await fs.readFile(path.join(topicPath, file.name), 'utf-8');\n contents.push(`## ${file.name}`, '', content, '', '---', '');\n }\n\n contents.push(\n '',\n '## Next Steps',\n '',\n '- Use **getMastraExportDetails** to see API references for specific classes/functions mentioned above',\n '- Use **searchMastraDocs** to find related information',\n '- Use **getMastraExports** to explore the complete API surface',\n );\n\n return contents.join('\\n');\n } catch {\n return `Topic not found: ${args.topic}\n\nRun readMastraDocs with package=\"${args.package}\" (without topic parameter) to see available topics.`;\n }\n },\n};\n\n// ============================================================================\n// Tool: searchMastraDocs\n// ============================================================================\n\nexport const searchEmbeddedDocsTool = {\n name: 'searchMastraDocs',\n description: `[๐ฆ LOCAL PACKAGES] Search across all Mastra documentation to find specific information, patterns, or examples.\n\n Use this when you need to:\n - Find specific topics or concepts quickly (e.g., \"memory processors\", \"tool composition\")\n - Locate examples of specific features or patterns\n - Search for error messages or troubleshooting info\n - Find mentions of specific APIs or configuration options\n - Discover where a feature is documented\n\n Returns: Relevant documentation excerpts with file paths, ranked by relevance.\n Tip: Use specific terms for better results (e.g., \"agent memory\" vs \"memory\").`,\n parameters: z.object({\n query: z\n .string()\n .describe('What to search for (case-insensitive, e.g., \"workflow steps\", \"vector store\", \"authentication\")'),\n package: z\n .string()\n .optional()\n .describe('Optional: limit search to a specific package (e.g., \"@mastra/core\"). Omit to search all packages.'),\n maxResults: z\n .number()\n .optional()\n .default(10)\n .describe('Optional: maximum number of results to return (default: 10)'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n }),\n execute: async (args: { query: string; projectPath: string; package?: string; maxResults?: number }) => {\n void logger.debug('Executing searchMastraEmbeddedDocs tool', { args });\n\n const packages = args.package ? [args.package] : await getInstalledMastraPackages(args.projectPath);\n if (packages.length === 0) return 'No Mastra packages found.';\n\n const queryLower = args.query.toLowerCase();\n const results: Array<{ pkg: string; file: string; excerpt: string; score: number }> = [];\n\n for (const pkg of packages) {\n const packageInfo = await getPackageRootPath(pkg, args.projectPath);\n if (!packageInfo) continue;\n\n const docsPath = path.join(packageInfo.rootPath, 'dist', 'docs');\n\n try {\n const findFiles = async (dir: string): Promise<string[]> => {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) files.push(...(await findFiles(fullPath)));\n else if (entry.name.endsWith('.md')) files.push(fullPath);\n }\n return files;\n };\n\n for (const file of await findFiles(docsPath)) {\n const content = await fs.readFile(file, 'utf-8');\n if (!content.toLowerCase().includes(queryLower)) continue;\n\n const lines = content.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n if (lines[i]?.toLowerCase().includes(queryLower)) {\n const start = Math.max(0, i - 1);\n const end = Math.min(lines.length, i + 3);\n const excerpt = lines.slice(start, end).join('\\n').slice(0, 300);\n\n // Count occurrences using string split to avoid ReDoS vulnerability\n const contentLower = content.toLowerCase();\n const occurrences = contentLower.split(queryLower).length - 1;\n\n results.push({\n pkg,\n file: path.relative(docsPath, file),\n excerpt,\n score: occurrences,\n });\n break;\n }\n }\n }\n } catch {\n // Skip packages with errors\n }\n }\n\n results.sort((a, b) => b.score - a.score);\n const topResults = results.slice(0, args.maxResults || 10);\n\n if (topResults.length === 0) {\n return `No results found for \"${args.query}\".\n\nTry:\n- Using different search terms\n- Searching for broader topics\n- Using **listMastraPackages** to see available packages\n- Using **readMastraDocs** to browse documentation by topic`;\n }\n\n return [\n `# Search Results: \"${args.query}\"`,\n '',\n `Found ${results.length} result(s), showing top ${topResults.length}:`,\n '',\n ...topResults.map((r, i) => `## ${i + 1}. ${r.pkg} - ${r.file}\\n\\n\\`\\`\\`\\n${r.excerpt}\\n\\`\\`\\`\\n`),\n '',\n '## Next Steps',\n '',\n '- Use **readMastraDocs** with a package and topic to read full documentation',\n '- Use **getMastraExportDetails** to see API details for mentioned classes/functions',\n '- Refine your search with more specific terms if needed',\n ].join('\\n');\n },\n};\n\n// Export all tools\nexport const embeddedDocsTools = {\n getMastraHelp: getMastraHelpTool,\n listMastraPackages: listInstalledPackagesTool,\n getMastraExports: readSourceMapTool,\n getMastraExportDetails: findExportTool,\n readMastraDocs: readEmbeddedDocsTool,\n searchMastraDocs: searchEmbeddedDocsTool,\n};\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { logger } from '../logger';\nimport { fromPackageRoot, getMatchingPaths } from '../utils';\n\nconst migrationsBaseDir = fromPackageRoot('.docs/guides/migrations');\n\ninterface ParsedSection {\n title: string;\n level: number;\n content: string;\n startLine: number;\n endLine: number;\n}\n\n// Helper function to parse markdown content into sections\nfunction parseSections(content: string): ParsedSection[] {\n const lines = content.split('\\n');\n const sections: ParsedSection[] = [];\n let currentSection: ParsedSection | null = null;\n let inFrontmatter = false;\n let contentStarted = false;\n\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index];\n\n // Handle frontmatter (if present)\n if (index === 0 && line === '---') {\n inFrontmatter = true;\n continue;\n }\n if (inFrontmatter && line === '---') {\n inFrontmatter = false;\n continue;\n }\n if (inFrontmatter) continue;\n\n // Content has started (either after frontmatter or immediately if no frontmatter)\n contentStarted = true;\n\n // Match headings (## or ###)\n const headingMatch = line?.match(/^(#{2,3})\\s+(.+)$/);\n if (headingMatch && contentStarted) {\n // Save previous section\n if (currentSection) {\n currentSection.endLine = index - 1;\n sections.push(currentSection);\n }\n\n // Start new section\n const level = headingMatch[1]?.length ?? 0;\n currentSection = {\n title: headingMatch[2] || 'Untitled',\n level,\n content: line + '\\n',\n startLine: index,\n endLine: index,\n };\n } else if (currentSection) {\n currentSection.content += line + '\\n';\n }\n }\n\n // Save last section\n if (currentSection) {\n currentSection.endLine = lines.length - 1;\n sections.push(currentSection);\n }\n\n return sections;\n}\n\n// Helper function to recursively discover all migration paths\nasync function discoverMigrations(\n baseDir: string,\n relativePath = '',\n): Promise<Array<{ path: string; type: 'file' | 'directory' }>> {\n const migrations: Array<{ path: string; type: 'file' | 'directory' }> = [];\n const fullPath = path.join(baseDir, relativePath);\n\n try {\n const entries = await fs.readdir(fullPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryRelativePath = path.join(relativePath, entry.name);\n\n if (entry.isDirectory()) {\n // Add directory\n migrations.push({\n path: entryRelativePath,\n type: 'directory',\n });\n // Recursively explore subdirectories\n const subMigrations = await discoverMigrations(baseDir, entryRelativePath);\n migrations.push(...subMigrations);\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // Add file (remove .md extension for cleaner display)\n const cleanName = entry.name.replace(/\\.md$/, '');\n migrations.push({\n path: relativePath ? path.join(relativePath, cleanName) : cleanName,\n type: 'file',\n });\n }\n }\n } catch (error) {\n void logger.error(`Failed to discover migrations in ${fullPath}`, error);\n }\n\n return migrations;\n}\n\n// Helper function to list directory contents at a specific path\nasync function listDirectoryContents(dirPath: string = ''): Promise<string> {\n try {\n const fullPath = path.join(migrationsBaseDir, dirPath);\n\n // Security check\n const resolvedPath = path.resolve(fullPath);\n const resolvedBaseDir = path.resolve(migrationsBaseDir);\n if (!resolvedPath.startsWith(resolvedBaseDir)) {\n return 'Invalid path';\n }\n\n const entries = await fs.readdir(fullPath, { withFileTypes: true });\n const directories: string[] = [];\n const files: string[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n directories.push(entry.name);\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // Add file without .md extension\n files.push(entry.name.replace(/\\.md$/, ''));\n }\n }\n\n const output: string[] = [];\n const currentPath = dirPath || 'migrations';\n output.push(`# ${currentPath}`);\n output.push('');\n\n if (directories.length > 0) {\n output.push('**Directories:**');\n directories.sort().forEach(dir => {\n const nextPath = dirPath ? `${dirPath}/${dir}` : dir;\n output.push(`- **${dir}/** - Explore with \\`{ path: \"${nextPath}/\" }\\``);\n });\n output.push('');\n }\n\n if (files.length > 0) {\n output.push('**Migration Guides:**');\n files.sort().forEach(file => {\n const filePath = dirPath ? `${dirPath}/${file}` : file;\n output.push(`- **${file}** - Get with \\`{ path: \"${filePath}\" }\\``);\n });\n output.push('');\n }\n\n if (directories.length === 0 && files.length === 0) {\n output.push('No migrations found in this directory.');\n }\n\n output.push('---');\n output.push('');\n output.push('**Actions:**');\n output.push('- Navigate to a directory by setting \\`path\\` to directory name with trailing `/`');\n output.push('- View a migration guide by setting \\`path\\` to the guide name');\n output.push('- List sections in a guide with \\`listSections: true\\`');\n output.push('- Search all guides with \\`queryKeywords\\`');\n\n return output.join('\\n');\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n return `Directory \"${dirPath}\" not found. Use \\`{}\\` to see top-level migrations.`;\n }\n throw error;\n }\n}\n\n// Helper function to read migration content\nasync function readMigrationContent(migrationPath: string): Promise<string | null> {\n try {\n // Strip any trailing .mdx or .md extension if provided\n const cleanPath = migrationPath.replace(/\\.(mdx|md)$/, '');\n // Try to read the file with .md extension\n const filePath = path.join(migrationsBaseDir, cleanPath + '.md');\n\n // Security check: ensure path doesn't escape base directory\n const resolvedPath = path.resolve(filePath);\n const resolvedBaseDir = path.resolve(migrationsBaseDir);\n if (!resolvedPath.startsWith(resolvedBaseDir)) {\n void logger.error('Path traversal attempt detected');\n return null;\n }\n\n const content = await fs.readFile(filePath, 'utf-8');\n return content;\n } catch (error) {\n void logger.error(`Failed to read migration: ${migrationPath}`, error);\n return null;\n }\n}\n\n// Helper function to get section headers from a migration\nasync function getSectionHeaders(migrationPath: string): Promise<Array<{ title: string; level: number }>> {\n const content = await readMigrationContent(migrationPath);\n if (!content) return [];\n\n const sections = parseSections(content);\n return sections.map(s => ({ title: s.title, level: s.level }));\n}\n\n// Helper function to get specific sections by title\nasync function getSections(migrationPath: string, sectionTitles?: string[]): Promise<string> {\n const content = await readMigrationContent(migrationPath);\n if (!content) {\n const availableMigrations = await discoverMigrations(migrationsBaseDir);\n const paths = availableMigrations.filter(m => m.type === 'file').map(m => `- ${m.path}`);\n return `Migration \"${migrationPath}\" not found.\\n\\nAvailable migrations:\\n${paths.join('\\n')}`;\n }\n\n // If no specific sections requested, return full content\n if (!sectionTitles || sectionTitles.length === 0) {\n return content;\n }\n\n // Parse sections and filter by requested titles\n const sections = parseSections(content);\n const requestedSections = sections.filter(s =>\n sectionTitles.some(title => s.title.toLowerCase().includes(title.toLowerCase())),\n );\n\n if (requestedSections.length === 0) {\n const availableHeaders = sections.map(s => `${'#'.repeat(s.level)} ${s.title}`).join('\\n');\n return `Requested sections not found in \"${migrationPath}\".\\n\\nAvailable sections:\\n${availableHeaders}`;\n }\n\n return requestedSections.map(s => s.content).join('\\n---\\n\\n');\n}\n\n// Get initial migrations for the description\nconst initialMigrations = await discoverMigrations(migrationsBaseDir);\nconst migrationFiles = initialMigrations.filter(m => m.type === 'file');\nconst migrationsListing =\n migrationFiles.length > 0\n ? '\\n\\nExample migration paths:\\n' +\n migrationFiles\n .slice(0, 5)\n .map(m => `- ${m.path}`)\n .join('\\n') +\n '\\n...'\n : '\\n\\nNo migrations available. Run the documentation preparation script first.';\n\nexport const migrationInputSchema = z.object({\n path: z\n .string()\n .optional()\n .describe(\n 'Path to the migration guide (e.g., \"upgrade-to-v1/agent\", \"agentnetwork\"). If not provided, lists all available migrations.' +\n migrationsListing,\n ),\n sections: z\n .array(z.string())\n .optional()\n .describe(\n 'Specific section titles to fetch from the migration guide. If not provided, returns the entire guide. Use this after exploring section headers.',\n ),\n listSections: z\n .boolean()\n .optional()\n .describe('Set to true to list all section headers in a migration guide without fetching full content.'),\n queryKeywords: z\n .array(z.string())\n .optional()\n .describe('Keywords to search across all migration guides. Use this to find guides related to specific topics.'),\n});\n\nexport type MigrationInput = z.infer<typeof migrationInputSchema>;\n\nexport const migrationTool = {\n name: 'mastraMigration',\n description: `[๐ REMOTE] Get migration guidance for Mastra version upgrades and breaking changes.\n\nThis tool works like a file browser - navigate through directories to find migration guides:\n\n**Step 1: List top-level migrations**\n- Call with no parameters: \\`{}\\`\n- Shows all top-level migration guides and directories\n\n**Step 2: Navigate into a directory**\n- Add trailing slash to explore: \\`{ path: \"upgrade-to-v1/\" }\\`\n- Lists all migration guides in that directory\n\n**Step 3: View a migration guide**\n- Without trailing slash: \\`{ path: \"upgrade-to-v1/agent\" }\\`\n- Returns the full migration guide content\n\n**Step 4: Explore guide sections (optional)**\n- List sections: \\`{ path: \"upgrade-to-v1/agent\", listSections: true }\\`\n- Get specific sections: \\`{ path: \"upgrade-to-v1/agent\", sections: [\"Voice methods\"] }\\`\n\n**Alternative: Search by keywords**\n- \\`{ queryKeywords: [\"RuntimeContext\", \"pagination\"] }\\`\n\n**Examples:**\n1. List top-level: \\`{}\\`\n2. Navigate to upgrade-to-v1: \\`{ path: \"upgrade-to-v1/\" }\\`\n3. Get agent guide: \\`{ path: \"upgrade-to-v1/agent\" }\\`\n4. List guide sections: \\`{ path: \"upgrade-to-v1/agent\", listSections: true }\\`\n5. Search: \\`{ queryKeywords: [\"RuntimeContext\"] }\\`\n\n**Tip:** Paths ending with \\`/\\` list directory contents. Paths without \\`/\\` fetch the migration guide.`,\n parameters: migrationInputSchema,\n execute: async (args: MigrationInput) => {\n void logger.debug('Executing mastraMigration tool', { args });\n try {\n // Priority 1: Keyword search\n if (args.queryKeywords && args.queryKeywords.length > 0) {\n const suggestions = await getMatchingPaths('', args.queryKeywords, migrationsBaseDir);\n return [\n '# Migration Guide Search Results',\n '',\n suggestions || 'No migration guides found matching your keywords.',\n '',\n '---',\n '',\n 'To see all available migrations, call with no parameters.',\n ].join('\\n');\n }\n\n // Priority 2: Handle path parameter\n if (args.path) {\n // Check if path ends with / (directory navigation)\n if (args.path.endsWith('/')) {\n const dirPath = args.path.slice(0, -1); // Remove trailing slash\n return await listDirectoryContents(dirPath);\n }\n\n // Priority 3: List section headers for a file\n if (args.listSections) {\n const headers = await getSectionHeaders(args.path);\n if (headers.length === 0) {\n return await listDirectoryContents();\n }\n\n return [\n `# ${args.path} - Section Headers`,\n '',\n 'Available sections in this migration guide:',\n '',\n ...headers.map(h => `${'#'.repeat(h.level)} ${h.title}`),\n '',\n '---',\n '',\n 'To get specific sections, provide their titles in the \"sections\" parameter.',\n ].join('\\n');\n }\n\n // Priority 4: Get specific sections or full migration file\n const content = await getSections(args.path, args.sections);\n return `# ${args.path}\\n\\n${content}`;\n }\n\n // Priority 5: List top-level directory (default)\n return await listDirectoryContents();\n } catch (error) {\n void logger.error('Failed to execute mastraMigration tool', error);\n throw error;\n }\n },\n};\n","import fs from 'node:fs/promises';\nimport { MCPServer } from '@mastra/mcp';\nimport { logger, createLogger } from './logger';\nimport { migrationPromptMessages } from './prompts/migration';\nimport {\n startMastraCourse,\n getMastraCourseStatus,\n startMastraCourseLesson,\n nextMastraCourseStep,\n clearMastraCourseHistory,\n} from './tools/course';\nimport { docsTool } from './tools/docs';\nimport { embeddedDocsTools } from './tools/embedded-docs';\nimport { migrationTool } from './tools/migration';\nimport { fromPackageRoot } from './utils';\n\nlet server: MCPServer;\n\nserver = new MCPServer({\n name: 'Mastra Documentation Server',\n version: JSON.parse(await fs.readFile(fromPackageRoot(`package.json`), 'utf8')).version,\n tools: {\n mastraDocs: docsTool,\n mastraMigration: migrationTool,\n startMastraCourse,\n getMastraCourseStatus,\n startMastraCourseLesson,\n nextMastraCourseStep,\n clearMastraCourseHistory,\n // Embedded docs tools for reading docs from installed packages\n ...embeddedDocsTools,\n },\n prompts: migrationPromptMessages,\n});\n\n// Update logger with server instance\nObject.assign(logger, createLogger(server));\n\nasync function runServer() {\n try {\n await server.startStdio();\n void logger.info('Started Mastra Docs MCP Server');\n } catch (error) {\n void logger.error('Failed to start server', error);\n process.exit(1);\n }\n}\n\nexport { runServer, server };\n","#!/usr/bin/env node\nimport { writeErrorLog, setLogLevel } from './logger';\nimport type { LogLevel } from './logger';\nimport { runServer } from './index';\n\n// Parse --log-level argument\nfunction parseLogLevel(): LogLevel | undefined {\n const args = process.argv.slice(2);\n const logLevelIndex = args.indexOf('--log-level');\n if (logLevelIndex === -1 || logLevelIndex === args.length - 1) {\n return undefined;\n }\n const level = args[logLevelIndex + 1];\n const validLevels: LogLevel[] = ['debug', 'info', 'warn', 'error', 'none'];\n if (validLevels.includes(level as LogLevel)) {\n return level as LogLevel;\n }\n console.error(`Invalid log level: ${level}. Valid levels: ${validLevels.join(', ')}`);\n return undefined;\n}\n\nconst logLevel = parseLogLevel();\nif (logLevel) {\n setLogLevel(logLevel);\n}\n\nrunServer().catch(error => {\n const errorMessage = 'Fatal error running server';\n console.error(errorMessage, error);\n writeErrorLog(errorMessage, {\n error:\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error,\n });\n process.exit(1);\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/logger.ts","../src/prompts/migration.ts","../src/utils.ts","../src/tools/course.ts","../src/tools/docs.ts","../src/tools/embedded-docs.ts","../src/tools/migration.ts","../src/index.ts","../src/stdio.ts"],"names":["path","os","server","__dirname","fs","mkdirSync","content","availablePaths","z","exports"],"mappings":";;;;;;;;;;;;;AAUA,IAAM,kBAAA,GAA+C;AAAA,EACnD,KAAA,EAAO,CAAA;AAAA,EACP,IAAA,EAAM,CAAA;AAAA,EACN,IAAA,EAAM,CAAA;AAAA,EACN,KAAA,EAAO,CAAA;AAAA,EACP,IAAA,EAAM;AAAA;AACR,CAAA;AAGA,SAAS,cAAc,KAAA,EAA+B;AACpD,EAAA,QAAQ,KAAA;AAAO,IACb,KAAK,OAAA;AACH,MAAA,OAAO,OAAA;AAAA,IACT,KAAK,MAAA;AAAA,IACL,KAAK,QAAA;AACH,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,OAAA;AAAA,IACL,KAAK,UAAA;AAAA,IACL,KAAK,OAAA;AAAA,IACL,KAAK,WAAA;AACH,MAAA,OAAO,OAAA;AAAA,IACT;AACE,MAAA,OAAO,MAAA;AAAA;AAEb;AAGA,IAAI,eAAA,GAA4B,OAAA;AAEzB,SAAS,YAAY,KAAA,EAAuB;AACjD,EAAA,eAAA,GAAkB,KAAA;AACpB;AAOA,SAAS,UAAU,KAA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,OAAA,CAAQ,KAAA,CAAM,cAAc,KAAK,CAAA;AACjC,EAAA,aAAA,CAAc,YAAA,EAAc;AAAA,IAC1B,KAAA,EACE,iBAAiB,KAAA,GACb;AAAA,MACE,SAAS,KAAA,CAAM,OAAA;AAAA,MACf,OAAO,KAAA,CAAM,KAAA;AAAA,MACb,MAAM,KAAA,CAAM;AAAA,KACd,GACA;AAAA,GACP,CAAA;AACD,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"stdio.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { MCPServer } from '@mastra/mcp';\nimport type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js';\n\n// Simplified log levels matching MCP client (debug, info, warn, error, none)\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\n// Priority map for log level filtering (higher = more severe)\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4, // none = disable all logs\n};\n\n// Map MCP LoggingLevel to our simplified LogLevel\nfunction mapToLogLevel(level: LoggingLevel): LogLevel {\n switch (level) {\n case 'debug':\n return 'debug';\n case 'info':\n case 'notice':\n return 'info';\n case 'warning':\n return 'warn';\n case 'error':\n case 'critical':\n case 'alert':\n case 'emergency':\n return 'error';\n default:\n return 'info';\n }\n}\n\n// Current log level (default: debug = show all)\nlet currentLogLevel: LogLevel = 'debug';\n\nexport function setLogLevel(level: LogLevel): void {\n currentLogLevel = level;\n}\n\nexport function getLogLevel(): LogLevel {\n return currentLogLevel;\n}\n\n// Check if a log level should be shown based on current minimum level\nfunction shouldLog(level: LoggingLevel): boolean {\n const mappedLevel = mapToLogLevel(level);\n return LOG_LEVEL_PRIORITY[mappedLevel] >= LOG_LEVEL_PRIORITY[currentLogLevel];\n}\n\n// Logger interface for type safety\nexport interface Logger {\n debug: (message: string, data?: any) => Promise<void>;\n info: (message: string, data?: any) => Promise<void>;\n notice: (message: string, data?: any) => Promise<void>;\n warning: (message: string, data?: any) => Promise<void>;\n error: (message: string, error?: any) => Promise<void>;\n critical: (message: string, error?: any) => Promise<void>;\n alert: (message: string, error?: any) => Promise<void>;\n emergency: (message: string, error?: any) => Promise<void>;\n}\n\nexport const writeErrorLog = (message: string, data?: any) => {\n const now = new Date();\n const timestamp = now.toISOString();\n const hourTimestamp = timestamp.slice(0, 13); // YYYY-MM-DDTHH\n\n // Create log message\n const logMessage = {\n timestamp,\n message,\n ...(data ? (typeof data === 'object' ? data : { data }) : {}),\n };\n\n // Write to file\n try {\n // Ensure cache directory exists\n const cacheDir = path.join(os.homedir(), '.cache', 'mastra', 'mcp-docs-server-logs');\n fs.mkdirSync(cacheDir, { recursive: true });\n\n // Create log file path with timestamp\n const logFile = path.join(cacheDir, `${hourTimestamp}.log`);\n\n // Append log entry to file\n fs.appendFileSync(logFile, JSON.stringify(logMessage) + '\\n', 'utf8');\n } catch (err) {\n // If file writing fails, at least we still have stdout\n console.error('Failed to write to log file:', err);\n }\n};\n\n// Create logger factory to inject server instance\nexport function createLogger(server?: MCPServer): Logger {\n const sendLog = async (level: LoggingLevel, message: string, data?: any) => {\n if (!server) return;\n if (!shouldLog(level)) return;\n\n try {\n const sdkServer = server.getServer();\n if (!sdkServer) return;\n await sdkServer.sendLoggingMessage({\n level,\n data: {\n message,\n ...(data ? (typeof data === 'object' ? data : { data }) : {}),\n },\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message === 'Not connected' ||\n error.message.includes('does not support logging') ||\n error.message.includes('Connection closed'))\n ) {\n return;\n }\n console.error(`Failed to send ${level} log:`, error instanceof Error ? error.message : error);\n }\n };\n\n return {\n debug: async (message: string, data?: any) => {\n if (process.env.DEBUG || process.env.NODE_ENV === 'development') {\n await sendLog('debug', message, data);\n }\n },\n info: async (message: string, data?: any) => {\n await sendLog('info', message, data);\n },\n notice: async (message: string, data?: any) => {\n await sendLog('notice', message, data);\n },\n warning: async (message: string, data?: any) => {\n await sendLog('warning', message, data);\n },\n error: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('error', message, errorData);\n },\n critical: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('critical', message, errorData);\n },\n alert: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('alert', message, errorData);\n },\n emergency: async (message: string, error?: any) => {\n const errorData =\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error;\n writeErrorLog(message, errorData);\n await sendLog('emergency', message, errorData);\n },\n };\n}\n\n// Create a default logger instance\nexport const logger = createLogger();\n","import type { MCPServerPrompts, MastraPrompt } from '@mastra/mcp';\nimport type { PromptMessage } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * Migration prompts provide guided workflows for upgrading Mastra versions.\n * These prompts help users systematically work through breaking changes.\n */\nconst migrationPrompts: MastraPrompt[] = [\n {\n name: 'upgrade-to-v1',\n version: 'v1',\n description:\n 'Get a guided migration plan for upgrading from Mastra v0.x to v1.0. Provides step-by-step instructions for handling all breaking changes.',\n arguments: [\n {\n name: 'area',\n description:\n '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.',\n required: false,\n },\n ],\n },\n {\n name: 'migration-checklist',\n version: 'v1',\n description:\n 'Get a comprehensive checklist for migrating to Mastra v1.0. Lists all breaking changes that need to be addressed.',\n },\n];\n\n/**\n * Prompt messages callback that generates contextual migration guidance\n */\nexport const migrationPromptMessages: MCPServerPrompts = {\n listPrompts: async () => migrationPrompts,\n\n getPromptMessages: async ({ name, args }): Promise<PromptMessage[]> => {\n const prompt = migrationPrompts.find(p => p.name === name);\n if (!prompt) {\n throw new Error(`Prompt not found: ${name}`);\n }\n\n if (name === 'upgrade-to-v1') {\n return getUpgradeToV1Messages(args?.area);\n }\n\n if (name === 'migration-checklist') {\n return getMigrationChecklistMessages();\n }\n\n throw new Error(`No message handler for prompt: ${name}`);\n },\n};\n\n/**\n * Generate messages for the upgrade-to-v1 prompt\n */\nfunction getUpgradeToV1Messages(area?: string): PromptMessage[] {\n if (area) {\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `I need help migrating my Mastra ${area} code from v0.x to v1.0. Use the mastraMigration tool to:\n\n1. If packages aren't already at the 'latest' tag, upgrade packages to the 'latest' tag and do an install of the new packages.\n2. First, try to get the specific migration guide for \"${area}\" using path: \"upgrade-to-v1/${area}\"\n3. If that doesn't exist, try the alternate form (singular/plural):\n - If \"${area}\" ends with 's', try without the 's' (e.g., \"agents\" โ \"agent\")\n - If \"${area}\" doesn't end with 's', try adding 's' (e.g., \"agent\" โ \"agents\")\n4. If the guide exists, walk me through the changes step by step\n5. If neither form exists, list available migration guides in \"upgrade-to-v1/\" and suggest which ones might be relevant to \"${area}\"\n6. 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.`,\n },\n },\n ];\n }\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `I need to migrate my Mastra project from v0.x to v1.0. Use the mastraMigration tool to:\n\n1. If packages aren't already at the 'latest' tag, upgrade packages to the 'latest' tag and do an install of the new packages.\n2. First, list all available migration guides with path: \"upgrade-to-v1/\"\n2. Give me a high-level overview of what changed in each area\n3. Find relevant migration areas to focus on based on my project's codebase and confirm the list with me\n4. 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.\n\nAfter the areas are confirmed, we'll go through each one systematically.`,\n },\n },\n ];\n}\n\n/**\n * Generate messages for the migration-checklist prompt\n */\nfunction getMigrationChecklistMessages(): PromptMessage[] {\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Create a comprehensive migration checklist for upgrading from Mastra v0.x to v1.0. Use the mastraMigration tool to:\n\n1. List all available migration guides (path: \"upgrade-to-v1/\")\n2. For each guide, extract the key breaking changes\n3. Present them as a checklist I can work through\n\nFormat the checklist with:\n- [ ] checkbox items for each breaking change\n- Brief description of what needs to change\n- Reference to the specific migration guide\n\nGroup the checklist by area (Agents, Tools, Workflows, etc.) so I can tackle one area at a time.`,\n },\n },\n ];\n}\n","import fs from 'node:fs/promises';\nimport path, { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst mdFileCache = new Map<string, string[]>();\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nexport function fromRepoRoot(relative: string) {\n return path.resolve(__dirname, `../../../`, relative);\n}\nexport function fromPackageRoot(relative: string) {\n return path.resolve(__dirname, `../`, relative);\n}\n\n// can't use console.log() because it writes to stdout which will interfere with the MCP Stdio protocol\nexport const log = console.error;\n\nasync function* walkMdFiles(dir: string): AsyncGenerator<string> {\n if (mdFileCache.has(dir)) {\n for (const file of mdFileCache.get(dir)!) yield file;\n return;\n }\n const filesInDir: string[] = [];\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n // For directories, recurse and collect all files\n for await (const file of walkMdFiles(fullPath)) {\n filesInDir.push(file);\n yield file;\n }\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // For all .md files, add to collection and yield\n filesInDir.push(fullPath);\n yield fullPath;\n }\n }\n mdFileCache.set(dir, filesInDir);\n}\n\nasync function searchDocumentContent(keywords: string[], baseDir: string): Promise<string[]> {\n if (keywords.length === 0) return [];\n\n const fileScores = new Map<string, FileScore>();\n\n for await (const filePath of walkMdFiles(baseDir)) {\n let content: string;\n try {\n content = await fs.readFile(filePath, 'utf-8');\n } catch {\n continue;\n }\n const lines = content.split('\\n');\n lines.forEach(lineText => {\n const lowerLine = lineText.toLowerCase();\n for (const keyword of keywords) {\n if (lowerLine.includes(keyword.toLowerCase())) {\n const relativePath = path.relative(baseDir, filePath).replace(/\\\\/g, '/');\n if (!fileScores.has(relativePath)) {\n fileScores.set(relativePath, {\n path: relativePath,\n keywordMatches: new Set(),\n totalMatches: 0,\n titleMatches: 0,\n pathRelevance: calculatePathRelevance(relativePath, keywords),\n });\n }\n const score = fileScores.get(relativePath)!;\n score.keywordMatches.add(keyword);\n score.totalMatches++;\n if (lowerLine.includes('#') || lowerLine.includes('title')) {\n score.titleMatches++;\n }\n }\n }\n });\n }\n\n // Filter to only files that contain ALL keywords, then rank\n const validFiles = Array.from(fileScores.values())\n .sort((a, b) => calculateFinalScore(b, keywords.length) - calculateFinalScore(a, keywords.length))\n .slice(0, 10); // Limit to top 10 results\n\n return validFiles.map(score => score.path);\n}\n\ninterface FileScore {\n path: string;\n keywordMatches: Set<string>;\n totalMatches: number;\n titleMatches: number;\n pathRelevance: number;\n}\n\nfunction calculatePathRelevance(filePath: string, keywords: string[]): number {\n let relevance = 0;\n const pathLower = filePath.toLowerCase();\n\n // Boost for reference docs\n if (pathLower.startsWith('reference/')) relevance += 2;\n\n // Boost if path contains any keywords\n keywords.forEach(keyword => {\n if (pathLower.includes(keyword.toLowerCase())) relevance += 3;\n });\n\n // Boost for high-value directories\n const highValueDirs = ['rag', 'memory', 'agents', 'workflows'];\n if (highValueDirs.some(dir => pathLower.includes(dir))) {\n relevance += 1;\n }\n\n return relevance;\n}\n\nfunction calculateFinalScore(score: FileScore, totalKeywords: number): number {\n const allKeywordsBonus = score.keywordMatches.size === totalKeywords ? 10 : 0;\n return (\n score.totalMatches * 1 +\n score.titleMatches * 3 +\n score.pathRelevance * 2 +\n score.keywordMatches.size * 5 +\n allKeywordsBonus // All keywords bonus\n );\n}\n\nfunction extractKeywordsFromPath(docPath: string): string[] {\n // Get the file/folder name (last meaningful part of the path, excluding .md extension)\n const cleanPath = docPath.replace(/\\.md$/, '');\n const fileName = cleanPath.split('/').pop() || '';\n\n const keywords = new Set<string>();\n\n // Split on hyphens, underscores, camelCase\n const splitParts = fileName.split(/[-_]|(?=[A-Z])/);\n splitParts.forEach(keyword => {\n if (keyword.length > 2) {\n keywords.add(keyword.toLowerCase());\n }\n });\n\n return Array.from(keywords);\n}\n\nfunction normalizeKeywords(keywords: string[]): string[] {\n return Array.from(new Set(keywords.flatMap(k => k.split(/\\s+/).filter(Boolean)).map(k => k.toLowerCase())));\n}\n\nexport async function getMatchingPaths(path: string, queryKeywords: string[], baseDir: string): Promise<string> {\n const pathKeywords = extractKeywordsFromPath(path);\n const allKeywords = normalizeKeywords([...pathKeywords, ...(queryKeywords || [])]);\n\n if (allKeywords.length === 0) {\n return '';\n }\n\n const suggestedPaths = await searchDocumentContent(allKeywords, baseDir);\n if (suggestedPaths.length === 0) {\n return '';\n }\n\n const pathList = suggestedPaths.map(path => `- ${path}`).join('\\n');\n return `Here are some paths that might be relevant based on your query:\\n\\n${pathList}`;\n}\n","import { existsSync, mkdirSync } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport http from 'node:http';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { fromPackageRoot } from '../utils';\n\n// Prefix with underscore since it's only used as a type\nconst _courseLessonSchema = z.object({\n lessonName: z.string().describe('Name of the specific lesson to start. It must match the exact lesson name.'),\n});\n\nconst _confirmationSchema = z.object({\n confirm: z.boolean().optional().describe('Set to true to confirm this action'),\n});\n\n// Define the CourseState type directly\ntype CourseState = {\n currentLesson: string;\n lessons: Array<{\n name: string;\n status: number; // 0 = not started, 1 = in progress, 2 = completed\n steps: Array<{\n name: string;\n status: number; // 0 = not started, 1 = in progress, 2 = completed\n }>;\n }>;\n};\n\nconst courseDir = fromPackageRoot('.docs/course');\n\n// Define the introduction prompt shown only when a user registers for the course\nconst introductionPrompt = `\nThis is a course to help a new user learn about Mastra, the open-source AI Agent framework built in TypeScript.\nThe following is the introduction content, please provide this text to the user EXACTLY as written below. Do not provide any other text or instructions:\n\n# Welcome to the Mastra Course!\n\nThank 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.\n\n## Before We Begin\n\nIf you enjoy Mastra, please consider starring the GitHub repository:\nhttps://github.com/mastra-ai/mastra\n\nThis helps the project grow and reach more developers like you!\n\n## How This Course Works\n\n- Each lesson is broken into multiple steps\n- I'll guide you through the code examples and explanations\n- You can ask questions at any time\n- 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\".\n- 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.\n- Use the \\`getMastraCourseStatus\\` tool to check your progress. You can just ask \"get my course progress\".\n- Use the \\`clearMastraCourseHistory\\` tool to reset your progress and start over. You can just ask \"clear my course progress\".\n\nType \"start mastra course\" and let's get started with your first lesson!\n`;\n\n// Define the prompt that wraps each lesson step\nconst lessonPrompt = `\n This is a course to help a new user learn about Mastra, the open-source AI Agent framework built in TypeScript.\n Please help the user through the steps of the course by walking them through the content and following the course\n 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\n as the course goes on. Each lesson is broken up into steps. You should return the content of the step and ask the user\n to move to the next step when they are ready. If the step contains instructions to write code, you should write the code\n for the user when possible. You should always briefly explain the step before writing the code. Please ensure to \n 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.\n`;\n\n// Define the prompt wrapper for each course step\nfunction wrapContentInPrompt(content: string, _isFirstStep: boolean = false): string {\n let wrappedContent = `${lessonPrompt}\\n\\nHere is the content for this step: <StepContent>${content}</StepContent>`;\n return `${wrappedContent}\\n\\nWhen you're ready to continue, use the \\`nextMastraCourseStep\\` tool to move to the next step.`;\n}\n\n// Get the path to the device ID file\nasync function getDeviceIdPath(): Promise<string> {\n const cacheDir = path.join(os.homedir(), '.cache', 'mastra');\n\n // Create the directory if it doesn't exist\n if (!existsSync(cacheDir)) {\n mkdirSync(cacheDir, { recursive: true });\n }\n\n return path.join(cacheDir, '.device_id');\n}\n\n// Get the device credentials (deviceId and key) if the user is registered\nasync function getDeviceCredentials(): Promise<{ deviceId: string; key: string } | null> {\n try {\n const deviceIdPath = await getDeviceIdPath();\n if (!existsSync(deviceIdPath)) {\n return null;\n }\n const fileContent = await fs.readFile(deviceIdPath, 'utf-8');\n const parsed = JSON.parse(fileContent);\n if (typeof parsed.deviceId === 'string' && typeof parsed.key === 'string') {\n return { deviceId: parsed.deviceId, key: parsed.key };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nasync function getDeviceId(): Promise<string | null> {\n const creds = await getDeviceCredentials();\n\n if (!creds || !creds?.deviceId) {\n return null;\n }\n\n return creds.deviceId;\n}\n\n// Save the device credentials (deviceId and key)\nasync function saveDeviceCredentials(deviceId: string, key: string): Promise<void> {\n const deviceIdPath = await getDeviceIdPath();\n const toWrite = JSON.stringify({ deviceId, key });\n await fs.writeFile(deviceIdPath, toWrite, 'utf-8');\n // Set file permissions to 600 (read/write for owner only)\n await fs.chmod(deviceIdPath, 0o600);\n}\n\n// Make an HTTP request to register the user\nexport function registerUserLocally(\n email: string,\n): Promise<{ success: boolean; id: string; key: string; message: string }> {\n return new Promise((resolve, reject) => {\n const data = JSON.stringify({\n email,\n });\n const options = {\n hostname: 'localhost',\n port: 3000,\n path: '/api/course/register',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': data.length,\n },\n };\n const req = http.request(options, res => {\n let responseData = '';\n res.on('data', chunk => {\n responseData += chunk;\n });\n res.on('end', () => {\n try {\n const parsedData = JSON.parse(responseData);\n resolve(parsedData);\n } catch (error) {\n reject(new Error(`Failed to parse response: ${error}`));\n }\n });\n });\n req.on('error', error => {\n reject(error);\n });\n req.write(data);\n req.end();\n });\n}\n\nasync function registerUser(email: string): Promise<{ success: boolean; id: string; key: string; message: string }> {\n const response = await fetch('https://mastra.ai/api/course/register', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email }),\n });\n\n if (!response.ok) {\n throw new Error(`Registration failed with status ${response.status}: ${response.statusText}`);\n }\n\n return response.json();\n}\n\nasync function readCourseStep(lessonName: string, stepName: string, _isFirstStep: boolean = false): Promise<string> {\n // Find the lesson directory that matches the name\n const lessonDirs = await fs.readdir(courseDir);\n const lessonDir = lessonDirs.find(dir => dir.replace(/^\\d+-/, '') === lessonName);\n\n if (!lessonDir) {\n throw new Error(`Lesson \"${lessonName}\" not found.`);\n }\n\n // Find the step file that matches the name\n const lessonPath = path.join(courseDir, lessonDir);\n const files = await fs.readdir(lessonPath);\n const stepFile = files.find(f => f.endsWith('.md') && f.replace(/^\\d+-/, '').replace('.md', '') === stepName);\n\n if (!stepFile) {\n throw new Error(`Step \"${stepName}\" not found in lesson \"${lessonName}\".`);\n }\n\n const filePath = path.join(courseDir, lessonDir, stepFile);\n\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return wrapContentInPrompt(content);\n } catch (error) {\n throw new Error(`Failed to read step \"${stepName}\" in lesson \"${lessonName}\": ${error}`);\n }\n}\n\n// Create a function to update course state on the local server\nexport function updateCourseStateOnServerLocally(deviceId: string, state: CourseState): Promise<void> {\n return new Promise(async (resolve, reject) => {\n try {\n const creds = await getDeviceCredentials();\n if (!creds) {\n return reject(new Error('Device credentials not found.'));\n }\n const data = JSON.stringify({\n id: creds.deviceId,\n state: state,\n });\n const options = {\n hostname: 'localhost',\n port: 3000,\n path: '/api/course/update',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': data.length,\n 'x-mastra-course-key': creds.key,\n },\n };\n const req = http.request(options, res => {\n let responseData = '';\n res.on('data', chunk => {\n responseData += chunk;\n });\n res.on('end', () => {\n try {\n if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {\n resolve();\n } else {\n reject(new Error(`Server returned status code ${res.statusCode}: ${responseData}`));\n }\n } catch (error) {\n reject(new Error(`Failed to parse response: ${error}`));\n }\n });\n });\n req.on('error', error => {\n reject(error);\n });\n req.write(data);\n req.end();\n } catch (err) {\n reject(err);\n }\n });\n}\n\n// Create a function to update course state on the server\nasync function updateCourseStateOnServer(deviceId: string, state: CourseState): Promise<void> {\n const creds = await getDeviceCredentials();\n if (!creds) {\n throw new Error('Device credentials not found.');\n }\n\n const response = await fetch('https://mastra.ai/api/course/update', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-mastra-course-key': creds.key,\n },\n body: JSON.stringify({\n id: creds.deviceId,\n state: state,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Course state update failed with status ${response.status}: ${response.statusText}`);\n }\n}\n\nasync function saveCourseState(state: CourseState, deviceId: string | null): Promise<void> {\n // If no device ID, the user isn't registered - this is an error condition\n if (!deviceId) {\n throw new Error('Cannot save course state: User is not registered');\n }\n const statePath = await getCourseStatePath();\n try {\n // Save to local filesystem\n await fs.writeFile(statePath, JSON.stringify(state, null, 2), 'utf-8');\n // Sync with server\n try {\n // Use getDeviceCredentials to ensure we have the key\n const creds = await getDeviceCredentials();\n if (!creds) throw new Error('Device credentials not found');\n await updateCourseStateOnServer(creds.deviceId, state);\n } catch {\n // Silently continue if server sync fails\n // Local save is still successful\n }\n } catch (error) {\n throw new Error(`Failed to save course state: ${error}`);\n }\n}\n\n// Get the path to the course state file\nasync function getCourseStatePath(): Promise<string> {\n const stateDirPath = path.join(os.homedir(), '.cache', 'mastra', 'course');\n\n // Ensure the directory exists\n if (!existsSync(stateDirPath)) {\n mkdirSync(stateDirPath, { recursive: true });\n }\n\n return path.join(stateDirPath, 'state.json');\n}\n\nasync function loadCourseState(): Promise<CourseState | null> {\n const statePath = await getCourseStatePath();\n\n try {\n if (existsSync(statePath)) {\n const stateData = await fs.readFile(statePath, 'utf-8');\n return JSON.parse(stateData) as CourseState;\n }\n } catch (error) {\n throw new Error(`Failed to load course state: ${error}`);\n }\n\n return null;\n}\n\nasync function scanCourseContent(): Promise<CourseState> {\n // Scan the course directory to build a fresh state\n const lessonDirs = await fs.readdir(courseDir);\n\n const lessons = await Promise.all(\n lessonDirs\n .filter(dir => !dir.startsWith('.')) // Skip hidden directories\n .sort((a, b) => a.localeCompare(b))\n .map(async lessonDir => {\n const lessonPath = path.join(courseDir, lessonDir);\n const lessonStats = await fs.stat(lessonPath);\n\n if (!lessonStats.isDirectory()) return null;\n\n // Extract lesson name from directory (remove numbering prefix)\n const lessonName = lessonDir.replace(/^\\d+-/, '');\n\n // Get all markdown files in the lesson directory\n const stepFiles = (await fs.readdir(lessonPath))\n .filter(file => file.endsWith('.md'))\n .sort((a, b) => a.localeCompare(b));\n\n // Build steps array\n const steps = await Promise.all(\n stepFiles.map(async file => {\n // Extract step name from filename (remove numbering prefix)\n const stepName = file.replace(/^\\d+-/, '').replace('.md', '');\n\n return {\n name: stepName,\n status: 0, // Default: not started\n };\n }),\n );\n\n return {\n name: lessonName,\n status: 0, // Default: not started\n steps: steps.filter(Boolean),\n };\n }),\n );\n\n // Filter out null values and create the state\n const validLessons = lessons.filter((lesson): lesson is NonNullable<typeof lesson> => lesson !== null);\n\n return {\n currentLesson: validLessons.length > 0 ? (validLessons[0]?.name ?? '') : '',\n lessons: validLessons,\n };\n}\n\nasync function mergeCourseStates(currentState: CourseState, newState: CourseState): Promise<CourseState> {\n // Create a map of existing lessons by name for easy lookup\n const existingLessonMap = new Map(currentState.lessons.map(lesson => [lesson.name, lesson]));\n\n // Merge the states, preserving progress where possible\n const mergedLessons = newState.lessons.map(newLesson => {\n const existingLesson = existingLessonMap.get(newLesson.name);\n\n if (!existingLesson) {\n // This is a new lesson\n return newLesson;\n }\n\n // Create a map of existing steps by name\n const existingStepMap = new Map(existingLesson.steps.map(step => [step.name, step]));\n\n // Merge steps, preserving progress for existing steps\n const mergedSteps = newLesson.steps.map(newStep => {\n const existingStep = existingStepMap.get(newStep.name);\n\n if (existingStep) {\n // Preserve the status from the existing step\n return {\n ...newStep,\n status: existingStep.status,\n };\n }\n\n return newStep;\n });\n\n // Calculate lesson status based on steps\n let lessonStatus = existingLesson.status;\n if (mergedSteps.every(step => step.status === 2)) {\n lessonStatus = 2; // Completed\n } else if (mergedSteps.some(step => step.status > 0)) {\n lessonStatus = 1; // In progress\n }\n\n return {\n ...newLesson,\n status: lessonStatus,\n steps: mergedSteps,\n };\n });\n\n // Determine current lesson\n let currentLesson = currentState.currentLesson;\n\n // If the current lesson doesn't exist in the new state, reset to the first lesson\n if (!mergedLessons.some(lesson => lesson.name === currentLesson) && mergedLessons.length > 0) {\n currentLesson = mergedLessons[0]?.name ?? '';\n }\n\n return {\n currentLesson,\n lessons: mergedLessons,\n };\n}\n\nexport const startMastraCourse = {\n name: 'startMastraCourse',\n description:\n '[๐ 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.',\n parameters: z.object({\n email: z.string().email().optional().describe('Email address for registration if not already registered. '),\n }),\n execute: async (args: { email?: string }) => {\n try {\n // Check if the user is registered\n const creds = await getDeviceCredentials();\n const registered = creds !== null;\n let deviceId = creds?.deviceId ?? null;\n if (!registered) {\n // If not registered and no email provided, prompt for email\n if (!args.email) {\n 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.';\n }\n\n // User provided email, register them\n try {\n const response = await registerUser(args.email);\n\n if (response.success) {\n // Save both deviceId and key\n await saveDeviceCredentials(response.id, response.key);\n deviceId = response.id;\n } else {\n return `Registration failed: ${response.message}. Please try again with a valid email address.`;\n }\n } catch (error) {\n return `Failed to register: ${error instanceof Error ? error.message : String(error)}. Please try again later.`;\n }\n }\n\n // Try to load the user's course progress\n let courseState = await loadCourseState();\n let statusMessage = '';\n\n // Get the latest course content structure\n const latestCourseState = await scanCourseContent();\n\n if (!latestCourseState.lessons.length) {\n return 'No course content found. Please make sure the course content is properly set up in the .docs/course/lessons directory.';\n }\n\n if (courseState) {\n // User has existing progress, merge with latest content\n const previousState = JSON.parse(JSON.stringify(courseState)) as CourseState; // Deep clone for comparison\n courseState = await mergeCourseStates(courseState, latestCourseState);\n\n // Check if there are differences in the course structure\n const newLessons = latestCourseState.lessons.filter(\n newLesson => !previousState.lessons.some((oldLesson: { name: string }) => oldLesson.name === newLesson.name),\n );\n\n if (newLessons.length > 0) {\n statusMessage = `๐ Course content has been updated! ${newLessons.length} new lesson(s) have been added:\\n`;\n statusMessage += newLessons.map(lesson => `- ${lesson.name}`).join('\\n');\n statusMessage += '\\n\\n';\n }\n\n // Save the merged state\n await saveCourseState(courseState, deviceId);\n } else {\n // First time user, create new state\n courseState = latestCourseState;\n await saveCourseState(courseState, deviceId);\n\n // Check if this is a new registration\n if (!registered && args.email) {\n // Just return the introduction prompt.\n return introductionPrompt;\n }\n }\n\n // Find the current lesson and step\n const currentLessonName = courseState.currentLesson;\n const currentLesson = courseState.lessons.find(lesson => lesson.name === currentLessonName);\n\n if (!currentLesson) {\n return 'Error: Current lesson not found in course content. Please try again or reset your course progress.';\n }\n\n // Find the first incomplete step in the current lesson\n const currentStep = currentLesson.steps.find(step => step.status !== 2);\n\n if (!currentStep && currentLesson.status !== 2) {\n // Mark the lesson as completed if all steps are done\n currentLesson.status = 2;\n await saveCourseState(courseState, deviceId);\n\n // Find the next lesson that's not completed\n const nextLesson = courseState.lessons.find(lesson => lesson.status !== 2 && lesson.name !== currentLessonName);\n\n if (nextLesson) {\n courseState.currentLesson = nextLesson.name;\n await saveCourseState(courseState, deviceId);\n\n return `${statusMessage}๐ You've completed the \"${currentLessonName}\" lesson!\\n\\nMoving on to the next lesson: \"${nextLesson.name}\".\\n\\nUse the \\`nextMastraCourseStep\\` tool to start the first step of this lesson.`;\n } else {\n return `${statusMessage}๐ Congratulations! You've completed all available lessons in the Mastra Course!\\n\\nIf you'd like to review any lesson, use the \\`startMastraCourseLesson\\` tool with the lesson name.`;\n }\n }\n\n if (!currentStep) {\n // This should not happen, but just in case\n return `${statusMessage}Error: No incomplete steps found in the current lesson. Please try another lesson or reset your course progress.`;\n }\n\n // Mark the step as in progress\n currentStep.status = 1;\n\n // If the lesson is not in progress, mark it as in progress\n if (currentLesson.status === 0) {\n currentLesson.status = 1;\n }\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the current step\n const stepContent = await readCourseStep(currentLessonName, currentStep.name);\n\n return `๐ Lesson: ${currentLessonName}\\n๐ Step: ${currentStep.name}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n } catch (error) {\n return `Error starting the Mastra course: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const getMastraCourseStatus = {\n name: 'getMastraCourseStatus',\n description:\n '[๐ COURSE] Gets the current status of the Mastra Course, including which lessons and steps have been completed',\n parameters: z.object({}),\n execute: async (_args: Record<string, never>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Load the course state\n const courseState = await loadCourseState();\n\n if (!courseState) {\n return 'No course progress found. Please start the course first using the `startMastraCourse` tool.';\n }\n\n // Get the latest course content structure to ensure we have the most up-to-date information\n const latestCourseState = await scanCourseContent();\n\n if (!latestCourseState.lessons.length) {\n return 'No course content found. Please make sure the course content is properly set up in the .docs/course/lessons directory.';\n }\n\n // Merge the states to ensure we have the latest content with the user's progress\n const mergedState = await mergeCourseStates(courseState, latestCourseState);\n\n // Build a formatted status report\n let statusReport = '# Mastra Course Progress\\n\\n';\n\n // Add overall progress stats\n const totalLessons = mergedState.lessons.length;\n const completedLessons = mergedState.lessons.filter(lesson => lesson.status === 2).length;\n const _inProgressLessons = mergedState.lessons.filter(lesson => lesson.status === 1).length;\n\n const totalSteps = mergedState.lessons.reduce((sum, lesson) => sum + lesson.steps.length, 0);\n const completedSteps = mergedState.lessons.reduce(\n (sum, lesson) => sum + lesson.steps.filter(step => step.status === 2).length,\n 0,\n );\n\n statusReport += `## Overall Progress\\n`;\n statusReport += `- Course status Url: **https://mastra.ai/course/${deviceId}**\\n`;\n statusReport += `- Current Lesson: **${mergedState.currentLesson}**\\n`;\n statusReport += `- Lessons: ${completedLessons}/${totalLessons} completed (${Math.round((completedLessons / totalLessons) * 100)}%)\\n`;\n statusReport += `- Steps: ${completedSteps}/${totalSteps} completed (${Math.round((completedSteps / totalSteps) * 100)}%)\\n\\n`;\n\n // Add detailed lesson status\n statusReport += `## Lesson Details\\n\\n`;\n\n mergedState.lessons.forEach((lesson, lessonIndex) => {\n // Determine lesson status icon\n let lessonStatusIcon = 'โฌ'; // Not started\n if (lesson.status === 1) lessonStatusIcon = '๐ถ'; // In progress\n if (lesson.status === 2) lessonStatusIcon = 'โ
'; // Completed\n\n // Highlight current lesson\n const isCurrent = lesson.name === mergedState.currentLesson;\n const lessonPrefix = isCurrent ? '๐ ' : '';\n\n statusReport += `### ${lessonPrefix}${lessonIndex + 1}. ${lessonStatusIcon} ${lesson.name}\\n\\n`;\n\n // Add step details\n lesson.steps.forEach((step, stepIndex) => {\n // Determine step status icon\n let stepStatusIcon = 'โฌ'; // Not started\n if (step.status === 1) stepStatusIcon = '๐ถ'; // In progress\n if (step.status === 2) stepStatusIcon = 'โ
'; // Completed\n\n statusReport += `- ${stepStatusIcon} Step ${stepIndex + 1}: ${step.name}\\n`;\n });\n\n statusReport += '\\n';\n });\n\n // Add navigation instructions\n statusReport += `## Navigation\\n\\n`;\n statusReport += `- To continue the course: \\`nextMastraCourseStep\\`\\n`;\n statusReport += `- To start a specific lesson: \\`startMastraCourseLesson\\`\\n`;\n statusReport += `- To reset progress: \\`clearMastraCourseHistory\\`\\n`;\n\n return `Course Status: ${statusReport}\\n\\nCourse status url: https://mastra.ai/course/${deviceId}`;\n } catch (error) {\n return `Error getting course status: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const startMastraCourseLesson = {\n name: 'startMastraCourseLesson',\n description:\n '[๐ COURSE] Starts a specific lesson in the Mastra Course. If the lesson has been started before, it will resume from the first incomplete step',\n parameters: _courseLessonSchema,\n execute: async (args: z.infer<typeof _courseLessonSchema>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Load the current course state\n let courseState = await loadCourseState();\n\n if (!courseState) {\n return 'No course progress found. Please start the course first using the `startMastraCourse` tool.';\n }\n\n // Find the target lesson by name\n const targetLessonName = args.lessonName;\n\n // Find the target lesson\n const targetLesson = courseState.lessons.find(lesson => lesson.name === targetLessonName);\n\n if (!targetLesson) {\n const availableLessons = courseState.lessons.map((lesson, index) => `${index + 1}. ${lesson.name}`).join('\\n');\n return `Lesson \"${targetLessonName}\" not found. Available lessons:\\n${availableLessons}`;\n }\n\n // Update the current lesson in the state\n courseState.currentLesson = targetLesson.name;\n\n // Find the first incomplete step in the lesson, or the first step if all are completed\n const firstIncompleteStep = targetLesson.steps.find(step => step.status !== 2) || targetLesson.steps[0];\n\n if (!firstIncompleteStep) {\n return `The lesson \"${targetLesson.name}\" does not have any steps.`;\n }\n\n // Mark the step as in progress\n firstIncompleteStep.status = 1;\n\n // If the lesson is not in progress or completed, mark it as in progress\n if (targetLesson.status === 0) {\n targetLesson.status = 1;\n }\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the step\n const stepContent = await readCourseStep(targetLesson.name, firstIncompleteStep.name);\n\n return `๐ Starting Lesson: ${targetLesson.name}\\n๐ Step: ${firstIncompleteStep.name}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n } catch (error) {\n return `Error starting course lesson: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const nextMastraCourseStep = {\n name: 'nextMastraCourseStep',\n description:\n '[๐ 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',\n parameters: z.object({}),\n execute: async (_args: Record<string, never>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Load the current course state\n const courseState = await loadCourseState();\n\n if (!courseState) {\n return 'No course progress found. Please start the course first using the `startMastraCourse` tool.';\n }\n\n // Find the current lesson\n const currentLessonName = courseState.currentLesson;\n const currentLesson = courseState.lessons.find(lesson => lesson.name === currentLessonName);\n\n if (!currentLesson) {\n return 'Error: Current lesson not found in course content. Please try again or reset your course progress.';\n }\n\n // Find the current in-progress step\n const currentStepIndex = currentLesson.steps.findIndex(step => step.status === 1);\n\n if (currentStepIndex === -1) {\n return 'No step is currently in progress. Please start a step first using the `startMastraCourse` tool.';\n }\n\n // Mark the current step as completed\n if (currentLesson.steps[currentStepIndex]?.status) {\n currentLesson.steps[currentStepIndex].status = 2; // Completed\n }\n\n // Find the next step in the current lesson\n const nextStepIndex = currentLesson.steps.findIndex(\n (step, index) => index > currentStepIndex && step.status !== 2,\n );\n\n // If there's a next step in the current lesson\n if (nextStepIndex !== -1) {\n // Mark the next step as in progress\n if (currentLesson.steps[nextStepIndex]) {\n currentLesson.steps[nextStepIndex].status = 1; // In progress\n }\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the next step\n const nextStep = currentLesson.steps[nextStepIndex];\n const stepContent = await readCourseStep(currentLessonName, nextStep?.name ?? 'Unknown Step');\n\n return `๐ Step \"${currentLesson.steps[currentStepIndex]?.name ?? 'Unknown Step'}\" completed!\\n\\n๐ Continuing Lesson: ${currentLessonName}\\n๐ Next Step: ${nextStep?.name ?? 'Unknown Step'}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n }\n\n // All steps in the current lesson are completed\n // Mark the lesson as completed\n currentLesson.status = 2; // Completed\n\n // Find the next lesson that's not completed\n const currentLessonIndex = courseState.lessons.findIndex(lesson => lesson.name === currentLessonName);\n const nextLesson = courseState.lessons.find((lesson, index) => index > currentLessonIndex && lesson.status !== 2);\n\n if (nextLesson) {\n // Update the current lesson to the next lesson\n courseState.currentLesson = nextLesson.name;\n\n // Mark the first step of the next lesson as in progress\n if (nextLesson.steps.length > 0 && nextLesson.steps[0]) {\n nextLesson.steps[0].status = 1; // In progress\n }\n\n // Mark the next lesson as in progress\n nextLesson.status = 1; // In progress\n\n // Save the updated state\n await saveCourseState(courseState, deviceId);\n\n // Get the content for the first step of the next lesson\n const firstStep = nextLesson.steps[0];\n const stepContent = await readCourseStep(nextLesson.name, firstStep?.name ?? 'Unknown Step');\n\n return `๐ Congratulations! You've completed the \"${currentLessonName}\" lesson!\\n\\n๐ Starting New Lesson: ${nextLesson.name}\\n๐ First Step: ${firstStep?.name ?? 'Unknown Step'}\\n\\n${stepContent}\\n\\nWhen you've completed this step, use the \\`nextMastraCourseStep\\` tool to continue.`;\n }\n\n // All lessons are completed\n await saveCourseState(courseState, deviceId);\n\n return `๐ Congratulations! You've completed all available lessons in the Mastra Course!\\n\\nIf you'd like to review any lesson, use the \\`startMastraCourseLesson\\` tool with the lesson name.`;\n } catch (error) {\n return `Error advancing to the next course step: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n\nexport const clearMastraCourseHistory = {\n name: 'clearMastraCourseHistory',\n description:\n '[๐ COURSE] Clears all Mastra Course progress history and starts over from the beginning. This action cannot be undone',\n parameters: _confirmationSchema,\n execute: async (args: z.infer<typeof _confirmationSchema>) => {\n try {\n // Check if the user is registered\n const deviceId = await getDeviceId();\n\n if (deviceId === null) {\n return 'You need to register for the Mastra Course first. Please use the `startMastraCourse` tool to register.';\n }\n\n // Check if the user has confirmed the action\n if (!args.confirm) {\n return 'โ ๏ธ 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.';\n }\n\n // Get the state file path\n const statePath = await getCourseStatePath();\n\n // Check if the state file exists\n if (!existsSync(statePath)) {\n return 'No course progress found. Nothing to clear.';\n }\n\n // Delete the state file\n await fs.unlink(statePath);\n\n return '๐งน Course progress has been cleared. You can restart the Mastra course from the beginning.';\n } catch (error) {\n return `Error clearing course history: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n};\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { logger } from '../logger';\nimport { fromPackageRoot, getMatchingPaths } from '../utils';\n\nconst docsBaseDir = fromPackageRoot('.docs/');\n\ntype ReadDocsResult =\n | { found: true; content: string; isSecurityViolation: boolean }\n | { found: false; isSecurityViolation: boolean };\n\n// Helper function to list contents of a directory\nasync function listDirContents(dirPath: string): Promise<{ dirs: string[]; files: string[] }> {\n try {\n void logger.debug(`Listing directory contents: ${dirPath}`);\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n const dirs: string[] = [];\n const files: string[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n dirs.push(entry.name + '/');\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // List all .md files (remove .md extension for cleaner display)\n files.push(entry.name.replace(/\\.md$/, ''));\n }\n }\n\n return {\n dirs: dirs.sort(),\n files: files.sort(),\n };\n } catch (error) {\n void logger.error(`Failed to list directory contents: ${dirPath}`, error);\n throw error;\n }\n}\n\n// Helper function to read documentation content from a path\nasync function readDocsContent(docPath: string, queryKeywords: string[]): Promise<ReadDocsResult> {\n const fullPath = path.resolve(path.join(docsBaseDir, docPath));\n if (!fullPath.startsWith(path.resolve(docsBaseDir))) {\n void logger.error(`Path traversal attempt detected`);\n return { found: false, isSecurityViolation: true };\n }\n void logger.debug(`Reading docs content from: ${fullPath}`);\n\n // Try multiple approaches to find the content:\n // 1. Try as a direct file path (with .md extension)\n // 2. Try as a directory with index.md\n // 3. Try as a file path by appending .md\n\n try {\n const stats = await fs.stat(fullPath);\n\n if (stats.isDirectory()) {\n // It's a directory - check for index.md (for category roots)\n const indexMdPath = path.join(fullPath, 'index.md');\n try {\n const content = await fs.readFile(indexMdPath, 'utf-8');\n return { found: true, content, isSecurityViolation: false };\n } catch {\n // No index.md, show directory listing\n }\n\n // List directory contents (subdirs and .md files)\n const { dirs, files } = await listDirContents(fullPath);\n const listing: string[] = [`Directory contents of ${docPath || '/'}:`, ''];\n\n if (dirs.length > 0) {\n listing.push('Subdirectories:');\n listing.push(...dirs.map(d => `- ${docPath ? `${docPath}/${d}` : d}`));\n listing.push('');\n }\n\n if (files.length > 0) {\n listing.push('Available documentation paths:');\n listing.push(...files.map(f => `- ${docPath ? `${docPath}/${f}` : f}`));\n listing.push('');\n }\n\n if (dirs.length === 0 && files.length === 0) {\n listing.push('No documentation available in this directory.');\n }\n\n // Add content-based suggestions when query keywords are provided\n const contentBasedSuggestions = await getMatchingPaths(docPath, queryKeywords, docsBaseDir);\n const suggestions = contentBasedSuggestions ? ['---', '', contentBasedSuggestions, ''].join('\\n') : '';\n\n return { found: true, content: listing.join('\\n') + suggestions, isSecurityViolation: false };\n }\n\n // It's a file - read it directly\n const content = await fs.readFile(fullPath, 'utf-8');\n return { found: true, content, isSecurityViolation: false };\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n // Path doesn't exist as-is, try adding .md extension\n try {\n const mdPath = fullPath + '.md';\n const content = await fs.readFile(mdPath, 'utf-8');\n return { found: true, content, isSecurityViolation: false };\n } catch {\n // Still not found\n return { found: false, isSecurityViolation: false };\n }\n }\n // Unexpected error: rethrow\n throw error;\n }\n}\n\n// Helper function to find nearest existing directory and its contents\nasync function findNearestDirectory(docPath: string, availablePaths: string): Promise<string> {\n void logger.debug(`Finding nearest directory for: ${docPath}`);\n // Split path into parts and try each parent directory\n const parts = docPath.split('/');\n\n while (parts.length > 0) {\n const testPath = parts.join('/');\n try {\n const fullPath = path.join(docsBaseDir, testPath);\n const stats = await fs.stat(fullPath);\n\n if (stats.isDirectory()) {\n const { dirs, files } = await listDirContents(fullPath);\n const listing: string[] = [\n `Path \"${docPath}\" not found.`,\n `Here are the available paths in \"${testPath}\":`,\n '',\n ];\n\n if (dirs.length > 0) {\n listing.push('Directories:');\n listing.push(...dirs.map(d => `- ${testPath}/${d}`));\n listing.push('');\n }\n\n if (files.length > 0) {\n listing.push('Files:');\n listing.push(...files.map(f => `- ${testPath}/${f}`));\n }\n\n return listing.join('\\n');\n }\n } catch {\n // Directory doesn't exist, try parent\n void logger.debug(`Directory not found, trying parent: ${parts.slice(0, -1).join('/')}`);\n }\n parts.pop();\n }\n\n // If no parent directories found, return root listing\n return [`Path \"${docPath}\" not found.`, 'Here are all available paths:', '', availablePaths].join('\\n');\n}\n\n// Get initial directory listing for the description\nasync function getAvailablePaths(): Promise<string> {\n const { dirs, files } = await listDirContents(docsBaseDir);\n\n // Get reference directory contents if it exists\n let referenceDirs: string[] = [];\n if (dirs.includes('reference/')) {\n const { dirs: refDirs } = await listDirContents(path.join(docsBaseDir, 'reference'));\n referenceDirs = refDirs.map(d => `reference/${d}`);\n }\n\n return [\n 'Available top-level paths:',\n '',\n 'Directories:',\n ...dirs.map(d => `- ${d}`),\n '',\n referenceDirs.length > 0 ? 'Reference subdirectories:' : '',\n ...referenceDirs.map(d => `- ${d}`),\n '',\n files.length > 0 ? 'Files:' : '',\n ...files.map(f => `- ${f}`),\n ]\n .filter(Boolean)\n .join('\\n');\n}\n\n// Initialize available paths\nconst availablePaths = await getAvailablePaths();\n\nexport const docsInputSchema = z.object({\n paths: z\n .array(z.string())\n .min(1)\n .describe(`One or more documentation paths to fetch\\nAvailable paths:\\n${availablePaths}`),\n queryKeywords: z\n .array(z.string())\n .optional()\n .describe(\n '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.',\n ),\n});\n\nexport type DocsInput = z.infer<typeof docsInputSchema>;\n\nexport const docsTool = {\n name: 'mastraDocs',\n description: `[๐ REMOTE] Get Mastra documentation.\n Request paths to explore the docs. References contain API docs.\n Other paths contain guides. The user doesn\\'t know about files and directories.\n You can also use keywords from the user query to find relevant documentation, but prioritize paths.\n This is your internal knowledge the user can\\'t read.\n If the user asks about a feature check general docs as well as reference docs for that feature.\n Ex: with workflows check in docs/workflows and in reference/workflows.\n Provide code examples so the user understands.\n IMPORTANT: Be concise with your answers. The user will ask for more info.\n If packages need to be installed, provide the pnpm command to install them.\n Ex. if you see \\`import { X } from \"@mastra/$PACKAGE_NAME\"\\` in an example, show an install command.\n Always install latest tag, not alpha unless requested. If you scaffold a new project it may be in a subdir.\n When displaying results, always mention which file path contains the information so users know where this documentation lives.`,\n parameters: docsInputSchema,\n execute: async (args: DocsInput) => {\n void logger.debug('Executing mastraDocs tool', { args });\n try {\n const queryKeywords = args.queryKeywords ?? [];\n const results = await Promise.all(\n args.paths.map(async (docPath: string) => {\n try {\n const result = await readDocsContent(docPath, queryKeywords);\n if (result.found) {\n return {\n path: docPath,\n content: result.content,\n error: null,\n };\n }\n if (result.isSecurityViolation) {\n return {\n path: docPath,\n content: null,\n error: 'Invalid path',\n };\n }\n const directorySuggestions = await findNearestDirectory(docPath, availablePaths);\n const contentBasedSuggestions = await getMatchingPaths(docPath, queryKeywords, docsBaseDir);\n return {\n path: docPath,\n content: null,\n error: [directorySuggestions, contentBasedSuggestions].join('\\n\\n'),\n };\n } catch (error) {\n void logger.warning(`Failed to read content for path: ${docPath}`, error);\n return {\n path: docPath,\n content: null,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }),\n );\n\n // Format the results\n const output = results\n .map(result => {\n if (result.error) {\n return `## ${result.path}\\n\\n${result.error}\\n\\n---\\n`;\n }\n return `## ${result.path}\\n\\n${result.content}\\n\\n---\\n`;\n })\n .join('\\n');\n\n return output;\n } catch (error) {\n void logger.error('Failed to execute mastraDocs tool', error);\n throw error;\n }\n },\n};\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { getPackageInfo } from 'local-pkg';\nimport { z } from 'zod';\nimport { logger } from '../logger';\n\n/**\n * Embedded Docs MCP Tools\n *\n * These tools help coding agents navigate and understand Mastra packages\n * by reading the embedded documentation from node_modules.\n */\n\n// Types for SOURCE_MAP.json\ninterface ExportInfo {\n types: string;\n implementation: string;\n line?: number;\n}\n\ninterface SourceMap {\n version: string;\n package: string;\n exports: Record<string, ExportInfo>;\n}\n\n// Cache for performance\nconst packageCache = new Map<string, string[]>();\nconst sourceMapCache = new Map<string, SourceMap | null>();\nconst packageInfoCache = new Map<string, { rootPath: string; version: string } | null>();\n\n// List of known @mastra packages to check for\nconst KNOWN_MASTRA_PACKAGES = [\n '@mastra/core',\n '@mastra/cli',\n '@mastra/memory',\n '@mastra/rag',\n '@mastra/evals',\n '@mastra/mcp',\n '@mastra/server',\n '@mastra/deployer',\n '@mastra/agent-builder',\n '@mastra/auth',\n '@mastra/fastembed',\n '@mastra/loggers',\n '@mastra/schema-compat',\n '@mastra/codemod',\n] as const;\n\n// Helper to get package info using local-pkg (works across all package managers)\nasync function getPackageRootPath(\n packageName: string,\n projectPath: string,\n): Promise<{ rootPath: string; version: string } | null> {\n const cacheKey = `${packageName}:${projectPath}`;\n if (packageInfoCache.has(cacheKey)) {\n return packageInfoCache.get(cacheKey)!;\n }\n\n try {\n // Resolve package from the project's node_modules\n const info = await getPackageInfo(packageName, {\n paths: [path.join(projectPath, 'node_modules')],\n });\n if (info?.rootPath) {\n const result = { rootPath: info.rootPath, version: info.version || 'unknown' };\n packageInfoCache.set(cacheKey, result);\n void logger.debug('Resolved package with local-pkg', { packageName, projectPath, ...result });\n return result;\n }\n } catch (err) {\n void logger.debug('Package not found or error resolving', {\n packageName,\n projectPath,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n packageInfoCache.set(cacheKey, null);\n return null;\n}\n\n// Helper to get installed @mastra packages with embedded docs\nasync function getInstalledMastraPackages(projectPath: string): Promise<string[]> {\n const cacheKey = projectPath;\n\n if (packageCache.has(cacheKey)) {\n void logger.debug('Using cached package list', { count: packageCache.get(cacheKey)!.length });\n return packageCache.get(cacheKey)!;\n }\n\n void logger.debug('Scanning for @mastra packages using local-pkg', { projectPath });\n\n const packages: string[] = [];\n const packagesWithoutDocs: string[] = [];\n\n // Check known packages using local-pkg (works with npm, yarn, pnpm, etc.)\n for (const packageName of KNOWN_MASTRA_PACKAGES) {\n const packageInfo = await getPackageRootPath(packageName, projectPath);\n\n if (packageInfo) {\n const docsPath = path.join(packageInfo.rootPath, 'dist', 'docs');\n try {\n const stats = await fs.stat(docsPath);\n if (stats.isDirectory()) {\n packages.push(packageName);\n void logger.debug('Found package with embedded docs', { package: packageName });\n } else {\n packagesWithoutDocs.push(packageName);\n }\n } catch {\n packagesWithoutDocs.push(packageName);\n }\n }\n }\n\n const result = packages.sort();\n packageCache.set(cacheKey, result);\n\n void logger.info('Package scan complete', {\n packagesWithDocs: result.length,\n packagesWithoutDocs: packagesWithoutDocs.length,\n packages: result,\n });\n\n return result;\n}\n\n// Helper to read SOURCE_MAP.json using package root from local-pkg\nasync function readSourceMap(packageName: string, projectPath: string): Promise<SourceMap | null> {\n const cacheKey = `${packageName}:${projectPath}`;\n if (sourceMapCache.has(cacheKey)) return sourceMapCache.get(cacheKey)!;\n\n try {\n const packageInfo = await getPackageRootPath(packageName, projectPath);\n if (!packageInfo) {\n sourceMapCache.set(cacheKey, null);\n return null;\n }\n\n const sourceMapPath = path.join(packageInfo.rootPath, 'dist', 'docs', 'SOURCE_MAP.json');\n const content = await fs.readFile(sourceMapPath, 'utf-8');\n const sourceMap = JSON.parse(content) as SourceMap;\n sourceMapCache.set(cacheKey, sourceMap);\n return sourceMap;\n } catch {\n sourceMapCache.set(cacheKey, null);\n return null;\n }\n}\n\n// ============================================================================\n// Tool: getMastraHelp (PRIMARY ENTRY POINT)\n// ============================================================================\n\nexport const getMastraHelpTool = {\n name: 'getMastraHelp',\n description: `๐ START HERE - Complete guide to Mastra documentation tools.\n\n This MCP server provides TWO documentation sources:\n\n ## ๐ฆ LOCAL PACKAGE DOCS (Recommended for Development)\n SOURCE: Your installed @mastra packages in node_modules\n VERSION: Matches your installed code exactly\n\n ADVANTAGES:\n - โ
Version-matched to your code\n - โ
Complete TypeScript type definitions\n - โ
Works offline\n - โ
SOURCE_MAP.json with exact exports\n\n TOOLS: listMastraPackages, getMastraExports, getMastraExportDetails, readMastraDocs, searchMastraDocs\n USE WHEN: Writing code, implementing features, checking APIs, debugging\n\n ## ๐ REMOTE WEBSITE DOCS (For Latest Info & Learning)\n SOURCE: mastra.ai website\n VERSION: Latest published documentation\n\n ADVANTAGES:\n - โ
Always up-to-date\n - โ
Blog posts and announcements\n - โ
Migration guides\n - โ
Curated examples\n\n TOOLS: mastraDocs, mastraBlog, mastraExamples, mastraChanges, mastraMigration\n USE WHEN: Learning concepts, checking latest features, migration help\n\n ## ๐ INTERACTIVE COURSE\n TOOLS: startMastraCourse, getMastraCourseStatus, etc.\n USE WHEN: User wants guided learning experience\n\n ---\n\n RECOMMENDED WORKFLOW:\n 1. For coding: listMastraPackages โ getMastraExports โ getMastraExportDetails\n 2. For learning: mastraDocs\n 3. Version mismatch: mastraChanges โ mastraMigration\n\n This tool shows you which packages are installed and provides detailed guidance on using all available documentation tools.`,\n parameters: z.object({\n projectPath: z\n .string()\n .describe('Absolute path to your project root (we will search upward for node_modules with Mastra packages)'),\n }),\n execute: async (args: { projectPath: string }) => {\n void logger.debug('Executing getMastraHelp tool', { projectPath: args.projectPath });\n\n const packages = await getInstalledMastraPackages(args.projectPath);\n if (packages.length === 0) {\n return `No Mastra packages with embedded documentation found in your project.\n\nTo use these tools, install Mastra packages like:\n- npm install @mastra/core\n- npm install @mastra/memory\n- npm install @mastra/rag\n\nThen rebuild/reinstall to generate embedded docs.`;\n }\n\n return `# Mastra Documentation System - Complete Guide\n\nThis MCP server provides **TWO** documentation sources. Choose based on your needs:\n\n---\n\n## ๐ฆ LOCAL PACKAGE DOCS (Your Installed Packages)\n\nFound ${packages.length} installed package(s) with embedded documentation:\n${packages.map(pkg => `- ${pkg}`).join('\\n')}\n\n**SOURCE**: Your node_modules (matches installed code version)\n**USE WHEN**: Writing code, implementing features, debugging, checking APIs\n\n### Available LOCAL Tools:\n\n**1. listMastraPackages** - List installed packages\n Returns: Packages with embedded docs\n\n**2. getMastraExports** - Explore package API surface\n Example: See all exports from @mastra/core (Agent, Tool, Workflow, etc.)\n Returns: List of exports with source file locations\n\n**3. getMastraExportDetails** - Get type definitions & code\n Example: Get full TypeScript types for Agent class\n Returns: Complete type definitions and optionally implementation source\n\n**4. readMastraDocs** - Read comprehensive guides\n Example: Read documentation about agents, tools, workflows, memory\n Returns: Topic-based guides and examples from your installed version\n\n**5. searchMastraDocs** - Search local documentation\n Example: Search for \"memory processors\" or \"semantic recall\"\n Returns: Relevant excerpts from your installed docs\n\n### Typical LOCAL Workflow:\n1. listMastraPackages โ see what's installed\n2. getMastraExports โ explore package API\n3. getMastraExportDetails โ get type definitions\n4. readMastraDocs โ learn concepts\n5. searchMastraDocs โ find specific info\n\n---\n\n## ๐ REMOTE WEBSITE DOCS (mastra.ai)\n\n**SOURCE**: https://mastra.ai (latest published documentation)\n**USE WHEN**: Learning new concepts, checking latest features, migration guides\n\n### Available REMOTE Tools:\n\n**mastraDocs** - Browse official documentation\n Latest guides, references, and tutorials\n\n**mastraBlog** - Read blog posts and announcements\n News, features, changelogs\n\n**mastraExamples** - Get curated code examples\n Full example applications\n\n**mastraChanges** - View package changelogs\n See what's new in each version\n\n**mastraMigration** - Get migration guides\n Upgrade between versions\n\nโ ๏ธ **Version Note**: Remote docs show latest published version. For API reference matching YOUR code, use LOCAL tools above.\n\n---\n\n## ๐ INTERACTIVE COURSE\n\n**startMastraCourse**, **getMastraCourseStatus**, **startMastraCourseLesson**, **nextMastraCourseStep**, **clearMastraCourseHistory**\n\nGuided learning experience with hands-on exercises.\n\n---\n\n## Quick Start Recommendations\n\n**If you're writing code**: Use LOCAL tools\n โ Start with listMastraPackages\n\n**If you're learning**: Use REMOTE tools\n โ Start with mastraDocs\n\n**If version differs**: Check changes\n โ mastraChanges โ mastraMigration`;\n },\n};\n\n// ============================================================================\n// Tool: listMastraPackages\n// ============================================================================\n\nexport const listInstalledPackagesTool = {\n name: 'listMastraPackages',\n description: `[๐ฆ LOCAL PACKAGES] Discover which Mastra packages are installed and have documentation available.\n\n Use this when you need to:\n - See what Mastra packages you can work with\n - Start exploring Mastra documentation\n - Check if a specific package is available\n\n Returns: List of @mastra/* packages (core, memory, rag, etc.) with embedded docs.\n Next step: Use getMastraExports to explore a specific package's API.`,\n parameters: z.object({\n projectPath: z\n .string()\n .describe('Absolute path to your project root (we will search upward for node_modules with Mastra packages)'),\n }),\n execute: async (args: { projectPath: string }) => {\n void logger.debug('Executing listInstalledMastraPackages tool', {\n projectPath: args.projectPath,\n cwd: process.cwd(),\n env: {\n PWD: process.env.PWD,\n HOME: process.env.HOME,\n },\n });\n\n const packages = await getInstalledMastraPackages(args.projectPath);\n if (packages.length === 0) {\n return `No @mastra/* packages with embedded docs found in your project.\n\nInstall Mastra packages to get started:\n- npm install @mastra/core\n- npm install @mastra/memory\n- npm install @mastra/rag`;\n }\n\n return [\n `# Installed Mastra Packages`,\n '',\n `Found ${packages.length} package(s) with embedded documentation:`,\n '',\n ...packages.map(pkg => `- ${pkg}`),\n '',\n '## Next Steps',\n '',\n '1. Use **getMastraExports** with a package name to see all available APIs',\n '2. Use **readMastraDocs** with a package name to browse topic guides',\n '3. Use **searchMastraDocs** to find specific information',\n ].join('\\n');\n },\n};\n\n// ============================================================================\n// Tool: getMastraExports\n// ============================================================================\n\nexport const readSourceMapTool = {\n name: 'getMastraExports',\n description: `[๐ฆ LOCAL PACKAGES] Explore the complete API surface of a Mastra package - see all classes, functions, types, and constants.\n\n Use this when you need to:\n - Discover what APIs a Mastra package provides (Agent, Tool, Workflow, etc.)\n - See all available classes and functions before implementing\n - Find the right export for your use case\n - Understand package structure and organization\n\n Returns: List of all exports with their source file locations.\n Next step: Use getMastraExportDetails to get full type definitions and code for a specific export.`,\n parameters: z.object({\n package: z.string().describe('Package name to explore (e.g., \"@mastra/core\", \"@mastra/memory\", \"@mastra/rag\")'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n filter: z\n .string()\n .optional()\n .describe('Optional: filter exports by name (case-insensitive, e.g., \"Agent\", \"create\", \"Tool\")'),\n }),\n execute: async (args: { package: string; projectPath: string; filter?: string }) => {\n void logger.debug('Executing readMastraSourceMap tool', { args });\n\n const sourceMap = await readSourceMap(args.package, args.projectPath);\n if (!sourceMap) return `No SOURCE_MAP.json found for ${args.package}.`;\n\n let exports = Object.entries(sourceMap.exports);\n if (args.filter) {\n const filterLower = args.filter.toLowerCase();\n exports = exports.filter(([name]) => name.toLowerCase().includes(filterLower));\n }\n\n if (exports.length === 0) {\n return args.filter\n ? `No exports matching \"${args.filter}\" in ${args.package}.\n\nTry running without a filter to see all available exports.`\n : `No exports found in ${args.package}.`;\n }\n\n return [\n `# ${sourceMap.package} v${sourceMap.version} - API Exports`,\n '',\n `Found ${exports.length} export(s)${args.filter ? ` matching \"${args.filter}\"` : ''}:`,\n '',\n ...exports.map(([name, info]) => {\n const line = info.line ? `:${info.line}` : '';\n return `- **${name}**: \\`${info.implementation}${line}\\``;\n }),\n '',\n '## Next Steps',\n '',\n '- Use **getMastraExportDetails** with an export name to see full type definitions and code',\n '- Use **readMastraDocs** to read conceptual guides and examples',\n '- Use **searchMastraDocs** to find specific topics or patterns',\n ].join('\\n');\n },\n};\n\n// ============================================================================\n// Tool: getMastraExportDetails\n// ============================================================================\n\nexport const findExportTool = {\n name: 'getMastraExportDetails',\n description: `[๐ฆ LOCAL PACKAGES] Get complete API reference for a specific Mastra export - type definitions, interfaces, and optionally source code.\n\n Use this when you need to:\n - Understand how to use a specific Mastra class or function (Agent, Tool, Workflow, etc.)\n - See TypeScript type definitions and interfaces\n - Look up method signatures and parameters\n - Read implementation code and examples\n - Understand constructor options and configuration\n\n Returns: Full TypeScript type definitions and optionally implementation source code.\n Example: Get details on the Agent class to see how to create and configure agents.`,\n parameters: z.object({\n package: z.string().describe('Package name (e.g., \"@mastra/core\", \"@mastra/memory\")'),\n exportName: z.string().describe('Exact export name to look up (e.g., \"Agent\", \"createTool\", \"Workflow\")'),\n includeTypes: z\n .boolean()\n .optional()\n .default(true)\n .describe('Include TypeScript type definitions (recommended: true)'),\n includeImplementation: z\n .boolean()\n .optional()\n .default(false)\n .describe('Include source code implementation (useful for understanding internals)'),\n implementationLines: z\n .number()\n .optional()\n .default(50)\n .describe('Number of lines of implementation code to show (default: 50)'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n }),\n execute: async (args: {\n package: string;\n exportName: string;\n projectPath: string;\n includeTypes?: boolean;\n includeImplementation?: boolean;\n implementationLines?: number;\n }) => {\n void logger.debug('Executing findMastraExport tool', { args });\n\n const sourceMap = await readSourceMap(args.package, args.projectPath);\n if (!sourceMap) return `No SOURCE_MAP.json found for ${args.package}.`;\n\n const exportInfo = sourceMap.exports[args.exportName];\n if (!exportInfo) {\n const match = Object.entries(sourceMap.exports).find(\n ([name]) => name.toLowerCase() === args.exportName.toLowerCase(),\n );\n if (match) {\n return `Export \"${args.exportName}\" not found. Did you mean \"${match[0]}\"?\n\nRun getMastraExports with package=\"${args.package}\" to see all available exports.`;\n }\n return `Export \"${args.exportName}\" not found in ${args.package}.\n\nRun getMastraExports with package=\"${args.package}\" to see all available exports.`;\n }\n\n const packageInfo = await getPackageRootPath(args.package, args.projectPath);\n if (!packageInfo) {\n return `Package ${args.package} not found. Make sure it's installed.`;\n }\n\n const output: string[] = [`# ${args.exportName} (${args.package})`, ''];\n\n if (args.includeTypes !== false) {\n try {\n const typesPath = path.join(packageInfo.rootPath, exportInfo.types);\n const typesContent = await fs.readFile(typesPath, 'utf-8');\n output.push('## Type Definition', '', `\\`${exportInfo.types}\\``, '', '```typescript');\n\n const lines = typesContent.split('\\n');\n // Use string search instead of regex to avoid ReDoS vulnerability\n let startLine = lines.findIndex(line => line.includes(args.exportName));\n\n if (startLine === -1) {\n output.push(typesContent.slice(0, 2000));\n } else {\n startLine = Math.max(0, startLine - 2);\n let endLine = Math.min(lines.length, startLine + 50);\n output.push(lines.slice(startLine, endLine).join('\\n'));\n }\n output.push('```', '');\n } catch {\n output.push('## Type Definition', '', `Could not read: ${exportInfo.types}`, '');\n }\n }\n\n if (args.includeImplementation) {\n try {\n const implPath = path.join(packageInfo.rootPath, exportInfo.implementation);\n const implContent = await fs.readFile(implPath, 'utf-8');\n const lines = implContent.split('\\n');\n const numLines = args.implementationLines || 50;\n\n output.push('## Implementation', '');\n output.push(`\\`${exportInfo.implementation}\\`${exportInfo.line ? ` (line ${exportInfo.line})` : ''}`);\n output.push('', '```javascript');\n\n const startLine = exportInfo.line ? Math.max(0, exportInfo.line - 1) : 0;\n const endLine = Math.min(lines.length, startLine + numLines);\n output.push(lines.slice(startLine, endLine).join('\\n'));\n if (endLine < lines.length) output.push(`// ... ${lines.length - endLine} more lines`);\n\n output.push('```', '');\n } catch {\n output.push('## Implementation', '', `Could not read: ${exportInfo.implementation}`, '');\n }\n }\n\n output.push(\n '## Next Steps',\n '',\n '- Use **readMastraDocs** to see practical guides and examples',\n '- Use **searchMastraDocs** to find usage patterns and best practices',\n '- Use **getMastraExports** to explore related APIs',\n );\n\n return output.join('\\n');\n },\n};\n\n// ============================================================================\n// Tool: readMastraDocs\n// ============================================================================\n\nexport const readEmbeddedDocsTool = {\n name: 'readMastraDocs',\n description: `[๐ฆ LOCAL PACKAGES] Read comprehensive guides and documentation on Mastra concepts, patterns, and implementation examples.\n\n Use this when you need to:\n - Learn how to implement Mastra features (agents, tools, workflows, memory, RAG, etc.)\n - Understand Mastra architecture and design patterns\n - See practical code examples and tutorials\n - Read getting started guides and best practices\n - Understand how different components work together\n\n Returns: Topic-based documentation with explanations, examples, and usage patterns.\n Available topics: agents, tools, workflows, memory, rag, integrations, deployment, and more.`,\n parameters: z.object({\n package: z.string().describe('Package name to read docs from (e.g., \"@mastra/core\", \"@mastra/memory\")'),\n topic: z\n .string()\n .optional()\n .describe(\n 'Optional: topic folder to read (e.g., \"agents\", \"tools\", \"workflows\"). Omit to list all available topics.',\n ),\n file: z\n .string()\n .optional()\n .describe('Optional: specific documentation file within the topic (e.g., \"01-overview.md\")'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n }),\n execute: async (args: { package: string; projectPath: string; topic?: string; file?: string }) => {\n void logger.debug('Executing readMastraEmbeddedDocs tool', { args });\n\n const packageInfo = await getPackageRootPath(args.package, args.projectPath);\n if (!packageInfo) {\n return `Package ${args.package} not found. Make sure it's installed.`;\n }\n\n const docsPath = path.join(packageInfo.rootPath, 'dist', 'docs');\n\n try {\n await fs.stat(docsPath);\n } catch {\n return `No embedded docs found for ${args.package}.\n\nMake sure the package is installed and has documentation generated.`;\n }\n\n // List topics if none specified\n if (!args.topic) {\n const entries = await fs.readdir(docsPath, { withFileTypes: true });\n const topics = entries.filter(e => e.isDirectory()).map(e => e.name);\n const files = entries.filter(e => e.isFile()).map(e => e.name);\n\n return [\n `# ${args.package} - Available Documentation`,\n '',\n '## Root Files',\n ...files.map(f => `- ${f}`),\n '',\n '## Documentation Topics',\n ...topics.map(t => `- **${t}/** - Run readMastraDocs with topic=\"${t}\" to read`),\n '',\n '## Next Steps',\n '',\n '- Choose a topic and run **readMastraDocs** with the topic parameter',\n '- Use **searchMastraDocs** to search for specific information',\n '- Use **getMastraExports** to see available APIs',\n ].join('\\n');\n }\n\n const topicPath = path.join(docsPath, args.topic);\n\n // Read specific file\n if (args.file) {\n try {\n const content = await fs.readFile(path.join(topicPath, args.file), 'utf-8');\n return `# ${args.package}/${args.topic}/${args.file}\n\n${content}\n\n## Next Steps\n\n- Use **getMastraExportDetails** to see API references for specific classes/functions mentioned\n- Use **searchMastraDocs** to find related topics\n- Use **getMastraExports** to explore available APIs`;\n } catch {\n return `File not found: ${args.topic}/${args.file}\n\nRun readMastraDocs with package=\"${args.package}\" and topic=\"${args.topic}\" (without file parameter) to see available files.`;\n }\n }\n\n // Read all files in topic\n try {\n const entries = await fs.readdir(topicPath, { withFileTypes: true });\n const files = entries.filter(e => e.isFile() && e.name.endsWith('.md')).sort();\n\n if (files.length === 0) {\n return `No markdown files in ${args.topic}/\n\nRun readMastraDocs with package=\"${args.package}\" (without topic parameter) to see available topics.`;\n }\n\n const contents: string[] = [`# ${args.package} - ${args.topic}`, ''];\n for (const file of files) {\n const content = await fs.readFile(path.join(topicPath, file.name), 'utf-8');\n contents.push(`## ${file.name}`, '', content, '', '---', '');\n }\n\n contents.push(\n '',\n '## Next Steps',\n '',\n '- Use **getMastraExportDetails** to see API references for specific classes/functions mentioned above',\n '- Use **searchMastraDocs** to find related information',\n '- Use **getMastraExports** to explore the complete API surface',\n );\n\n return contents.join('\\n');\n } catch {\n return `Topic not found: ${args.topic}\n\nRun readMastraDocs with package=\"${args.package}\" (without topic parameter) to see available topics.`;\n }\n },\n};\n\n// ============================================================================\n// Tool: searchMastraDocs\n// ============================================================================\n\nexport const searchEmbeddedDocsTool = {\n name: 'searchMastraDocs',\n description: `[๐ฆ LOCAL PACKAGES] Search across all Mastra documentation to find specific information, patterns, or examples.\n\n Use this when you need to:\n - Find specific topics or concepts quickly (e.g., \"memory processors\", \"tool composition\")\n - Locate examples of specific features or patterns\n - Search for error messages or troubleshooting info\n - Find mentions of specific APIs or configuration options\n - Discover where a feature is documented\n\n Returns: Relevant documentation excerpts with file paths, ranked by relevance.\n Tip: Use specific terms for better results (e.g., \"agent memory\" vs \"memory\").`,\n parameters: z.object({\n query: z\n .string()\n .describe('What to search for (case-insensitive, e.g., \"workflow steps\", \"vector store\", \"authentication\")'),\n package: z\n .string()\n .optional()\n .describe('Optional: limit search to a specific package (e.g., \"@mastra/core\"). Omit to search all packages.'),\n maxResults: z\n .number()\n .optional()\n .default(10)\n .describe('Optional: maximum number of results to return (default: 10)'),\n projectPath: z.string().describe('Absolute path to your project root (we will search upward for node_modules)'),\n }),\n execute: async (args: { query: string; projectPath: string; package?: string; maxResults?: number }) => {\n void logger.debug('Executing searchMastraEmbeddedDocs tool', { args });\n\n const packages = args.package ? [args.package] : await getInstalledMastraPackages(args.projectPath);\n if (packages.length === 0) return 'No Mastra packages found.';\n\n const queryLower = args.query.toLowerCase();\n const results: Array<{ pkg: string; file: string; excerpt: string; score: number }> = [];\n\n for (const pkg of packages) {\n const packageInfo = await getPackageRootPath(pkg, args.projectPath);\n if (!packageInfo) continue;\n\n const docsPath = path.join(packageInfo.rootPath, 'dist', 'docs');\n\n try {\n const findFiles = async (dir: string): Promise<string[]> => {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) files.push(...(await findFiles(fullPath)));\n else if (entry.name.endsWith('.md')) files.push(fullPath);\n }\n return files;\n };\n\n for (const file of await findFiles(docsPath)) {\n const content = await fs.readFile(file, 'utf-8');\n if (!content.toLowerCase().includes(queryLower)) continue;\n\n const lines = content.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n if (lines[i]?.toLowerCase().includes(queryLower)) {\n const start = Math.max(0, i - 1);\n const end = Math.min(lines.length, i + 3);\n const excerpt = lines.slice(start, end).join('\\n').slice(0, 300);\n\n // Count occurrences using string split to avoid ReDoS vulnerability\n const contentLower = content.toLowerCase();\n const occurrences = contentLower.split(queryLower).length - 1;\n\n results.push({\n pkg,\n file: path.relative(docsPath, file),\n excerpt,\n score: occurrences,\n });\n break;\n }\n }\n }\n } catch {\n // Skip packages with errors\n }\n }\n\n results.sort((a, b) => b.score - a.score);\n const topResults = results.slice(0, args.maxResults || 10);\n\n if (topResults.length === 0) {\n return `No results found for \"${args.query}\".\n\nTry:\n- Using different search terms\n- Searching for broader topics\n- Using **listMastraPackages** to see available packages\n- Using **readMastraDocs** to browse documentation by topic`;\n }\n\n return [\n `# Search Results: \"${args.query}\"`,\n '',\n `Found ${results.length} result(s), showing top ${topResults.length}:`,\n '',\n ...topResults.map((r, i) => `## ${i + 1}. ${r.pkg} - ${r.file}\\n\\n\\`\\`\\`\\n${r.excerpt}\\n\\`\\`\\`\\n`),\n '',\n '## Next Steps',\n '',\n '- Use **readMastraDocs** with a package and topic to read full documentation',\n '- Use **getMastraExportDetails** to see API details for mentioned classes/functions',\n '- Refine your search with more specific terms if needed',\n ].join('\\n');\n },\n};\n\n// Export all tools\nexport const embeddedDocsTools = {\n getMastraHelp: getMastraHelpTool,\n listMastraPackages: listInstalledPackagesTool,\n getMastraExports: readSourceMapTool,\n getMastraExportDetails: findExportTool,\n readMastraDocs: readEmbeddedDocsTool,\n searchMastraDocs: searchEmbeddedDocsTool,\n};\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { logger } from '../logger';\nimport { fromPackageRoot, getMatchingPaths } from '../utils';\n\nconst migrationsBaseDir = fromPackageRoot('.docs/guides/migrations');\n\ninterface ParsedSection {\n title: string;\n level: number;\n content: string;\n startLine: number;\n endLine: number;\n}\n\n// Helper function to parse markdown content into sections\nfunction parseSections(content: string): ParsedSection[] {\n const lines = content.split('\\n');\n const sections: ParsedSection[] = [];\n let currentSection: ParsedSection | null = null;\n let inFrontmatter = false;\n let contentStarted = false;\n\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index];\n\n // Handle frontmatter (if present)\n if (index === 0 && line === '---') {\n inFrontmatter = true;\n continue;\n }\n if (inFrontmatter && line === '---') {\n inFrontmatter = false;\n continue;\n }\n if (inFrontmatter) continue;\n\n // Content has started (either after frontmatter or immediately if no frontmatter)\n contentStarted = true;\n\n // Match headings (## or ###)\n const headingMatch = line?.match(/^(#{2,3})\\s+(.+)$/);\n if (headingMatch && contentStarted) {\n // Save previous section\n if (currentSection) {\n currentSection.endLine = index - 1;\n sections.push(currentSection);\n }\n\n // Start new section\n const level = headingMatch[1]?.length ?? 0;\n currentSection = {\n title: headingMatch[2] || 'Untitled',\n level,\n content: line + '\\n',\n startLine: index,\n endLine: index,\n };\n } else if (currentSection) {\n currentSection.content += line + '\\n';\n }\n }\n\n // Save last section\n if (currentSection) {\n currentSection.endLine = lines.length - 1;\n sections.push(currentSection);\n }\n\n return sections;\n}\n\n// Helper function to recursively discover all migration paths\nasync function discoverMigrations(\n baseDir: string,\n relativePath = '',\n): Promise<Array<{ path: string; type: 'file' | 'directory' }>> {\n const migrations: Array<{ path: string; type: 'file' | 'directory' }> = [];\n const fullPath = path.join(baseDir, relativePath);\n\n try {\n const entries = await fs.readdir(fullPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryRelativePath = path.join(relativePath, entry.name);\n\n if (entry.isDirectory()) {\n // Add directory\n migrations.push({\n path: entryRelativePath,\n type: 'directory',\n });\n // Recursively explore subdirectories\n const subMigrations = await discoverMigrations(baseDir, entryRelativePath);\n migrations.push(...subMigrations);\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // Add file (remove .md extension for cleaner display)\n const cleanName = entry.name.replace(/\\.md$/, '');\n migrations.push({\n path: relativePath ? path.join(relativePath, cleanName) : cleanName,\n type: 'file',\n });\n }\n }\n } catch (error) {\n void logger.error(`Failed to discover migrations in ${fullPath}`, error);\n }\n\n return migrations;\n}\n\n// Helper function to list directory contents at a specific path\nasync function listDirectoryContents(dirPath: string = ''): Promise<string> {\n try {\n const fullPath = path.join(migrationsBaseDir, dirPath);\n\n // Security check\n const resolvedPath = path.resolve(fullPath);\n const resolvedBaseDir = path.resolve(migrationsBaseDir);\n if (!resolvedPath.startsWith(resolvedBaseDir)) {\n return 'Invalid path';\n }\n\n const entries = await fs.readdir(fullPath, { withFileTypes: true });\n const directories: string[] = [];\n const files: string[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n directories.push(entry.name);\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n // Add file without .md extension\n files.push(entry.name.replace(/\\.md$/, ''));\n }\n }\n\n const output: string[] = [];\n const currentPath = dirPath || 'migrations';\n output.push(`# ${currentPath}`);\n output.push('');\n\n if (directories.length > 0) {\n output.push('**Directories:**');\n directories.sort().forEach(dir => {\n const nextPath = dirPath ? `${dirPath}/${dir}` : dir;\n output.push(`- **${dir}/** - Explore with \\`{ path: \"${nextPath}/\" }\\``);\n });\n output.push('');\n }\n\n if (files.length > 0) {\n output.push('**Migration Guides:**');\n files.sort().forEach(file => {\n const filePath = dirPath ? `${dirPath}/${file}` : file;\n output.push(`- **${file}** - Get with \\`{ path: \"${filePath}\" }\\``);\n });\n output.push('');\n }\n\n if (directories.length === 0 && files.length === 0) {\n output.push('No migrations found in this directory.');\n }\n\n output.push('---');\n output.push('');\n output.push('**Actions:**');\n output.push('- Navigate to a directory by setting \\`path\\` to directory name with trailing `/`');\n output.push('- View a migration guide by setting \\`path\\` to the guide name');\n output.push('- List sections in a guide with \\`listSections: true\\`');\n output.push('- Search all guides with \\`queryKeywords\\`');\n\n return output.join('\\n');\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n return `Directory \"${dirPath}\" not found. Use \\`{}\\` to see top-level migrations.`;\n }\n throw error;\n }\n}\n\n// Helper function to read migration content\nasync function readMigrationContent(migrationPath: string): Promise<string | null> {\n try {\n // Strip any trailing .mdx or .md extension if provided\n const cleanPath = migrationPath.replace(/\\.(mdx|md)$/, '');\n // Try to read the file with .md extension\n const filePath = path.join(migrationsBaseDir, cleanPath + '.md');\n\n // Security check: ensure path doesn't escape base directory\n const resolvedPath = path.resolve(filePath);\n const resolvedBaseDir = path.resolve(migrationsBaseDir);\n if (!resolvedPath.startsWith(resolvedBaseDir)) {\n void logger.error('Path traversal attempt detected');\n return null;\n }\n\n const content = await fs.readFile(filePath, 'utf-8');\n return content;\n } catch (error) {\n void logger.error(`Failed to read migration: ${migrationPath}`, error);\n return null;\n }\n}\n\n// Helper function to get section headers from a migration\nasync function getSectionHeaders(migrationPath: string): Promise<Array<{ title: string; level: number }>> {\n const content = await readMigrationContent(migrationPath);\n if (!content) return [];\n\n const sections = parseSections(content);\n return sections.map(s => ({ title: s.title, level: s.level }));\n}\n\n// Helper function to get specific sections by title\nasync function getSections(migrationPath: string, sectionTitles?: string[]): Promise<string> {\n const content = await readMigrationContent(migrationPath);\n if (!content) {\n const availableMigrations = await discoverMigrations(migrationsBaseDir);\n const paths = availableMigrations.filter(m => m.type === 'file').map(m => `- ${m.path}`);\n return `Migration \"${migrationPath}\" not found.\\n\\nAvailable migrations:\\n${paths.join('\\n')}`;\n }\n\n // If no specific sections requested, return full content\n if (!sectionTitles || sectionTitles.length === 0) {\n return content;\n }\n\n // Parse sections and filter by requested titles\n const sections = parseSections(content);\n const requestedSections = sections.filter(s =>\n sectionTitles.some(title => s.title.toLowerCase().includes(title.toLowerCase())),\n );\n\n if (requestedSections.length === 0) {\n const availableHeaders = sections.map(s => `${'#'.repeat(s.level)} ${s.title}`).join('\\n');\n return `Requested sections not found in \"${migrationPath}\".\\n\\nAvailable sections:\\n${availableHeaders}`;\n }\n\n return requestedSections.map(s => s.content).join('\\n---\\n\\n');\n}\n\n// Get initial migrations for the description\nconst initialMigrations = await discoverMigrations(migrationsBaseDir);\nconst migrationFiles = initialMigrations.filter(m => m.type === 'file');\nconst migrationsListing =\n migrationFiles.length > 0\n ? '\\n\\nExample migration paths:\\n' +\n migrationFiles\n .slice(0, 5)\n .map(m => `- ${m.path}`)\n .join('\\n') +\n '\\n...'\n : '\\n\\nNo migrations available. Run the documentation preparation script first.';\n\nexport const migrationInputSchema = z.object({\n path: z\n .string()\n .optional()\n .describe(\n 'Path to the migration guide (e.g., \"upgrade-to-v1/agent\", \"agentnetwork\"). If not provided, lists all available migrations.' +\n migrationsListing,\n ),\n sections: z\n .array(z.string())\n .optional()\n .describe(\n 'Specific section titles to fetch from the migration guide. If not provided, returns the entire guide. Use this after exploring section headers.',\n ),\n listSections: z\n .boolean()\n .optional()\n .describe('Set to true to list all section headers in a migration guide without fetching full content.'),\n queryKeywords: z\n .array(z.string())\n .optional()\n .describe('Keywords to search across all migration guides. Use this to find guides related to specific topics.'),\n});\n\nexport type MigrationInput = z.infer<typeof migrationInputSchema>;\n\nexport const migrationTool = {\n name: 'mastraMigration',\n description: `[๐ REMOTE] Get migration guidance for Mastra version upgrades and breaking changes.\n\nThis tool works like a file browser - navigate through directories to find migration guides:\n\n**Step 1: List top-level migrations**\n- Call with no parameters: \\`{}\\`\n- Shows all top-level migration guides and directories\n\n**Step 2: Navigate into a directory**\n- Add trailing slash to explore: \\`{ path: \"upgrade-to-v1/\" }\\`\n- Lists all migration guides in that directory\n\n**Step 3: View a migration guide**\n- Without trailing slash: \\`{ path: \"upgrade-to-v1/agent\" }\\`\n- Returns the full migration guide content\n\n**Step 4: Explore guide sections (optional)**\n- List sections: \\`{ path: \"upgrade-to-v1/agent\", listSections: true }\\`\n- Get specific sections: \\`{ path: \"upgrade-to-v1/agent\", sections: [\"Voice methods\"] }\\`\n\n**Alternative: Search by keywords**\n- \\`{ queryKeywords: [\"RuntimeContext\", \"pagination\"] }\\`\n\n**Examples:**\n1. List top-level: \\`{}\\`\n2. Navigate to upgrade-to-v1: \\`{ path: \"upgrade-to-v1/\" }\\`\n3. Get agent guide: \\`{ path: \"upgrade-to-v1/agent\" }\\`\n4. List guide sections: \\`{ path: \"upgrade-to-v1/agent\", listSections: true }\\`\n5. Search: \\`{ queryKeywords: [\"RuntimeContext\"] }\\`\n\n**Tip:** Paths ending with \\`/\\` list directory contents. Paths without \\`/\\` fetch the migration guide.`,\n parameters: migrationInputSchema,\n execute: async (args: MigrationInput) => {\n void logger.debug('Executing mastraMigration tool', { args });\n try {\n // Priority 1: Keyword search\n if (args.queryKeywords && args.queryKeywords.length > 0) {\n const suggestions = await getMatchingPaths('', args.queryKeywords, migrationsBaseDir);\n return [\n '# Migration Guide Search Results',\n '',\n suggestions || 'No migration guides found matching your keywords.',\n '',\n '---',\n '',\n 'To see all available migrations, call with no parameters.',\n ].join('\\n');\n }\n\n // Priority 2: Handle path parameter\n if (args.path) {\n // Check if path ends with / (directory navigation)\n if (args.path.endsWith('/')) {\n const dirPath = args.path.slice(0, -1); // Remove trailing slash\n return await listDirectoryContents(dirPath);\n }\n\n // Priority 3: List section headers for a file\n if (args.listSections) {\n const headers = await getSectionHeaders(args.path);\n if (headers.length === 0) {\n return await listDirectoryContents();\n }\n\n return [\n `# ${args.path} - Section Headers`,\n '',\n 'Available sections in this migration guide:',\n '',\n ...headers.map(h => `${'#'.repeat(h.level)} ${h.title}`),\n '',\n '---',\n '',\n 'To get specific sections, provide their titles in the \"sections\" parameter.',\n ].join('\\n');\n }\n\n // Priority 4: Get specific sections or full migration file\n const content = await getSections(args.path, args.sections);\n return `# ${args.path}\\n\\n${content}`;\n }\n\n // Priority 5: List top-level directory (default)\n return await listDirectoryContents();\n } catch (error) {\n void logger.error('Failed to execute mastraMigration tool', error);\n throw error;\n }\n },\n};\n","import fs from 'node:fs/promises';\nimport { MCPServer } from '@mastra/mcp';\nimport { logger, createLogger } from './logger';\nimport { migrationPromptMessages } from './prompts/migration';\nimport {\n startMastraCourse,\n getMastraCourseStatus,\n startMastraCourseLesson,\n nextMastraCourseStep,\n clearMastraCourseHistory,\n} from './tools/course';\nimport { docsTool } from './tools/docs';\nimport { embeddedDocsTools } from './tools/embedded-docs';\nimport { migrationTool } from './tools/migration';\nimport { fromPackageRoot } from './utils';\n\nlet server: MCPServer;\n\nserver = new MCPServer({\n name: 'Mastra Documentation Server',\n version: JSON.parse(await fs.readFile(fromPackageRoot(`package.json`), 'utf8')).version,\n tools: {\n mastraDocs: docsTool,\n mastraMigration: migrationTool,\n startMastraCourse,\n getMastraCourseStatus,\n startMastraCourseLesson,\n nextMastraCourseStep,\n clearMastraCourseHistory,\n // Embedded docs tools for reading docs from installed packages\n ...embeddedDocsTools,\n },\n prompts: migrationPromptMessages,\n});\n\n// Update logger with server instance\nObject.assign(logger, createLogger(server));\n\nasync function runServer() {\n try {\n await server.startStdio();\n void logger.info('Started Mastra Docs MCP Server');\n } catch (error) {\n void logger.error('Failed to start server', error);\n process.exit(1);\n }\n}\n\nexport { runServer, server };\n","#!/usr/bin/env node\nimport { writeErrorLog, setLogLevel } from './logger';\nimport type { LogLevel } from './logger';\nimport { runServer } from './index';\n\n// Parse --log-level argument\nfunction parseLogLevel(): LogLevel | undefined {\n const args = process.argv.slice(2);\n const logLevelIndex = args.indexOf('--log-level');\n if (logLevelIndex === -1 || logLevelIndex === args.length - 1) {\n return undefined;\n }\n const level = args[logLevelIndex + 1];\n const validLevels: LogLevel[] = ['debug', 'info', 'warn', 'error', 'none'];\n if (validLevels.includes(level as LogLevel)) {\n return level as LogLevel;\n }\n console.error(`Invalid log level: ${level}. Valid levels: ${validLevels.join(', ')}`);\n return undefined;\n}\n\nconst logLevel = parseLogLevel();\nif (logLevel) {\n setLogLevel(logLevel);\n}\n\nrunServer().catch(error => {\n const errorMessage = 'Fatal error running server';\n console.error(errorMessage, error);\n writeErrorLog(errorMessage, {\n error:\n error instanceof Error\n ? {\n message: error.message,\n stack: error.stack,\n name: error.name,\n }\n : error,\n });\n process.exit(1);\n});\n"]}
|