find_code_blocks
Extract and filter code blocks from markdown files by programming language to analyze documentation content.
Instructions
Find all fenced code blocks in a markdown file. Optionally filter by language (e.g. typescript, python).
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| file | Yes | Path to the markdown file | |
| language | No | Optional: filter by language (e.g. typescript, python) |
Implementation Reference
- src/markdown.ts:142-184 (handler)Main implementation of findCodeBlocks function - reads a markdown file, parses it for fenced code blocks, and optionally filters by language. Returns an array of CodeBlock objects containing language, code content, and line number.
export async function findCodeBlocks( filePath: string, language?: string, ): Promise<CodeBlock[]> { const absPath = path.resolve(filePath); const content = await fs.readFile(absPath, "utf-8"); const lines = content.split("\n"); const blocks: CodeBlock[] = []; const fenceRe = /^```(\w*)\s*$/; let inBlock = false; let blockLang = ""; let blockStart = 0; const blockLines: string[] = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (line === undefined) continue; const fence = line.match(fenceRe); if (fence) { if (!inBlock) { inBlock = true; blockLang = fence[1] ?? ""; blockStart = i + 1; blockLines.length = 0; } else { inBlock = false; if ( language === undefined || blockLang.toLowerCase() === language.toLowerCase() ) { blocks.push({ language: blockLang, code: blockLines.join("\n"), line: blockStart, }); } } } else if (inBlock) { blockLines.push(line); } } return blocks; } - src/index.ts:86-107 (registration)Tool registration for 'find_code_blocks' using server.tool - defines the tool name, description, input schema (file and optional language parameters), and the handler that calls findCodeBlocks and formats the output.
server.tool( "find_code_blocks", "Find all fenced code blocks in a markdown file. Optionally filter by language (e.g. typescript, python).", { file: z.string().describe("Path to the markdown file"), language: z .string() .optional() .describe("Optional: filter by language (e.g. typescript, python)"), }, async ({ file, language }) => { const absPath = path.resolve(file); const blocks = await findCodeBlocks(absPath, language); const parts = blocks.map((b) => { const lang = b.language || "(no lang)"; return `--- ${lang} (L${b.line}) ---\n${b.code}`; }); const text = parts.length > 0 ? parts.join("\n\n") : "(no code blocks found)"; return { content: [{ type: "text" as const, text }] }; }, ); - src/markdown.ts:16-20 (schema)CodeBlock interface defining the return type structure with language (string), code (string), and line (number) properties.
export interface CodeBlock { language: string; code: string; line: number; }