Astro MCP插件

一个可重用的Astro集成,通过模型上下文协议(MCP)暴露内容集合,便于在Astro项目中添加MCP服务器功能以实现AI助手集成。

  • by jem-computer
  • Astro
  • 本地部署
  • 4 星标
  • 更新于
在 GitHub 查看 jem-computer/astro-mcp

使用说明

Astro MCP插件

一个可重用的Astro集成,通过模型上下文协议(MCP)公开内容集合。轻松将MCP服务器功能添加到任何Astro项目中,以实现AI助手集成。

特性

  • 🚀 简易安装: npm install astro-mcp 并添加到Astro配置中
  • 🔧 MCP服务器工具:使用Astro内容构建MCP服务器的完整工具包
  • 📝 内容查询工具:按集合名称查询内容并按路径筛选
  • 🎯 即插即用:任何Astro项目与内容集合的直接集成
  • 📋 类型安全:通过Zod输入/输出模式提供全面的TypeScript支持
  • ⚡ 演出:内容缓存和高效搜索功能
  • 🛠️ 开发者体验:生物特征格式化、详细记录和错误处理
  • 📚 完整示例:展示实际使用情况的工作演示网站

安装

npm install astro-mcp
# or
bun add astro-mcp

快速开始

1.添加到Astro配置中

// astro.config.mjs
import { defineConfig } from 'astro/config';
import astroMCP from 'astro-mcp';

export default defineConfig({
  integrations: [
    astroMCP({
      collections: ['blog', 'docs'], // Your content collections
      includeContent: true
    })
  ]
});

2.构建你的项目

npm run build

这将自动将您的内容集合导出到 .astro-mcp/collections.json.

3.创建您的MCP服务器

// mcp-server.js
import { MCPServer } from '@mastra/mcp';
import { astroContentTool, ContentLoader } from 'astro-mcp/mcp';

const tools = { astro_content: astroContentTool };
const server = new MCPServer({ name: 'my-astro-mcp', version: '1.0.0', tools });

await server.startStdio();

配置

插件选项

// astro.config.mjs
import astroMCP from 'astro-mcp';

export default defineConfig({
  integrations: [
    astroMCP({
      collections: ['blog', 'docs'],    // Which collections to export
      exportPath: '.astro-mcp',         // Export directory (default)
      includeContent: true,             // Include full markdown content
      transform: (entry) => ({          // Optional: transform entries
        ...entry,
        wordCount: entry.body?.split(' ').length || 0
      })
    })
  ]
});

内容集合

在中定义您的收藏 src/content.config.ts:

import { glob } from 'astro/loaders';
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
  loader: glob({
    pattern: '**/*.md',
    base: './src/data/blog',
  }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.date(),
    author: z.string(),
    tags: z.array(z.string()),
  }),
});

export const collections = { blog };

MCP工具使用

服务器公开了一个 astro_content 具有以下界面的工具:

输入架构

{
  collection?: string,     // Filter by collection name
  paths?: string[],        // Filter by path patterns
  limit?: number,          // Maximum entries to return
  includeContent?: boolean // Include full markdown content
}

输出模式

{
  success: boolean,        // Whether the query was successful
  collection: string,      // The collection that was queried
  entries: Array<{
    id: string,           // Unique entry identifier
    slug: string,         // URL-friendly slug for the entry
    collection: string,   // Collection name this entry belongs to
    frontmatter: Record<string, any>, // Parsed frontmatter data
    content?: string,     // Full markdown content (if includeContent=true)
    excerpt?: string      // Content excerpt (first 200 characters)
  }>,
  total: number           // Total number of entries returned
}

示例用法

// Get all blog posts
{
  "collection": "blog"
}

// Get specific entries by path
{
  "collection": "blog",
  "paths": ["post-1", "getting-started"],
  "limit": 5
}

// Get all content without full markdown
{
  "includeContent": false
}

示例项目

请参阅 example/ 完整工作实现的目录:

# Clone the repository
git clone https://github.com/your-username/astro-mcp
cd astro-mcp

# Install dependencies
npm install

# Run the example
cd example
npm run build
npm run mcp:dev

发展

插件开发脚本

# Build the plugin
npm run build

# Test with example project
cd example && npm run dev

# Code formatting and linting
npx biome check --fix

# Publish to npm
npm publish

建筑

┌─────────────────┐     ┌──────────────────┐     ┌─────────────┐
│  Astro Build    │────▶│ Content Export   │────▶│ MCP Server  │
│  (collections)  │     │ (JSON file)      │     │ (tool API)  │
└─────────────────┘     └──────────────────┘     └─────────────┘
  1. 建造时间:Astro集成将集合导出为JSON
  2. 运行时:MCP服务器读取导出的数据并公开工具
  3. 查询时间:工具提供对内容的过滤访问

封装结构

astro-mcp/                       # Published npm package
├── src/                         # Plugin source code
│   ├── integrations/
│   │   └── astro-mcp.ts         # Main Astro integration
│   └── mcp/                     # MCP server tooling
│       ├── tools/
│       │   └── astro-content.ts # Content query tool
│       ├── utils/
│       │   └── content-loader.ts # JSON loading utilities
│       └── logger.ts            # Logging utilities
├── example/                     # Working example project
│   ├── src/
│   │   ├── content.config.ts    # Content collections config
│   │   ├── data/                # Example content
│   │   │   ├── blog/            # Blog posts
│   │   │   └── docs/            # Documentation
│   │   └── pages/               # Example site pages
│   ├── astro.config.mjs         # Uses astro-mcp plugin
│   ├── mcp-server.ts            # Example MCP server
│   └── package.json             # Example dependencies
├── dist/                        # Built plugin
├── package.json                 # Plugin package config
└── README.md                    # Plugin documentation

api参考

插件导出

// Main integration
import astroMCP from 'astro-mcp';

// MCP server components  
import { 
  astroContentTool, 
  ContentLoader, 
  createLogger 
} from 'astro-mcp/mcp';

配置接口

interface AstroMCPConfig {
  collections?: string[] | '*';        // Which collections to export
  exportPath?: string;                 // Export directory (default: '.astro-mcp')
  includeContent?: boolean;            // Include full content (default: true)
  transform?: (entry: any) => any;     // Transform function for entries
}

技术细节

内容导出过程

  1. Astro集成挂钩 astro:build:done
  2. 从配置的集合目录读取markdown文件
  3. 使用简化的YAML解析来解析frontmatter
  4. 将结构化数据与元数据一起导出为JSON

MCP服务器实现

  • 使用stdio传输与Mastra的MCPServer构建
  • 提供 astro_content 具有全面输入/输出模式的工具
  • 包括内容缓存以提高性能
  • 支持错误处理和结构化日志记录

类型安全

  • 整个代码库完全支持TypeScript
  • 用于输入/输出验证的Zod模式
  • 所有数据结构的全面类型定义

贡献

  1. 分叉存储库
  2. 创建要素分支
  3. 进行更改
  4. 跑 bunx biome check --fix 格式化代码
  5. 测试用 bun run build && bun run mcp:build
  6. 提交拉取请求

许可证

麻省理工学院