### Development Setup for mcp-server-markdown Source: https://github.com/ofershap/mcp-server-markdown/blob/main/README.md Clone the repository, install dependencies, run tests, and build the project. ```bash git clone https://github.com/ofershap/mcp-server-markdown.git cd mcp-server-markdown npm install npm test npm run build ``` -------------------------------- ### MCP Server Instantiation Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Provides an example of how to instantiate the MCP server. This is the starting point for running the server. ```typescript // Server instantiation code import { MCP } from "@mcp-server/server"; const server = new MCP({ // configuration options }); server.start(); ``` -------------------------------- ### Install and Run mcp-server-markdown Source: https://github.com/ofershap/mcp-server-markdown/blob/main/README.md Install and run the mcp-server-markdown tool from the command line. ```bash npx mcp-server-markdown ``` -------------------------------- ### Response Content Format Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md Shows the key-value pair format for response content, including an example with frontmatter. ```text title: API Documentation author: Jane Doe date: 2025-06-15 tags: api,reference version: 1.0.0 ``` ```text (no frontmatter) ``` -------------------------------- ### Get Section Response Example (Section Found) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This is an example of a successful response when the specified heading is found in the markdown file. The content includes the heading and all subsequent subsections. ```markdown ## Installation Run the installation script: ```bash npm install mylib ``` ### Prerequisites You need Node.js 18 or later. ### Post-Installation Run setup wizard with: ```bash npx mylib setup ``` ``` -------------------------------- ### List Files Response Example (Files Found) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This is an example of a successful response when markdown files are found in the specified directory. File paths are newline-separated and alphabetically sorted. ```json { "content": [ { "type": "text", "text": "api.md\ncore/architecture.md\ncore/design.md\nREADME.md" } ] } ``` -------------------------------- ### Example Usage for list_files Tool Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Demonstrates the input and expected output for the 'list_files' tool when searching the './docs' directory. ```text Input: { "directory": "./docs" } Output: api.md guides/getting-started.md guides/advanced-usage.md README.md ``` -------------------------------- ### Example File Structure with Frontmatter Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md Illustrates the required structure for a file using frontmatter, with delimiters and content. ```markdown --- title: My Document author: John Doe --- # Heading Content... ``` -------------------------------- ### List Headings in Markdown File (Example 2) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This example demonstrates listing headings from a different markdown file, `./README.md`. It shows the expected JSON request and response format. ```json { "file": "./README.md" } ``` ```json { "content": [ { "type": "text", "text": "- mcp-server-markdown (L1)\n - Why (L10)\n - Tools (L15)\n - Quick Start (L25)\n - Cursor (L26)\n - Claude Desktop (L35)\n - Examples (L45)" } ] } ``` -------------------------------- ### Example Usage for search_docs Tool Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Demonstrates the input and expected output for the 'search_docs' tool when searching for 'authentication' in the './docs' directory. ```text Input: { "directory": "./docs", "query": "authentication" } Output: api.md:15 All endpoints require authentication via Bearer token. setup.md:42 Configure authentication in the .env file. ``` -------------------------------- ### List Headings Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Demonstrates how to use the 'list_headings' tool to get a table of contents from a markdown file. The output is indented based on heading level. ```json Input: { "file": "./docs/README.md" } Output: - Overview (L1) - Getting Started (L5) - Installation (L8) - Configuration (L15) - API Reference (L20) - Endpoints (L22) ``` -------------------------------- ### Get Frontmatter Example Usage Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Illustrates how to use the 'get_frontmatter' tool to extract metadata from a markdown file. The output displays frontmatter as key-value pairs. ```json Input: { "file": "./docs/post.md" } Output: title: Getting Started with the API author: Jane Doe date: 2025-06-15 tags: tutorial,api ``` -------------------------------- ### Install MCP Server Markdown CLI Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/INDEX.md Instructions for installing the mcp-server-markdown package globally as a CLI tool. This allows you to run it directly from your terminal. ```bash # As CLI tool npm install -g mcp-server-markdown npx mcp-server-markdown ``` -------------------------------- ### Install MCP Server Markdown Library Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/INDEX.md Instructions for installing the mcp-server-markdown package as a dependency for your project. This is for using it as a library within your Node.js application. ```bash # As library npm install mcp-server-markdown ``` -------------------------------- ### Example Usage for get_section Tool Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Demonstrates the input and expected output for the 'get_section' tool when retrieving the 'Authentication' section from './docs/api.md'. ```text Input: { "file": "./docs/api.md", "heading": "Authentication" } Output: ## Authentication All API requests must include a Bearer token in the Authorization header. ### Token Format Tokens are JWT-formatted strings issued by the auth server. ### Token Refresh Tokens expire after 24 hours... ``` -------------------------------- ### Library Usage Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Demonstrates importing and using searchDocs and getSection functions from the mcp-server-markdown library. ```typescript import { searchDocs, getSection } from 'mcp-server-markdown'; const results = await searchDocs('./docs', 'API'); ``` -------------------------------- ### Get Section Response Example (Heading Not Found) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This response indicates that the specified heading was not found in the markdown file. The content will be a status message. ```text (heading "Installation" not found) ``` -------------------------------- ### Search Documents Response Example (Matches Found) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This is an example of a successful search response when matches are found. Results are formatted as 'file:line_number content_of_matching_line' and are limited to 50. ```json { "content": [ { "type": "text", "text": "setup.md:12 Basic configuration requires setting environment variables.\napi.md:45 Advanced configuration options are documented in RFC-3.\nadmin.md:8 System configuration is managed via the config.yaml file." } ] } ``` -------------------------------- ### Find Code Blocks Example Usage Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Shows an example of using the 'find_code_blocks' tool with a specific file and language filter. The output lists code blocks with their language and line number. ```json Input: { "file": "./docs/guide.md", "language": "typescript" } Output: --- typescript (L10) --- const greet = (name: string) => { console.log(`Hello, ${name}!`); }; --- typescript (L25) --- interface User { id: string; name: string; } ``` -------------------------------- ### List Files Response Example (No Files Found) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This response indicates that no markdown files were found in the specified directory. The content will be a status message. ```json { "content": [ { "type": "text", "text": "(no markdown files found)" } ] } ``` -------------------------------- ### MCP Server Interaction Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Illustrates the communication flow between an MCP Client, the mcp-server-markdown process, and its tools via stdio. ```text MCP Client → Stdio → mcp-server-markdown → Tools ``` -------------------------------- ### Server Metadata Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Specifies the hardcoded name and version for the mcp-server-markdown package. ```typescript name: "mcp-server-markdown" version: "1.0.0" ``` -------------------------------- ### Get Specific Section Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Retrieves the content of a specific section (heading) from a markdown file. Requires the file path and the exact heading name. ```typescript import { getSection } from "@mcp-server/markdown"; async function example() { const filePath = "/path/to/your/docs/file.md"; const heading = "Introduction"; const sectionContent = await getSection(filePath, heading); console.log(sectionContent); } ``` -------------------------------- ### List Files using MCP Tool Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/INDEX.md This example shows the JSON request format for the `list_files` MCP tool. It specifies the directory to list files from. ```json { "tool": "list_files", "arguments": { "directory": "./docs" } } Response: (list of markdown files) ``` -------------------------------- ### Get Section Request Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md Use this snippet to extract a specific markdown section from a file by its heading. The heading matching is case-insensitive. ```json { "file": "./README.md", "heading": "Installation" } ``` -------------------------------- ### Example Request for File Processing Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md A JSON request object specifying a file path for processing. ```json { "file": "./docs/post.md" } ``` -------------------------------- ### Example Response with Text Content Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md A JSON response object containing text content, which includes frontmatter details. ```json { "content": [ { "type": "text", "text": "title: Getting Started Guide\nauthor: Alice Smith\npublished: 2025-06-15\ncategory: tutorials" } ] } ``` -------------------------------- ### Search Documentation Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Shows how to search for specific queries within markdown files in a given directory. The search results include file path, heading, and content snippets. ```typescript import { searchDocs } from "@mcp-server/markdown"; async function example() { const directory = "/path/to/your/docs"; const query = "documentation patterns"; const results = await searchDocs(directory, query); console.log(results); } ``` -------------------------------- ### Search Documents using MCP Tool Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/INDEX.md This example demonstrates the JSON request for the `search_docs` MCP tool. It includes the directory to search and the query string. ```json { "tool": "search_docs", "arguments": { "directory": "./docs", "query": "authentication" } } Response: (search results with file:line format) ``` -------------------------------- ### List Headings Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Lists all headings within a specified markdown file. This is useful for understanding the structure of a document. ```typescript import { listHeadings } from "@mcp-server/markdown"; async function example() { const filePath = "/path/to/your/docs/file.md"; const headings = await listHeadings(filePath); console.log(headings); } ``` -------------------------------- ### MCP Server Main Function Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Illustrates the main function for starting the MCP server. This serves as the entry point for the server application. ```typescript async function main() { // ... server setup and configuration ... console.log("MCP Server started."); // ... connection details ... } main().catch(err => { console.error("Server failed to start:", err); }); ``` -------------------------------- ### Absolute Path Resolution Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Normalizes input paths to absolute paths using path.resolve for consistent behavior. ```typescript const absDir = path.resolve(directory); const absPath = path.resolve(filePath); ``` -------------------------------- ### List Markdown Files Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Demonstrates how to list all markdown files within a specified directory using the listMarkdownFiles function. Ensure the directory path is correctly provided. ```typescript import { listMarkdownFiles } from "@mcp-server/markdown"; async function example() { const directory = "/path/to/your/docs"; const files = await listMarkdownFiles(directory); console.log(files); } ``` -------------------------------- ### MCP Client Response: No Search Matches Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md Example of an MCP response when the search_docs command is executed and no matching documentation is found. ```typescript { content: [{ type: "text", text: "(no matches)" }] } ``` -------------------------------- ### List Files Request Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md Use this snippet to list all markdown files in a specified directory recursively. The directory path can be absolute or relative. ```json { "directory": "./docs" } ``` -------------------------------- ### MCP Client Response: No Markdown Files Found Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md Example of an MCP response when the list_files command is executed and no markdown files are present. ```typescript { content: [{ type: "text", text: "(no markdown files found)" }] } ``` -------------------------------- ### Line-Based Processing Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Splits file content by newlines and iterates through each line for processing. Line numbers are 1-indexed. ```typescript const lines = content.split("\n"); for (let i = 0; i < lines.length; i++) { // Process lines[i] with 1-indexed line numbers } ``` -------------------------------- ### Example Usage of listHeadings Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/types.md Demonstrates how to use the `listHeadings` function to extract all headings from a markdown file. The results are returned as an array of `Heading` objects. ```typescript const headings = await listHeadings('./docs/README.md'); // [ // { level: 1, text: 'Overview', line: 1 }, // { level: 2, text: 'Getting Started', line: 5 }, // { level: 3, text: 'Installation', line: 8 }, // { level: 2, text: 'Configuration', line: 15 } // ] ``` -------------------------------- ### MCP Client Response: No Frontmatter Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md Example of an MCP response when the get_frontmatter command is executed but the target file has no frontmatter. ```typescript { content: [{ type: "text", text: "(no frontmatter)" }] } ``` -------------------------------- ### Search Documents Response Example (No Matches) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This response indicates that no matches were found for the given search query in the specified directory. The content will be a status message. ```json { "content": [ { "type": "text", "text": "(no matches)" } ] } ``` -------------------------------- ### MCP Client Response: No Headings Found Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md Example of an MCP response when the list_headings command is executed and the target file contains no headings. ```typescript { content: [{ type: "text", text: "(no headings found)" }] } ``` -------------------------------- ### Example Usage of searchDocs Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/types.md Demonstrates how to use the `searchDocs` function to find occurrences of a query within a specified directory. The results are returned as an array of `SearchResult` objects. ```typescript const results = await searchDocs('./docs', 'API'); // [ // { // file: 'api.md', // line: 5, // content: 'This document describes the public API.' // }, // { // file: 'architecture.md', // line: 42, // content: 'The API layer handles all HTTP requests.' // } // ] ``` -------------------------------- ### MCP Client Response: Heading Not Found Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md Example of an MCP response when the get_section command is executed but the specified heading does not exist. ```typescript { content: [{ type: "text", text: "(heading \"...\" not found)" }] } ``` -------------------------------- ### Search Documents Request Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md Use this snippet to perform a full-text search across all markdown files within a given directory. The search is case-insensitive. ```json { "directory": "./docs", "query": "configuration" } ``` -------------------------------- ### Example Usage of findCodeBlocks Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/types.md Demonstrates how to use the `findCodeBlocks` function to find all fenced code blocks within a markdown file. Optionally, you can filter by a specific language. ```typescript const blocks = await findCodeBlocks('./docs/guide.md'); // [ // { // language: 'typescript', // code: 'const x: number = 42; // console.log(x);', // line: 10 // }, // { // language: 'bash', // code: 'npm install @mylib/core', // line: 20 // }, // { // language: '', // code: 'Plain text without language marker', // line: 30 // } // ] ``` -------------------------------- ### MCP Client Response: No Code Blocks Found Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md Example of an MCP response when the find_code_blocks command is executed and no matching code blocks are found. ```typescript { content: [{ type: "text", text: "(no code blocks found)" }] } ``` -------------------------------- ### Find Code Blocks Example Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Extracts all code blocks from a markdown file, optionally filtering by a specific programming language. Returns an array of code block objects. ```typescript import { findCodeBlocks } from "@mcp-server/markdown"; async function example() { const filePath = "/path/to/your/docs/file.md"; // To find all code blocks: const allCodeBlocks = await findCodeBlocks(filePath); console.log("All code blocks:", allCodeBlocks); // To find only JavaScript code blocks: const jsCodeBlocks = await findCodeBlocks(filePath, "javascript"); console.log("JavaScript code blocks:", jsCodeBlocks); } ``` -------------------------------- ### Example Usage of getFrontmatter Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/types.md Demonstrates how to use the `getFrontmatter` function to parse YAML frontmatter from a markdown file. It returns a `Frontmatter` object or `null` if no frontmatter is found. ```typescript const fm = await getFrontmatter('./docs/post.md'); // File content: // --- // title: My Article // author: John Doe // date: 2025-06-15 // tags: tutorial,api // --- // Result: // { // title: 'My Article', // author: 'John Doe', // date: '2025-06-15', // tags: 'tutorial,api' // } ``` -------------------------------- ### List Markdown Files in Directory Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/markdown-module.md Recursively discovers all markdown files in a specified directory and returns their relative paths, sorted alphabetically. Use this to get a list of all markdown documents within a project structure. ```typescript import { listMarkdownFiles } from './markdown.js'; const files = await listMarkdownFiles('./docs'); // Result: ['README.md', 'api.md', 'setup.md'] ``` -------------------------------- ### Catch ENOENT Error for File Not Found Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md This example shows how to catch the 'ENOENT' error, which indicates that a file or directory was not found. This can occur if the path provided to functions like listHeadings does not exist. ```typescript import { listHeadings } from './markdown.js'; try { const headings = await listHeadings('/nonexistent/file.md'); } catch (error) { if (error instanceof Error) { if ('code' in error && error.code === 'ENOENT') { console.log('File not found'); } } } ``` -------------------------------- ### Find All and Filtered Code Blocks in Markdown Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/markdown-module.md Demonstrates how to use the findCodeBlocks function to retrieve all code blocks from a markdown file or to filter them by a specific language. Shows example usage and expected results for both scenarios. ```typescript import { findCodeBlocks } from './markdown.js'; // Get all code blocks const allBlocks = await findCodeBlocks('./docs/guide.md'); // Result: // [ // { language: 'typescript', code: 'const x = 1; console.log(x);', line: 10 }, // { language: 'bash', code: 'npm install @mylib/core', line: 20 } // ] // Get only TypeScript blocks const tsBlocks = await findCodeBlocks('./docs/guide.md', 'typescript'); // Result: [{ language: 'typescript', code: '...', line: 10 }] ``` -------------------------------- ### Server Startup Implementation Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Shows the main function responsible for initializing the MCP server and connecting to the transport layer. Includes error handling for startup failures. ```typescript async function main() { const transport = new StdioServerTransport(); await server.connect(transport); } main().catch((error) => { console.error("Fatal error:", error); process.exit(1); }); ``` -------------------------------- ### MCP Server Entry Point Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md The binary entry point for the MCP server. Invoked via npx or node, it sets up the server, registers tools, and connects to the stdio transport to listen for client requests. ```bash npx mcp-server-markdown ``` ```bash node dist/index.js ``` -------------------------------- ### Build Commands Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Common npm scripts for building, type checking, and testing the project. ```bash npm run build # Runs tsup, outputs to dist/ npm run typecheck # TypeScript strict mode check npm run test # Run tests ``` -------------------------------- ### Initialize McpServer Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Initializes the McpServer with a name and version. The server runs on stdio transport and connects automatically. ```typescript const server = new McpServer({ name: "mcp-server-markdown", version: "1.0.0", }); ``` -------------------------------- ### Using Markdown Utility Functions Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/errors.md Demonstrates how to use listHeadings, getSection, and searchDocs from the markdown utility. Includes error handling for file system operations and checking for optional results. ```typescript import { listHeadings, searchDocs, getSection } from './markdown.js'; // Check for existence first try { const headings = await listHeadings('./docs/README.md'); console.log(`Found ${headings.length} headings`); } catch (error) { // Handle ENOENT, EACCES, or other fs errors if (error instanceof Error) { if ('code' in error && (error.code === 'ENOENT' || error.code === 'EACCES')) { console.error(`File access error: ${error.message}`); } else { console.error(`Unexpected error: ${error.message}`); } } } // Optional results are checked after successful execution const section = await getSection('./docs/api.md', 'API Endpoints'); if (section) { console.log(section); } else { console.log('Section not found'); } // Search results are empty arrays when no match const results = await searchDocs('./docs', 'authentication'); if (results.length === 0) { console.log('No results found'); } else { results.forEach(r => console.log(`${r.file}:${r.line}`)); } ``` -------------------------------- ### Get Frontmatter Function Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Parses and returns the YAML frontmatter metadata from a markdown file. Returns null if no frontmatter is present. ```typescript getFrontmatter(file): Promise ``` -------------------------------- ### MCP Server File Organization Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/MANIFEST.md Illustrates the directory structure of the MCP Server project, showing the location of key documentation files. ```tree /workspace/home/output/ ├── README.md Entry point, welcome guide ├── INDEX.md Navigation hub, quick reference ├── OVERVIEW.md Architecture and design ├── USAGE-PATTERNS.md Code examples and patterns ├── types.md Type definitions ├── errors.md Error handling ├── endpoints.md MCP tool specifications ├── MANIFEST.md This file └── api-reference/ ├── markdown-module.md Core function API └── mcp-server.md MCP server implementation ``` -------------------------------- ### Search Documentation with mcp-server-markdown Library Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/INDEX.md Use the `searchDocs` function to find documentation. It requires the directory to search and the query string. Results include file, line, and content. ```typescript import { searchDocs } from 'mcp-server-markdown'; const results = await searchDocs('./docs', 'API'); results.forEach(r => { console.log(`${r.file}:${r.line} ${r.content}`); }); ``` -------------------------------- ### Get Section Function Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Extracts a specific markdown section by its heading from a given file. Returns an empty string if the heading is not found. ```typescript getSection(file, heading): Promise ``` -------------------------------- ### CodeBlock Type Definition Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/types.md Defines the structure for a fenced code block, including the programming language, the code content, and the starting line number. ```typescript interface CodeBlock { language: string; code: string; line: number; } ``` -------------------------------- ### Build LLM Context from Search Results Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Builds context for LLM systems by searching markdown files for a given topic. It identifies relevant files and extracts content from sections associated with search results. ```typescript async function buildLLMContext(docsDir, topic) { const results = await searchDocs(docsDir, topic); const context = { topic, relevantFiles: new Set(), sections: [] }; for (const result of results) { context.relevantFiles.add(result.file); // Get the section containing this match const headings = await listHeadings(`${docsDir}/${result.file}`); const relevantHeading = headings .filter(h => h.line < result.line) .sort((a, b) => b.line - a.line)[0]; if (relevantHeading) { const section = await getSection( `${docsDir}/${result.file}`, relevantHeading.text ); context.sections.push({ file: result.file, heading: relevantHeading.text, content: section }); } } return context; } ``` -------------------------------- ### Build In-Memory Documentation Index Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Construct an in-memory index of documentation files, headings, and metadata for efficient searching. This pattern aggregates information from multiple files into a single structure. ```typescript import { listMarkdownFiles, listHeadings, getFrontmatter } from './markdown.js'; async function buildIndex(docDir) { const index = { files: [], headings: [], metadata: {} }; const files = await listMarkdownFiles(docDir); for (const file of files) { const filePath = `${docDir}/${file}`; // Add file entry index.files.push(file); // Add headings const headings = await listHeadings(filePath); for (const heading of headings) { index.headings.push({ file, ...heading }); } // Add metadata const fm = await getFrontmatter(filePath); if (fm) { index.metadata[file] = fm; } } return index; } const index = await buildIndex('./docs'); console.log(`Indexed ${index.files.length} files`); console.log(`Found ${index.headings.length} headings`); console.log(`Parsed ${Object.keys(index.metadata).length} files with metadata`); ``` -------------------------------- ### Get Frontmatter Tool Definition Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Defines the 'get_frontmatter' tool, which parses YAML frontmatter from the beginning of a markdown file. It returns key-value metadata. ```typescript server.tool( "get_frontmatter", "Parse YAML frontmatter (between --- delimiters) at the start of a markdown file. Returns key-value metadata.", { file: z.string().describe("Path to the markdown file"), }, async ({ file }) => { ... } ) ``` -------------------------------- ### Project Directory Structure Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/README.md This snippet shows the directory structure of the mcp-server-markdown project, illustrating the organization of its documentation files. ```tree output/ ├── README.md (this file) ├── INDEX.md (navigation hub) ├── OVERVIEW.md (architecture) ├── USAGE-PATTERNS.md (code examples) ├── types.md (type definitions) ├── errors.md (error reference) ├── endpoints.md (MCP tool specs) └── api-reference/ ├── markdown-module.md (core functions) └── mcp-server.md (MCP tools) ``` -------------------------------- ### Import Core Markdown Functions Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/INDEX.md Import the core functions from the markdown module for use in your Node.js project. Ensure the path is correct for your project setup. ```typescript import { listMarkdownFiles, searchDocs, getSection, listHeadings, findCodeBlocks, getFrontmatter, } from './markdown.js'; ``` -------------------------------- ### CodeBlock Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/types.md Represents a single fenced code block found in a markdown file. It includes the language identifier, code content, and the starting line number. ```APIDOC ## Type: CodeBlock ### Description Represents a single fenced code block found in a markdown file. ### Fields - **language** (string) - Language identifier from the opening fence (e.g., `"typescript"`, `"python"`). Empty string if no language specified. - **code** (string) - The code content without the fence delimiters (triple backticks) - **line** (number) - 1-indexed line number where the code block begins (the opening fence line) ### Example ```typescript const blocks = await findCodeBlocks('./docs/guide.md'); // [ // { // language: 'typescript', // code: 'const x: number = 42;\nconsole.log(x);', // line: 10 // }, // { // language: 'bash', // code: 'npm install @mylib/core', // line: 20 // }, // { // language: '', // code: 'Plain text without language marker', // line: 30 // } // ] ``` ``` -------------------------------- ### Configure mcp-server-markdown for Cursor Source: https://github.com/ofershap/mcp-server-markdown/blob/main/README.md Add the mcp-server-markdown server configuration to your Cursor IDE's mcp.json file. ```json { "mcpServers": { "markdown": { "command": "npx", "args": ["-y", "mcp-server-markdown"] } } } ``` -------------------------------- ### Library Entry Point Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md The library entry point for core markdown parsing functions. These can be imported and used independently of the MCP server, requiring only Node.js built-ins. ```typescript src/markdown.ts ``` -------------------------------- ### Generate Documentation Summaries Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Creates a structured summary of markdown documents, including file names, titles from frontmatter, and a list of level 2 headings. Requires utility functions for listing markdown files, headings, and frontmatter. ```typescript import { listMarkdownFiles, listHeadings, getFrontmatter } from './markdown.js'; async function summarizeDocs(docDir) { const files = await listMarkdownFiles(docDir); const summary = []; for (const file of files) { const filePath = `${docDir}/${file}`; const fm = await getFrontmatter(filePath); const headings = await listHeadings(filePath); const entry = { file, title: fm?.title || file, sections: headings.filter(h => h.level === 2).map(h => h.text) }; summary.push(entry); } return summary; } const summary = await summarizeDocs('./docs'); console.log(JSON.stringify(summary, null, 2)); ``` -------------------------------- ### MCP Tool: list_files Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/OVERVIEW.md Discovers all markdown files in a specified directory. The output is a newline-separated list of file paths. ```plaintext list_files Input Parameters: directory: string Output Format: Text: newline-separated paths ``` -------------------------------- ### Search Documentation with Context Highlighting Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Searches markdown files for a given query and returns results with context, including the file, line number, and a snippet of the content with the match highlighted. Requires a `searchDocs` utility function. ```typescript import { searchDocs } from './markdown.js'; async function searchWithContext(docDir, query, contextLines = 1) { const results = await searchDocs(docDir, query); return results.map(result => ({ ...result, query, // Highlight: show where in the line the match occurred matchStart: result.content.toLowerCase().indexOf(query.toLowerCase()), snippet: result.content.substring( Math.max(0, result.content.toLowerCase().indexOf(query.toLowerCase()) - 20), result.content.toLowerCase().indexOf(query.toLowerCase()) + query.length + 20 ) })); } const results = await searchWithContext('./docs', 'API endpoints', 1); for (const r of results) { console.log(`${r.file}:${r.line}`); console.log(` ...${r.snippet}...`); } ``` -------------------------------- ### listMarkdownFiles(directory: string): Promise Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/markdown-module.md Recursively discovers all markdown files in a specified directory and returns their relative paths, sorted alphabetically. It returns an empty array if no markdown files are found. ```APIDOC ## `listMarkdownFiles` ### Description Recursively discovers all markdown files in a directory and returns their relative paths sorted alphabetically. ### Signature ```typescript async function listMarkdownFiles(directory: string): Promise ``` ### Parameters #### Path Parameters - **directory** (string) - Required - Absolute or relative path to the directory to scan ### Return Type `Promise` - Array of relative file paths (e.g., `["README.md", "docs/guide.md"]`), always sorted alphabetically. Returns empty array if no markdown files exist. ### Throws - `Error` - Throws "Not a directory" error if the path is not a valid directory ### Example ```typescript import { listMarkdownFiles } from './markdown.js'; const files = await listMarkdownFiles('./docs'); // Result: ['README.md', 'api.md', 'setup.md'] ``` ``` -------------------------------- ### Extract Code Blocks by Language Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Find and extract all code blocks of a specific language (e.g., 'typescript') from markdown files. This helps in collecting examples or specific code snippets. ```typescript import { listMarkdownFiles, findCodeBlocks } from './markdown.js'; const files = await listMarkdownFiles('./docs'); for (const file of files) { const blocks = await findCodeBlocks(`./docs/${file}`, 'typescript'); for (const block of blocks) { console.log(`Found at ${file}:${block.line}`); console.log(block.code); console.log('---'); } } ``` -------------------------------- ### Find Code Blocks in Markdown File (With Filter) Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md This example demonstrates using the `find_code_blocks` tool with a language filter to retrieve only TypeScript code blocks from a markdown file. The filter is case-insensitive. ```json { "file": "./docs/guide.md", "language": "typescript" } ``` ```json { "content": [ { "type": "text", "text": "--- typescript (L10) ---\nconst x = 42;\nconsole.log(x);" } ] } ``` -------------------------------- ### Generate Sitemap from Markdown Files Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Integrates with documentation generation workflows by creating a sitemap. It extracts frontmatter and headings from markdown files to define page paths, titles, and sections. ```typescript import { listMarkdownFiles, getFrontmatter, listHeadings } from './markdown.js'; async function generateSiteMap(docsDir) { const files = await listMarkdownFiles(docsDir); const sitemap = { pages: [] }; for (const file of files) { const fm = await getFrontmatter(`${docsDir}/${file}`); const headings = await listHeadings(`${docsDir}/${file}`); sitemap.pages.push({ path: `/${file.replace(/\.md$/, '/')}`, title: fm?.title || file, sections: headings.filter(h => h.level <= 2) }); } return sitemap; } ``` -------------------------------- ### Server Invocation Commands Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/api-reference/mcp-server.md Provides commands for invoking the compiled MCP server, both directly using Node.js and via npm. ```bash node dist/index.js ``` ```bash npx mcp-server-markdown ``` -------------------------------- ### Get YAML Frontmatter from Markdown File Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md The `get_frontmatter` tool parses and returns the YAML frontmatter from the beginning of a markdown file. This is useful for accessing metadata defined in the file's header. ```typescript { file: string } ``` -------------------------------- ### List Headings in Markdown File Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/endpoints.md Use the `list_headings` tool to get a structured list of all headings within a specified markdown file. This is useful for generating tables of contents or navigating document structure. ```json { "file": "./docs/guide.md", "heading": "API Reference" } ``` ```json { "content": [ { "type": "text", "text": "## API Reference\n\nAll endpoints accept JSON requests and return JSON responses.\n\n### GET /api/users\n\nList all users..." } ] } ``` -------------------------------- ### List Markdown Files and Table of Contents Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Discover all markdown files in a directory and display their heading structure. This is useful for understanding the organization of your documentation. ```typescript import { listMarkdownFiles, listHeadings } from './markdown.js'; const files = await listMarkdownFiles('./docs'); for (const file of files) { const headings = await listHeadings(`./docs/${file}`); if (headings.length > 0) { console.log(` ${file}`); for (const heading of headings) { const indent = ' '.repeat(heading.level - 1); console.log(`${indent}- ${heading.text}`); } } } ``` -------------------------------- ### Watch for Markdown File Changes Source: https://github.com/ofershap/mcp-server-markdown/blob/main/_autodocs/USAGE-PATTERNS.md Monitors a directory for changes in markdown files and triggers a sync process when a file is modified. Requires the 'fs' module and utility functions for listing files and getting frontmatter. ```typescript import fs from 'fs'; import { listMarkdownFiles, getFrontmatter } from './markdown.js'; async function syncDocumentation(docsDir) { const watcher = fs.watch(docsDir, { recursive: true }, async (eventType, filename) => { if (filename?.endsWith('.md')) { console.log(`File changed: ${filename}`); const fm = await getFrontmatter(`${docsDir}/${filename}`); if (fm?.id) { // Sync to external system using id from frontmatter console.log(`Syncing document ${fm.id} to external system`); } } }); return watcher; } ``` -------------------------------- ### Configure mcp-server-markdown for VS Code Source: https://github.com/ofershap/mcp-server-markdown/blob/main/README.md Add the mcp-server-markdown server configuration to your VS Code settings or .vscode/mcp.json file. ```json { "mcp": { "servers": { "markdown": { "command": "npx", "args": ["-y", "mcp-server-markdown"] } } } } ```