### Quick Start Installation and Run Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/10-quick-reference.md Install the server globally, set necessary environment variables for BookStack API access, and run the server. The server defaults to port 3000. ```bash # 1. Install npm install -g bookstack-mcp-server # 2. Set environment variables export BOOKSTACK_BASE_URL=https://bookstack.example.com/api export BOOKSTACK_API_TOKEN=token_id:token_secret # 3. Run bookstack-mcp-server # Server starts on port 3000 ``` -------------------------------- ### Development Setup for BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/README.md Clone the repository, install dependencies, and start the development server. This is the initial setup for contributing to or modifying the server. ```bash git clone cd bookstack-mcp-server npm install npm run dev ``` -------------------------------- ### Initialize BookStackMCPServer Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/03-server.md Provides examples for initializing the BookStackMCPServer, demonstrating both default setup and initialization with custom configuration overrides for the BookStack API. ```typescript // Basic initialization with defaults const server = new BookStackMCPServer(); // With configuration overrides const server = new BookStackMCPServer({ bookstack: { baseUrl: 'https://custom-bookstack.com/api', apiToken: 'custom_token:secret' } }); ``` -------------------------------- ### Configure and Start Development Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/setup-guide.md Copy the environment template, edit the .env file for custom configurations, and start the development server with npm. ```bash # Copy environment template cp .env.example .env # Edit configuration nano .env # Start development server npm run dev ``` -------------------------------- ### Install and Configure BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md Installs the BookStack MCP Server globally and sets up necessary environment variables for connecting to your BookStack instance. Use this to begin your setup. ```bash # Install and configure npm install -g bookstack-mcp-server # Set up environment export BOOKSTACK_BASE_URL="https://your-bookstack.example.com/api" export BOOKSTACK_API_TOKEN="your-api-token-here" # Test connection bookstack-mcp-server --test-connection ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/setup-guide.md Steps to clone the BookStack MCP Server repository, navigate into the directory, and install project dependencies using npm. ```bash # Clone repository git clone https://github.com/pnocera/bookstack-mcp-server.git cd bookstack-mcp-server # Install dependencies npm install ``` -------------------------------- ### Install BookStack MCP Server Globally Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/README.md Install the server globally using npm. This command makes the server executable available system-wide. ```bash # Install globally npm install -g bookstack-mcp-server ``` -------------------------------- ### Debug Logging Output Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Example of the output format when debug logging is enabled with LOG_FORMAT=pretty. ```text 2024-01-15 14:30:45 [debug] API request { "method": "GET", "url": "/books", "params": { "count": 10 } } 2024-01-15 14:30:46 [debug] API response { "status": 200, "url": "/books", "dataLength": 2345 } ``` -------------------------------- ### JSON Log Output Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Example of log output when LOG_FORMAT is set to 'json'. ```json { "timestamp": "2024-01-15T14:30:45.000Z", "level": "info", "message": "API request", "method": "GET", "url": "/books" } ``` -------------------------------- ### Tool Registration Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/07-tools-resources.md Tools are registered during server initialization by instantiating tool classes and adding their tools to a map. ```typescript private setupTools(): void { const toolClasses = [ new BookTools(this.client, this.validator, this.logger), new PageTools(this.client, this.validator, this.logger), // ... other tool classes ]; toolClasses.forEach((toolClass) => { toolClass.getTools().forEach((tool) => { this.tools.set(tool.name, tool); // Register by name }); }); this.logger.info(`Registered ${this.tools.size} tools`); } ``` -------------------------------- ### Configuration Inheritance Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/09-architecture.md Demonstrates the priority of configuration sources, showing how system environment variables override .env files and manager defaults. ```bash # System env (highest) export BOOKSTACK_API_TOKEN=system_token # .env file BOOKSTACK_API_TOKEN=env_file_token # Result: system_token wins ``` -------------------------------- ### Production Readiness Environment Variables Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/02-configmanager.md This example shows the required environment variables for a production deployment to ensure the application is ready and secure. ```bash NODE_ENV=production BOOKSTACK_BASE_URL=https://bookstack.prod.com/api # No localhost BOOKSTACK_API_TOKEN=prod_token_id:prod_token_secret DEBUG=false LOG_LEVEL=info ``` -------------------------------- ### ResourceExample Interface Definition Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/04-types.md Defines the structure for an example usage of an MCP resource. It includes the example URI, a description, the expected format, and the use case. ```typescript export interface ResourceExample { uri: string; // Example URI description: string; // Description expected_format: string; // Expected format use_case: string; // Use case } ``` -------------------------------- ### Update Bookstack MCP Server to Latest Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Install the latest available version of the bookstack-mcp-server globally. ```bash npm install -g bookstack-mcp-server@latest ``` -------------------------------- ### Run bookstack-mcp-server in HTTP Mode Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Starts the server in its default HTTP mode, listening on the configured port. ```bash bookstack-mcp-server # Listens on port 3000 (or $SERVER_PORT) ``` -------------------------------- ### URI Encoding Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/resources-guide.md Demonstrates how to encode spaces in URIs for search queries. ```text bookstack://search/API%20guide ``` -------------------------------- ### Instantiate RateLimiter Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/06-utilities.md Example of creating a new RateLimiter instance. Configure with desired requests per minute and burst limit. ```typescript const limiter = new RateLimiter({ requestsPerMinute: 60, // 1 request per second sustained burstLimit: 10 // Up to 10 concurrent }); ``` -------------------------------- ### Local Project Installation of BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/setup-guide.md Install the package within a specific project directory for project-scoped usage. This is useful for managing dependencies per project. ```bash # Create project directory mkdir my-bookstack-mcp cd my-bookstack-mcp # Install locally npm install bookstack-mcp-server # Or install from source git clone https://github.com/pnocera/bookstack-mcp-server.git cd bookstack-mcp-server npm install ``` -------------------------------- ### ConfigManager Methods Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/10-quick-reference.md Methods to get the current configuration, reload it from environment variables, validate it for production, and get a summary. ```typescript getConfig(): Config reload(): Config validateForProduction(): void getSummary(): object ``` -------------------------------- ### Comprehensive Setup Test for BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md This script performs a comprehensive test of the BookStack MCP Server setup, verifying connection, authentication, basic operations, search functionality, and permissions. It's useful for ensuring your environment is correctly configured before proceeding with complex operations. ```javascript // Comprehensive setup test const testSetup = async () => { const tests = [ { name: 'Connection', test: testConnection }, { name: 'Authentication', test: testAuthentication }, { name: 'Basic Operations', test: testBasicOperations }, { name: 'Search Functionality', test: testSearch }, { name: 'Permissions', test: testPermissions } ]; const results = []; for (const test of tests) { try { await test.test(); results.push({ name: test.name, status: 'passed' }); } catch (error) { results.push({ name: test.name, status: 'failed', error: error.message }); } } return results; }; const testConnection = async () => { const info = await tools.bookstack_system_info(); console.log('✓ Connection successful'); }; const testAuthentication = async () => { const books = await tools.bookstack_books_list({ count: 1 }); console.log('✓ Authentication successful'); }; const testBasicOperations = async () => { // Create a test book const book = await tools.bookstack_books_create({ name: 'Test Book', description: 'Test book for setup validation' }); // Create a test page const page = await tools.bookstack_pages_create({ book_id: book.id, name: 'Test Page', markdown: '# Test Page\n\nThis is a test page.' }); // Clean up await tools.bookstack_pages_delete({ id: page.id }); await tools.bookstack_books_delete({ id: book.id }); console.log('✓ Basic operations successful'); }; ``` -------------------------------- ### List All Tools via HTTP Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/10-quick-reference.md Send a POST request to the `/message` endpoint with the `tools/list` method to get a list of available tools. ```bash # List all tools (via HTTP) curl -X POST http://localhost:3000/message \ -H "Content-Type: application/json" \ -d '{"method": "tools/list"}' ``` -------------------------------- ### Pin Bookstack MCP Server to Specific Version Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Install a specific version of the bookstack-mcp-server globally. ```bash npm install -g bookstack-mcp-server@1.0.0 ``` -------------------------------- ### Pretty Log Format Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/06-utilities.md Illustrates the default 'pretty' log format, which is human-readable and includes timestamp, level, message, and metadata. ```text 2024-01-15 14:30:45 [info] User logged in {"userId": 123} 2024-01-15 14:30:46 [error] API error {"status": 500, "message": "..."} ``` -------------------------------- ### Setup Team Collaboration Workflow Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md Automates the creation of roles, users, and a dedicated bookshelf for a team, including setting up initial permissions. Use this to quickly establish a collaborative environment for a new team. ```javascript // Create team structure const setupTeamWorkflow = async (teamConfig) => { // Create team roles const roles = await Promise.all([ tools.bookstack_roles_create({ display_name: "Documentation Editors", description: "Can create and edit documentation", permissions: { "content-export": true, "restrictions-manage-own": true } }), tools.bookstack_roles_create({ display_name: "Documentation Reviewers", description: "Can review and approve documentation", permissions: { "content-export": true, "restrictions-manage-all": true } }) ]); // Create team members const users = await Promise.all(teamConfig.members.map(member => tools.bookstack_users_create({ name: member.name, email: member.email, roles: [roles[member.role === 'reviewer' ? 1 : 0].id], send_invite: true }) )); // Create team bookshelf const teamShelf = await tools.bookstack_shelves_create({ name: `${teamConfig.name} Documentation`, description: `Documentation collection for ${teamConfig.name} team`, tags: [ { name: "team", value: teamConfig.name.toLowerCase() }, { name: "access", value: "team" } ] }); // Set up permissions await tools.bookstack_permissions_update({ content_type: 'bookshelf', content_id: teamShelf.id, permissions: users.map(user => ({ user_id: user.id, view: true, create: true, update: user.roles.includes(roles[1].id), // Reviewers can update delete: false })) }); return { roles, users, shelf: teamShelf }; }; // Usage const teamSetup = await setupTeamWorkflow({ name: "Engineering", members: [ { name: "Alice Johnson", email: "alice@company.com", role: "editor" }, { name: "Bob Smith", email: "bob@company.com", role: "reviewer" }, { name: "Carol Davis", email: "carol@company.com", role: "editor" } ] }); ``` -------------------------------- ### Build and Run BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Provides commands to build the Docker image for the BookStack MCP Server and run it as a container. It also shows how to use docker-compose for a multi-container setup. ```bash # Build Docker image docker build -t bookstack-mcp-server . # Run container docker run -p 3000:3000 \ -e BOOKSTACK_BASE_URL=https://bookstack.com/api \ -e BOOKSTACK_API_TOKEN=token:secret \ bookstack-mcp-server # Or use docker-compose docker-compose up -d ``` -------------------------------- ### Get ConfigManager Instance and Configuration Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/02-configmanager.md Demonstrates how to obtain the singleton ConfigManager instance and then retrieve the application's configuration object. ```typescript const manager = ConfigManager.getInstance(); const config = manager.getConfig(); ``` -------------------------------- ### Run BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/README.md Execute the server directly using npx. By default, this command starts the server in Streamable HTTP mode. ```bash # Or run directly (starts HTTP server by default) npx bookstack-mcp-server ``` -------------------------------- ### Code Analysis and Documentation Creation with Claude Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md Example of Claude analyzing code and creating new documentation pages in BookStack. Requires 'tools.bookstack_pages_create'. ```javascript // Example 2: Code Analysis and Documentation // Claude can analyze code and create documentation // After analyzing code files, Claude can create documentation const apiDocs = await tools.bookstack_pages_create({ book_id: 123, name: "User Management API", markdown: `# User Management API Based on the code analysis, here are the available endpoints: ## POST /api/users Creates a new user account. **Parameters:** - `name` (string): User's full name - `email` (string): User's email address - `password` (string): Password (minimum 8 characters) **Response:** \`\`\`json { "id": 1, "name": "John Doe", "email": "john@example.com", "created_at": "2023-01-01T00:00:00Z" } \`\`\` ## GET /api/users/{id} Retrieves user information. ... `, tags: [ { name: "type", value: "api_reference" }, { name: "generated", value: "true" }, { name: "version", value: "1.0" } ] }); ``` -------------------------------- ### Run bookstack-mcp-server in Development Mode Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Starts the server in development mode using npm run dev, which typically enables features like auto-reloading with ts-node. ```bash npm run dev # Uses ts-node with auto-reload ``` -------------------------------- ### Basic Configuration Access Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/02-configmanager.md Demonstrates how to get an instance of ConfigManager, retrieve the configuration object, and access nested properties for BookStack, server, and rate limiting settings. ```typescript import { ConfigManager } from './config/manager'; const manager = ConfigManager.getInstance(); const config = manager.getConfig(); // Access nested properties console.log(config.bookstack.baseUrl); console.log(config.server.port); console.log(config.rateLimit.requestsPerMinute); ``` -------------------------------- ### ServerUsageExample Interface Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/04-types.md Defines the structure for an example workflow, including its title, description, the sequence of workflow steps, and the expected outcome. Useful for demonstrating how to use server capabilities. ```typescript export interface ServerUsageExample { title: string; description: string; workflow: WorkflowStep[]; expected_outcome: string; } ``` -------------------------------- ### Configuration Summary for Logging Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/02-configmanager.md Provides a method to get a summary of the current configuration, which can be useful for logging purposes. The summary is returned as a JSON string. ```typescript const manager = ConfigManager.getInstance(); const summary = manager.getSummary(); console.log('Current configuration:'); console.log(JSON.stringify(summary, null, 2)); ``` -------------------------------- ### Search Examples Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md Illustrates various search query syntaxes, including exact phrase matching, field-specific searches, entity type filtering, tag-based searches, and boolean operators. ```text "API documentation" // Exact phrase name:authentication // Search in names only [page] authentication // Pages containing authentication tag:category:api // Content tagged as category:api authentication AND security // Boolean search ``` -------------------------------- ### Search Content with BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/README.md Perform a search across BookStack content using the MCP server. This example searches for "API documentation" and limits the results to 20 items. ```javascript bookstack_search({ query: "API documentation", count: 20 }) ``` -------------------------------- ### Research and Documentation with Claude Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md Example of using Claude to search, read, and update documentation in BookStack. Requires 'tools.bookstack_search', 'tools.bookstack_pages_read', and 'tools.bookstack_pages_update' to be available. ```javascript // Example 1: Research and Documentation // Claude can now directly access your BookStack instance // Search for existing documentation const searchResults = await tools.bookstack_search({ query: "authentication API [page]", count: 10 }); // Read existing content const existingDoc = await tools.bookstack_pages_read({ id: searchResults.data[0].id }); // Update with new information await tools.bookstack_pages_update({ id: existingDoc.id, markdown: `${existingDoc.markdown}\n\n## New Section\n\nAdditional content...` }); ``` -------------------------------- ### Example Environment File (.env) Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/02-configmanager.md This file demonstrates how to set environment variables for various application settings, including BookStack connection details, server configuration, rate limiting, validation, logging, context7, security, and development flags. ```bash # BookStack Connection BOOKSTACK_BASE_URL=https://bookstack.example.com/api BOOKSTACK_API_TOKEN=abc123:xyz789 BOOKSTACK_TIMEOUT=30000 # Server Settings SERVER_NAME=bookstack-mcp-server SERVER_VERSION=1.0.0 SERVER_PORT=3000 # Rate Limiting RATE_LIMIT_REQUESTS_PER_MINUTE=60 RATE_LIMIT_BURST_LIMIT=10 # Validation VALIDATION_ENABLED=true VALIDATION_STRICT_MODE=false # Logging LOG_LEVEL=info LOG_FORMAT=pretty # Context7 CONTEXT7_ENABLED=true CONTEXT7_LIBRARY_ID=/bookstack/bookstack CONTEXT7_CACHE_TTL=3600 # Security CORS_ENABLED=true CORS_ORIGIN=* HELMET_ENABLED=true # Development NODE_ENV=production DEBUG=false ``` -------------------------------- ### Search and Organize Content Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md Provides examples for searching content using keywords, listing books filtered by author, retrieving the full structure of a book, and exporting book content in PDF format. ```typescript // Search for API-related content const apiContent = await bookstack_search({ query: '[page] API AND authentication', count: 50 }); // Find all books by a specific author const userBooks = await bookstack_books_list({ filter: { created_by: 5 }, sort: 'updated_at' }); // Get complete book structure const fullBook = await bookstack_books_read({ id: 1 }); console.log(`Book has ${fullBook.contents.length} items`); // Export documentation const pdfExport = await bookstack_books_export({ id: 1, format: 'pdf' }); ``` -------------------------------- ### Register Custom Tool Instance Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/07-tools-resources.md Instantiate your custom tool class and add it to the list of tool classes during the server setup. Ensure all necessary dependencies like client, validator, and logger are provided. ```typescript const toolClasses = [ // ... existing new CustomTools(this.client, this.validator, this.logger), ]; ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Environment variables for the development setup. Includes settings for Node.js environment, debugging, logging, BookStack API, rate limiting, and security headers. ```bash NODE_ENV=development DEBUG=true LOG_LEVEL=debug LOG_FORMAT=pretty VALIDATION_STRICT_MODE=true BOOKSTACK_BASE_URL=http://localhost:8080/api BOOKSTACK_API_TOKEN=local_token:local_secret BOOKSTACK_TIMEOUT=30000 RATE_LIMIT_REQUESTS_PER_MINUTE=1000 RATE_LIMIT_BURST_LIMIT=100 CORS_ENABLED=true CORS_ORIGIN=* HELMET_ENABLED=false ``` -------------------------------- ### Creating Server with Configuration Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/02-configmanager.md Shows how to instantiate the BookStackMCPServer using configuration values retrieved from the ConfigManager, specifically for BookStack connection details. ```typescript import { BookStackMCPServer } from './server'; import { ConfigManager } from './config/manager'; const configManager = ConfigManager.getInstance(); const config = configManager.getConfig(); const server = new BookStackMCPServer({ bookstack: { baseUrl: config.bookstack.baseUrl, apiToken: config.bookstack.apiToken, timeout: config.bookstack.timeout, } }); ``` -------------------------------- ### Configuration Initialization Sequence Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/09-architecture.md Outlines the steps involved in initializing the configuration, from loading .env files to validating and storing the configuration object. ```mermaid graph TD A[Process Start] --> B(dotenv.config() - Load .env file) B --> C(ConfigManager.getInstance()) C -- Load environment variables --> D C -- Construct raw config object --> D C -- Validate with Zod schema --> D C -- Apply defaults --> D C -- Store validated Config --> D D --> E[Config usage in BookStackMCPServer] E -- Pass to BookStackClient --> F E -- Pass to ValidationHandler --> F E -- Pass to other components --> F ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Sets up the required and optional environment variables in a .env file for server configuration. Includes BookStack connection details and server settings. ```bash # BookStack Connection (Required) BOOKSTACK_BASE_URL=https://bookstack.example.com/api BOOKSTACK_API_TOKEN=token_id:token_secret # Optional: Override defaults SERVER_PORT=3000 NODE_ENV=production MCP_TRANSPORT=http ``` -------------------------------- ### BookStack Books List Request Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md An example of a request payload for the List Books API endpoint. This demonstrates how to specify count, filter by name, and sort by update time. ```json { "count": 10, "filter": { "name": "API" }, "sort": "updated_at" } ``` -------------------------------- ### Get BookStack System Information Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/01-bootstackclient.md Retrieves essential BookStack system details including version, theme, and upload limits. Use this to get configuration details about the BookStack instance. ```typescript async getSystemInfo(): Promise ``` ```typescript const info = await client.getSystemInfo(); console.log(`BookStack ${info.version}`); console.log(`Theme: ${info.theme}`); console.log(`Max upload: ${info.upload_limit} bytes`); ``` -------------------------------- ### Create Book, Chapters, and Pages Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md Demonstrates the process of creating a complete documentation structure by first creating a book, then its chapters, and finally populating it with pages. Includes adding tags and organizing books into shelves. ```typescript // 1. Create a book const book = await bookstack_books_create({ name: "API Documentation", description: "Complete REST API reference", tags: [ { name: "category", value: "documentation" }, { name: "version", value: "1.0" } ] }); // 2. Create chapters const authChapter = await bookstack_chapters_create({ book_id: book.id, name: "Authentication", description: "API authentication methods", priority: 1 }); const endpointsChapter = await bookstack_chapters_create({ book_id: book.id, name: "Endpoints", description: "Available API endpoints", priority: 2 }); // 3. Create pages const authPage = await bookstack_pages_create({ chapter_id: authChapter.id, name: "Getting Started", markdown: `# Authentication ## API Token Your API token must be included in the Authorization header: \`\`\` Authorization: Token your_token_here \`\`\` ## Rate Limits - 60 requests per minute - 10 request burst capacity `, tags: [{ name: "type", value: "guide" }] }); // 4. Add to a bookshelf await bookstack_shelves_create({ name: "Developer Resources", books: [book.id] }); ``` -------------------------------- ### Create Project Documentation Structure Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md Automates the creation of a new documentation project in BookStack, including the main book, organized chapters, and initial pages. This is useful for setting up new project documentation from scratch. ```javascript // Step 1: Create the main project book const projectBook = await tools.bookstack_books_create({ name: "Project Alpha Documentation", description: "Complete documentation for Project Alpha", tags: [ { name: "project", value: "alpha" }, { name: "status", value: "active" }, { name: "team", value: "engineering" } ] }); // Step 2: Create chapters for organization const chapters = await Promise.all([ tools.bookstack_chapters_create({ book_id: projectBook.id, name: "Getting Started", description: "Setup and installation guides", priority: 1 }), tools.bookstack_chapters_create({ book_id: projectBook.id, name: "API Reference", description: "Complete API documentation", priority: 2 }), tools.bookstack_chapters_create({ book_id: projectBook.id, name: "Examples", description: "Code examples and tutorials", priority: 3 }) ]); // Step 3: Create initial pages const pages = await Promise.all([ tools.bookstack_pages_create({ chapter_id: chapters[0].id, name: "Quick Start Guide", markdown: `# Quick Start Guide ## Installation \`\`\`bash npm install project-alpha \`\`\` ## Configuration ... `, tags: [{ name: "type", value: "guide" }] }), tools.bookstack_pages_create({ chapter_id: chapters[1].id, name: "Authentication", markdown: `# Authentication ## API Keys ... `, tags: [{ name: "type", value: "reference" }] }) ]); ``` -------------------------------- ### BookStack Books List Response Example Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md An example response from the List Books API endpoint, showing a paginated list of books with total count. Includes book details like ID, name, and timestamps. ```json { "data": [ { "id": 1, "name": "API Documentation", "slug": "api-documentation", "description": "Complete API reference guide", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-20T15:45:00Z", "created_by": 1, "updated_by": 1, "owned_by": 1, "tags": [ { "name": "category", "value": "documentation", "order": 0 } ] } ], "total": 1 } ``` -------------------------------- ### Get Image Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/01-bootstackclient.md Retrieves a specific image by its ID. ```typescript async getImage(id: number): Promise ``` -------------------------------- ### Deploy and Manage Bookstack on Kubernetes Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Commands to create a namespace, apply the deployment configuration, check pod status, view logs, and port-forward for testing. ```bash # Create namespace kubectl create namespace bookstack # Apply configuration kubectl apply -f deployment.yaml -n bookstack # Check status kubectl get pods -n bookstack kubectl logs -f deployment/bookstack-mcp-server -n bookstack # Port forward for testing kubectl port-forward svc/bookstack-mcp-server 3000:3000 -n bookstack ``` -------------------------------- ### Get Attachment Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/01-bootstackclient.md Retrieves a specific attachment by its unique identifier. ```typescript async getAttachment(id: number): Promise ``` -------------------------------- ### Get Role Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/01-bootstackclient.md Retrieves a specific role, including its associated permissions. ```typescript async getRole(id: number): Promise ``` -------------------------------- ### BookStackClient - Get Page Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/10-quick-reference.md Retrieve a specific page by its ID, including its content. ```typescript getPage(id: number): Promise ``` -------------------------------- ### Implement Documentation Review Workflow Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md Sets up a review process by tagging pages and creating individual review task pages for specified reviewers. Use this to manage the approval of documentation changes. ```javascript // Create review workflow const createReviewWorkflow = async (pageId, reviewerIds) => { const page = await tools.bookstack_pages_read({ id: pageId }); // Create review tracking tags const reviewTags = [ { name: "status", value: "pending_review" }, { name: "review_requested", value: new Date().toISOString() }, { name: "reviewers", value: reviewerIds.join(",") } ]; // Update page with review status await tools.bookstack_pages_update({ id: pageId, tags: [...page.tags, ...reviewTags] }); // Create review task pages const reviewTasks = await Promise.all(reviewerIds.map(async (reviewerId) => { const reviewer = await tools.bookstack_users_read({ id: reviewerId }); return tools.bookstack_pages_create({ book_id: page.book_id, name: `Review: ${page.name} (${reviewer.name})`, markdown: `# Review Task: ${page.name} ## Reviewer ${reviewer.name} ## Original Page [${page.name}](${page.url}) ## Review Checklist - [ ] Content accuracy - [ ] Grammar and style - [ ] Completeness - [ ] Links and references - [ ] Code examples (if applicable) ## Comments ## Decision `, tags: [ { name: "type", value: "review_task" }, { name: "target_page", value: pageId.toString() }, { name: "reviewer", value: reviewerId.toString() }, { name: "status", value: "pending" } ] }); })); return { page, reviewTasks }; }; // Check review status const checkReviewStatus = async (pageId) => { const reviewTasks = await tools.bookstack_search({ query: `tag:type=review_task tag:target_page=${pageId}`, count: 20 }); const status = { total: reviewTasks.data.length, completed: 0, approved: 0, rejected: 0, pending: 0 }; for (const task of reviewTasks.data) { const taskDetails = await tools.bookstack_pages_read({ id: task.id }); const statusTag = taskDetails.tags.find(t => t.name === 'status'); if (statusTag) { switch (statusTag.value) { case 'approved': status.approved++; status.completed++; break; case 'rejected': status.rejected++; status.completed++; break; case 'changes_requested': status.completed++; break; default: status.pending++; } } } return status; }; ``` -------------------------------- ### BookStackClient - Get Book Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/10-quick-reference.md Retrieve a specific book by its ID, including its contents. ```typescript getBook(id: number): Promise ``` -------------------------------- ### Get Specific User Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/resources-guide.md Retrieves a specific user by their ID, including their associated roles. ```APIDOC ## GET bookstack://users/{id} ### Description Gets a specific user by their ID, returning the complete user object with role information. ### Method GET ### Endpoint bookstack://users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **id** (Integer) - The user's unique identifier. - **name** (String) - The name of the user. - **email** (String) - The email address of the user. - **roles** (Array) - An array of role objects associated with the user. #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john@example.com", "roles": [ { "id": 2, "display_name": "Editor", "description": "Can edit content" } ] } ``` ``` -------------------------------- ### Docker Build and Run Commands Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/setup-guide.md Commands to build the Docker image for BookStack MCP Server and run it as a container, mapping ports and setting environment variables. ```bash # Build image docker build -t bookstack-mcp-server . # Run container docker run -d \ --name bookstack-mcp \ -p 3000:3000 \ -e BOOKSTACK_BASE_URL=http://bookstack:8080/api \ -e BOOKSTACK_API_TOKEN=your-token \ bookstack-mcp-server ``` -------------------------------- ### Get Shelf Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/01-bootstackclient.md Retrieves a specific shelf along with all its associated books. Requires the shelf ID. ```typescript async getShelf(id: number): Promise ``` -------------------------------- ### Get Specific Shelf Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/resources-guide.md Retrieves a specific shelf by its ID, including all the books contained within it. ```APIDOC ## GET bookstack://shelves/{id} ### Description Gets a specific shelf by its ID, returning the complete shelf object with nested books. ### Method GET ### Endpoint bookstack://shelves/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the shelf. ### Response #### Success Response (200) - **id** (Integer) - The shelf's unique identifier. - **name** (String) - The name of the shelf. - **books** (Array) - An array of book objects contained within the shelf. #### Response Example ```json { "id": 321, "name": "Technical Documentation", "books": [ { "id": 123, "name": "API Guide", "description": "Complete API documentation" }, { "id": 124, "name": "Installation Guide", "description": "Step-by-step installation" } ] } ``` ``` -------------------------------- ### Create Knowledge Base and Organize Books Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/examples-and-workflows.md Implements the creation of a knowledge base in BookStack, including books, chapters, and pages, and organizes them using shelves. Requires a predefined structure. ```javascript // Create the knowledge base const createKnowledgeBase = async (structure) => { // Step 1: Create the main book const book = await tools.bookstack_books_create({ name: structure.name, description: structure.description, tags: [ { name: "type", value: "knowledge_base" }, { name: "status", value: "active" }, { name: "created", value: new Date().toISOString() } ] }); // Step 2: Create chapters and pages const chapters = []; let chapterPriority = 1; for (const [chapterName, pages] of Object.entries(structure.structure)) { const chapter = await tools.bookstack_chapters_create({ book_id: book.id, name: chapterName, description: `${chapterName} documentation`, priority: chapterPriority++ }); chapters.push(chapter); // Create pages within the chapter let pagePriority = 1; for (const [pageName, contentType] of Object.entries(pages)) { const page = await tools.bookstack_pages_create({ chapter_id: chapter.id, name: pageName, markdown: generateTemplateContent(pageName, contentType), priority: pagePriority++, tags: [ { name: "template", value: "true" }, { name: "content_type", value: contentType } ] }); } } // Step 3: Create a bookshelf to organize related books const shelf = await tools.bookstack_shelves_create({ name: "Project Documentation", description: "All documentation for the project", books: [book.id], tags: [ { name: "project", value: "main" }, { name: "type", value: "documentation_collection" } ] }); return { book, chapters, shelf }; }; // Generate template content for different content types const generateTemplateContent = (pageName, contentType) => { const templates = { markdown: `# ${pageName}`, ## Overview ## Content ## See Also --- *Last updated: ${new Date().toISOString()}* `, api: `# ${pageName}`, ## Endpoints ### GET /api/example **Parameters:** - `param1` (string): Description **Response:** ```json { "example": "response" } ``` ## Examples ```bash curl -X GET /api/example ``` `, guide: `# ${pageName}`, ## Prerequisites ## Step-by-Step Instructions ### Step 1: Initial Setup ### Step 2: Configuration ## Troubleshooting ## Next Steps ` }; return templates[contentType] || templates.markdown; }; ``` -------------------------------- ### Get Current Token Count Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/06-utilities.md Retrieves the current number of available tokens. This can be a fractional value. ```typescript getTokenCount(): number ``` ```typescript const tokens = limiter.getTokenCount(); console.log(`${Math.floor(tokens)} tokens available`); ``` -------------------------------- ### Create Shelf Parameters Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md Defines parameters for creating a new bookshelf. Requires a name. Supports optional description, description_html, tags, and an array of book IDs. ```typescript // Tool: bookstack_shelves_create interface CreateShelfParams { name: string; // Required, max 255 chars description?: string; // Optional, max 1900 chars description_html?: string; // Optional, max 2000 chars tags?: Tag[]; // Optional tags books?: number[]; // Optional array of book IDs } ``` -------------------------------- ### Get User API Method Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/01-bootstackclient.md Retrieves a specific user's details along with their assigned roles. ```typescript async getUser(id: number): Promise ``` -------------------------------- ### Get System Info Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md Retrieves information about the BookStack system, including version, configuration, and feature status. ```APIDOC ## Get System Info ### Description Retrieves information about the BookStack system, including version, configuration, and feature status. ### Method GET ### Endpoint /api/system ### Response #### Success Response (200) - **version** (string) - The current BookStack version. - **instance_id** (string) - A unique identifier for this BookStack instance. - **php_version** (string) - The version of PHP running the server. - **theme** (string) - The name of the currently active theme. - **language** (string) - The default language of the application. - **timezone** (string) - The server's configured timezone. - **app_url** (string) - The base URL of the BookStack application. - **drawing_enabled** (boolean) - Indicates if the drawing feature is enabled. - **registrations_enabled** (boolean) - Indicates if user registrations are currently enabled. - **upload_limit** (number) - The maximum file upload size in bytes. #### Response Example { "version": "23.10.1", "instance_id": "abc123xyz789", "php_version": "8.1.10", "theme": "default", "language": "en", "timezone": "UTC", "app_url": "https://bookstack.example.com", "drawing_enabled": true, "registrations_enabled": false, "upload_limit": 20971520 } ``` -------------------------------- ### Integrate bookstack-mcp-server with Claude Desktop Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Shows how to add the bookstack-mcp-server as a tool within Claude Desktop, configuring its environment variables for stdio transport. ```bash claude mcp add bookstack \ npx bookstack-mcp-server \ --env BOOKSTACK_BASE_URL=https://bookstack.local/api \ --env BOOKSTACK_API_TOKEN=my_token:my_secret \ --env MCP_TRANSPORT=stdio ``` -------------------------------- ### Runtime Configuration Object Structure Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/02-configmanager.md Illustrates the expected structure of the complete runtime configuration object, including descriptions for each property. ```typescript { bookstack: { baseUrl: string; // API endpoint URL apiToken: string; // Authentication token timeout: number; // Request timeout in milliseconds }; server: { name: string; // Server name for User-Agent version: string; // Version string port: number; // HTTP port to listen on }; rateLimit: { requestsPerMinute: number; // Rate limit ceiling burstLimit: number; // Max burst requests }; validation: { enabled: boolean; // Enable input validation strictMode: boolean; // Throw on validation failure }; logging: { level: 'error' | 'warn' | 'info' | 'debug'; // Log level format: 'json' | 'pretty'; // Output format }; context7: { enabled: boolean; // Enable Context7 integration libraryId: string; // Library identifier cacheTtl: number; // Cache TTL in seconds }; security: { corsEnabled: boolean; // Enable CORS corsOrigin: string; // CORS origin pattern helmetEnabled: boolean; // Enable Helmet.js security }; development: { nodeEnv: 'development' | 'production' | 'test'; debug: boolean; // Debug mode }; } ``` -------------------------------- ### Get Specific Chapter Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/resources-guide.md Retrieves a specific chapter, including all of its nested pages. Requires the chapter ID. ```APIDOC ## Get Specific Chapter ### Description Retrieves a specific chapter, including all of its nested pages. Requires the chapter ID. ### Method GET ### Endpoint `bookstack://chapters/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the chapter to retrieve. ### Request Example None ### Response #### Success Response (200) - **id** (integer) - The chapter's ID. - **name** (string) - The chapter's name. - **pages** (array) - An array of page objects nested within this chapter. **Page Object Schema**: ```json { "id": 789, "name": "Overview", "priority": 1 } ``` ### Response Example ```json { "id": 456, "name": "Getting Started", "pages": [ { "id": 789, "name": "Overview", "priority": 1 }, { "id": 790, "name": "Installation", "priority": 2 } ] } ``` ``` -------------------------------- ### Hierarchical Navigation Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/resources-guide.md Navigate through the resource hierarchy, starting from shelves, then books, chapters, and finally individual pages. ```javascript // Step 1: Get shelf organization const shelf = await readResource(`bookstack://shelves/${shelfId}`); // Step 2: Navigate to specific book const book = await readResource(`bookstack://books/${bookId}`); // Step 3: Read chapter contents const chapter = await readResource(`bookstack://chapters/${chapterId}`); // Step 4: Access individual pages const page = await readResource(`bookstack://pages/${pageId}`); ``` -------------------------------- ### Run bookstack-mcp-server in Stdio Mode Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Configures and runs the server to use standard input/output for communication, suitable for local integrations like Claude Desktop. ```bash export MCP_TRANSPORT=stdio bookstack-mcp-server ``` -------------------------------- ### User and Permission Management Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/docs/api-reference.md Illustrates how to create custom roles with specific permissions, create new users, assign them to roles, and update book-level permissions for viewing, creating, updating, and deleting content. ```typescript // Create documentation team role const docRole = await bookstack_roles_create({ display_name: "Documentation Team", description: "Can manage documentation content", permissions: { 'content-export': true, 'restrictions-manage-own': true } }); // Create team member const user = await bookstack_users_create({ name: "Jane Smith", email: "jane@company.com", roles: [docRole.id], send_invite: true }); // Set book permissions await bookstack_permissions_update('book', 1, { permissions: [ { role_id: docRole.id, view: true, create: true, update: true, delete: false } ] }); ``` -------------------------------- ### Get Chapter API Method Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/01-bootstackclient.md Retrieves a specific chapter along with all its associated pages. Requires the chapter ID. ```typescript async getChapter(id: number): Promise ``` -------------------------------- ### Dockerfile for BookStack MCP Server Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/08-deployment-startup.md Defines the steps to build a Docker image for the BookStack MCP Server. It sets up the Node.js environment, copies application code, creates a non-root user, exposes the application port, and configures health checks and the start command. ```dockerfile FROM node:18-alpine WORKDIR /app # Copy package files COPY package*.json . RUN npm ci --only=production # Copy built application COPY dist ./dist # Create non-root user RUN addgroup -g 1001 -S nodejs RUN adduser -S nodejs -u 1001 USER nodejs # Expose port EXPOSE 3000 # Health check HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ CMD node -e "require('http').get('http://localhost:3000/health', (r) => r.statusCode === 200 ? process.exit(0) : process.exit(1))" # Start server CMD ["node", "dist/server.js"] ``` -------------------------------- ### Get Singleton Logger Instance Source: https://github.com/pnocera/bookstack-mcp-server/blob/main/_autodocs/06-utilities.md Retrieves the single instance of the Logger. Ensure the Logger class is imported before use. ```typescript import { Logger } from './utils/logger'; const logger = Logger.getInstance(); logger.info('Application started'); ```