search_posts
Search Hexo blog posts by keyword to find specific articles in titles and content using this MCP server tool.
Instructions
按关键词搜索文章标题和正文内容
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | 搜索关键词 |
Implementation Reference
- src/utils/post-manager.ts:81-107 (handler)The core logic for searching posts, which iterates through markdown files and checks if the title or content contains the query string.
export async function searchPosts(query: string): Promise<PostMeta[]> { const files = await fs.readdir(POSTS_DIR); const mdFiles = files.filter((f) => f.endsWith(".md")); const q = query.toLowerCase(); const results: PostMeta[] = []; for (const file of mdFiles) { const fullPath = path.join(POSTS_DIR, file); const raw = await fs.readFile(fullPath, "utf-8"); const { data, content } = matter(raw); if ( (data.title && String(data.title).toLowerCase().includes(q)) || content.toLowerCase().includes(q) ) { results.push({ title: data.title || file.replace(/\.md$/, ""), date: data.date ? String(data.date) : "未知", tags: Array.isArray(data.tags) ? data.tags : data.tags ? [data.tags] : [], filename: file, wordCount: content.length, }); } } return results; } - src/tools/post-tools.ts:45-67 (registration)Tool registration for "search_posts" which uses the Zod schema for input validation and calls the handler from `post-manager.ts`.
server.tool( "search_posts", "按关键词搜索文章标题和正文内容", { query: z.string().describe("搜索关键词") }, async ({ query }) => { try { const results = await searchPosts(query); if (results.length === 0) { return { content: [{ type: "text" as const, text: `未找到包含 "${query}" 的文章。` }] }; } const summary = results .map((p, i) => `${i + 1}. 【${p.title}】 (${p.date}) - ${p.filename}`) .join("\n"); return { content: [ { type: "text" as const, text: `找到 ${results.length} 篇相关文章:\n\n${summary}` }, ], }; } catch (e: any) { return { content: [{ type: "text" as const, text: `错误: ${e.message}` }], isError: true }; } } );