> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 构建笔记 MCP 服务器 本指南将介绍如何从零构建完整的 MCP(Model Context Protocol)服务器。该服务器用于管理一组 Markdown 笔记,并提供以下功能: 1. **列出并读取笔记**:允许客户端浏览和查看服务器上存储的 Markdown 文件 2. **写入笔记**:提供用于创建或更新笔记的 Tool 3. **提供智能提示词**:生成上下文相关的提示词,例如创建每日笔记模板或总结现有内容 ## 前提条件 - 已安装 Node.js `v22.13.0` 或更高版本 - 受支持的[模型 Provider](https://mastra.zisheng.pro/models)所提供的 API 密钥 - 现有 Mastra 项目(按照[安装指南](https://mastra.zisheng.pro/guides/getting-started/quickstart)设置新项目) ## 添加必要的依赖项和文件 创建 MCP 服务器之前,需要先安装其他依赖项并设置样板文件夹结构。 1. 将 `@mastra/mcp` 添加到项目: **npm**: ```bash npm install @mastra/mcp@latest ``` **pnpm**: ```bash pnpm add @mastra/mcp@latest ``` **Yarn**: ```bash yarn add @mastra/mcp@latest ``` **Bun**: ```bash bun add @mastra/mcp@latest ``` 2. 按照默认[安装指南](https://mastra.zisheng.pro/guides/getting-started/quickstart)操作后,项目中会包含与本指南无关的文件。可以安全地将其删除: ```bash rm -rf src/mastra/agents src/mastra/workflows src/mastra/tools/weather-tool.ts ``` 还应按如下方式修改 `src/mastra/index.ts` 文件: ```ts import { Mastra } from '@mastra/core' import { PinoLogger } from '@mastra/loggers' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', // stores telemetry, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db url: ':memory:', }), logger: new PinoLogger({ name: 'Mastra', level: 'info', }), }) ``` 3. 为 MCP 服务器逻辑创建专用目录,并为笔记创建 `notes` 目录: ```bash mkdir notes src/mastra/mcp ``` 创建以下文件: ```bash touch src/mastra/mcp/{server,resources,prompts}.ts ``` - `server.ts`:包含 MCP 服务器的主要配置 - `resources.ts`:处理笔记文件的列出和读取 - `prompts.ts`:包含智能提示词的逻辑 最终目录结构应如下所示: ```text / ├── notes/ └── src/ └── mastra/ ├── index.ts ├── mcp/ │ ├── server.ts │ ├── resources.ts │ └── prompts.ts └── tools/ ``` ## 创建 MCP 服务器 下面添加 MCP 服务器。 1. 在 `src/mastra/mcp/server.ts` 中定义 MCP 服务器实例: ```typescript import { MCPServer } from '@mastra/mcp' export const notes = new MCPServer({ id: 'notes', name: 'Notes Server', version: '0.1.0', tools: {}, }) ``` 在 `src/mastra/index.ts` 的 Mastra 实例中注册此 MCP 服务器。`notes` key 是 MCP 服务器的公开标识符: ```typescript import { Mastra } from '@mastra/core' import { PinoLogger } from '@mastra/loggers' import { LibSQLStore } from '@mastra/libsql' import { notes } from './mcp/server' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', // stores telemetry, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db url: ':memory:', }), logger: new PinoLogger({ name: 'Mastra', level: 'info', }), mcpServers: { notes, }, }) ``` 2. Resource handler 允许客户端发现并读取服务器管理的内容。实现用于处理 `notes` 目录中 Markdown 文件的 handler。将以下内容添加到 `src/mastra/mcp/resources.ts` 文件: ```typescript import fs from 'fs/promises' import path from 'path' import { fileURLToPath } from 'url' import type { MCPServerResources, Resource } from '@mastra/mcp' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) const NOTES_DIR = path.resolve(__dirname, '../../notes') // relative to the default output directory const listNoteFiles = async (): Promise => { try { await fs.mkdir(NOTES_DIR, { recursive: true }) const files = await fs.readdir(NOTES_DIR) return files .filter(file => file.endsWith('.md')) .map(file => { const title = file.replace('.md', '') return { uri: `notes://${title}`, name: title, description: `A note about ${title}`, mime_type: 'text/markdown', } }) } catch (error) { console.error('Error listing note resources:', error) return [] } } const readNoteFile = async (uri: string): Promise => { const title = uri.replace('notes://', '') const notePath = path.join(NOTES_DIR, `${title}.md`) try { return await fs.readFile(notePath, 'utf-8') } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { console.error(`Error reading resource ${uri}:`, error) } return null } } export const resourceHandlers: MCPServerResources = { listResources: listNoteFiles, getResourceContent: async ({ uri }: { uri: string }) => { const content = await readNoteFile(uri) if (content === null) return { text: '' } return { text: content } }, } ``` 在 `src/mastra/mcp/server.ts` 中注册这些 resource handler: ```typescript import { MCPServer } from '@mastra/mcp' import { resourceHandlers } from './resources' export const notes = new MCPServer({ id: 'notes', name: 'Notes Server', version: '0.1.0', tools: {}, resources: resourceHandlers, }) ``` 3. Tool 是服务器可以执行的操作。下面创建一个 `write` Tool。 首先,在 `src/mastra/tools/write-note.ts` 中定义该 Tool: ```typescript import { createTool } from '@mastra/core/tools' import { z } from 'zod' import { fileURLToPath } from 'url' import path from 'node:path' import fs from 'fs/promises' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) const NOTES_DIR = path.resolve(__dirname, '../../../notes') export const writeNoteTool = createTool({ id: 'write', description: 'Write a new note or overwrite an existing one.', inputSchema: z.object({ title: z.string().nonempty().describe('The title of the note. This will be the filename.'), content: z.string().nonempty().describe('The markdown content of the note.'), }), outputSchema: z.string().nonempty(), execute: async inputData => { try { const { title, content } = inputData const filePath = path.join(NOTES_DIR, `${title}.md`) await fs.mkdir(NOTES_DIR, { recursive: true }) await fs.writeFile(filePath, content, 'utf-8') return `Successfully wrote to note \"${title}\".` } catch (error: any) { return `Error writing note: ${error.message}` } }, }) ``` 在 `src/mastra/mcp/server.ts` 中注册此 Tool: ```typescript import { MCPServer } from '@mastra/mcp' import { resourceHandlers } from './resources' import { writeNoteTool } from '../tools/write-note' export const notes = new MCPServer({ id: 'notes', name: 'Notes Server', version: '0.1.0', resources: resourceHandlers, tools: { write: writeNoteTool, }, }) ``` 4. Prompt handler 为客户端提供可直接使用的提示词。你将添加以下三个提示词: - 每日笔记 - 总结笔记 - 集思广益 这需要安装几个 Markdown 解析库: ```bash npm install unified remark-parse gray-matter @types/unist ``` 在 `src/mastra/mcp/prompts.ts` 中实现提示词: ```typescript import type { MCPServerPrompts } from '@mastra/mcp' import { unified } from 'unified' import remarkParse from 'remark-parse' import matter from 'gray-matter' import type { Node } from 'unist' const prompts = [ { name: 'new_daily_note', description: 'Create a new daily note.', version: '1.0.0', }, { name: 'summarize_note', description: 'Give me a TL;DR of the note.', version: '1.0.0', }, { name: 'brainstorm_ideas', description: 'Brainstorm new ideas based on a note.', version: '1.0.0', }, ] function stringifyNode(node: Node): string { if ('value' in node && typeof node.value === 'string') return node.value if ('children' in node && Array.isArray(node.children)) return node.children.map(stringifyNode).join('') return '' } export async function analyzeMarkdown(md: string) { const { content } = matter(md) const tree = unified().use(remarkParse).parse(content) const headings: string[] = [] const wordCounts: Record = {} let currentHeading = 'untitled' wordCounts[currentHeading] = 0 tree.children.forEach(node => { if (node.type === 'heading' && node.depth === 2) { currentHeading = stringifyNode(node) headings.push(currentHeading) wordCounts[currentHeading] = 0 } else { const textContent = stringifyNode(node) if (textContent.trim()) { wordCounts[currentHeading] = (wordCounts[currentHeading] || 0) + textContent.split(/\\s+/).length } } }) return { headings, wordCounts } } const getPromptMessages: MCPServerPrompts['getPromptMessages'] = async ({ name, args }) => { switch (name) { case 'new_daily_note': const today = new Date().toISOString().split('T')[0] return [ { role: 'user', content: { type: 'text', text: `Create a new note titled \"${today}\" with sections: \"## Tasks\", \"## Meetings\", \"## Notes\".`, }, }, ] case 'summarize_note': if (!args?.noteContent) throw new Error('No content provided') const metaSum = await analyzeMarkdown(args.noteContent as string) return [ { role: 'user', content: { type: 'text', text: `Summarize each section in ≤ 3 bullets.\\n\\n### Outline\\n${metaSum.headings.map(h => `- ${h} (${metaSum.wordCounts[h] || 0} words)`).join('\\n')}`.trim(), }, }, ] case 'brainstorm_ideas': if (!args?.noteContent) throw new Error('No content provided') const metaBrain = await analyzeMarkdown(args.noteContent as string) return [ { role: 'user', content: { type: 'text', text: `Brainstorm 3 ideas for underdeveloped sections below ${args?.topic ? `on ${args.topic}` : '.'}\\n\\nUnderdeveloped sections:\\n${metaBrain.headings.length ? metaBrain.headings.map(h => `- ${h}`).join('\\n') : '- (none, pick any)'}`, }, }, ] default: throw new Error(`Prompt \"${name}\" not found`) } } export const promptHandlers: MCPServerPrompts = { listPrompts: async () => prompts, getPromptMessages, } ``` 在 `src/mastra/mcp/server.ts` 中注册这些 prompt handler: ```typescript import { MCPServer } from '@mastra/mcp' import { resourceHandlers } from './resources' import { writeNoteTool } from '../tools/write-note' import { promptHandlers } from './prompts' export const notes = new MCPServer({ id: 'notes', name: 'Notes Server', version: '0.1.0', resources: resourceHandlers, prompts: promptHandlers, tools: { write: writeNoteTool, }, }) ``` ## 运行服务器 你已经创建了第一个 MCP 服务器!现在可以启动 Mastra 开发服务器并打开 [Studio](https://mastra.zisheng.pro/docs/studio/overview) 进行尝试: ```bash npm run dev ``` 在浏览器中打开 [`http://localhost:4111`](http://localhost:4111)。在左侧边栏中选择 **MCP Servers**,然后选择 **notes** MCP 服务器。 现在会显示如何将 MCP 服务器添加到 IDE 的说明。你可以将此 MCP 服务器与任何 MCP Client 配合使用。还可以在右侧的 **Available Tools** 下选择 **write** Tool。 在 **write** Tool 中进行尝试:名称输入 `test`,Markdown 内容输入 `this is a test`。选择 **Submit** 后,`notes` 中会出现新的 `test.md` 文件。