UNPKG

n8n-bookstack-agent-tool

Version:

Comprehensive BookStack API integration tool for n8n AI Agent with MCP framework compatibility

397 lines (307 loc) 12.9 kB
# BookStack n8n AI Agent Tool A comprehensive AI Agent Tool for integrating the BookStack API within the n8n AI Agent framework. This tool enables n8n AI Agents to autonomously read, create, modify, and delete documentation data through the BookStack API using LangChain-compatible tools. ## Features - **n8n AI Agent Integration**: Designed specifically as an AI Agent Tool for n8n workflows - **Full BookStack API Coverage**: 46+ commands covering all major BookStack resources - **LangChain Compatible**: Built with DynamicStructuredTool for seamless AI Agent integration - **Modular Architecture**: Each API resource implemented as its own module - **Introspectable**: All commands and parameters machine-readable for AI Agents - **GUI Configurable**: Connection settings manageable via n8n AI Agent interface - **Comprehensive Error Handling**: HTTP 4xx, 5xx, network and timeout errors - **Built-in Caching**: Optional caching for improved performance - **TypeScript Support**: Full type definitions included ## Supported Resources - **Books**: Create, read, update, delete, and export books - **Chapters**: Manage book chapters with full CRUD operations - **Pages**: Handle individual pages with content management - **Shelves**: Organize books into shelves - **Users**: User management and administration - **Roles**: Role-based access control - **Attachments**: File attachment management - **Tags**: Tagging system for content organization ## Installation in n8n ### Method 1: Docker Container Installation If you're running n8n in Docker, install the package in your container: ```bash # Access your n8n Docker container docker exec -it your-n8n-container npm install n8n-bookstack-agent-tool # Restart the container docker restart your-n8n-container ``` ### Method 2: Local n8n Installation For local n8n installations: ```bash npm install n8n-bookstack-agent-tool ``` ## Usage in n8n AI Agent ### Step 1: Create an AI Agent Workflow 1. **Create a new workflow** in n8n 2. **Add a trigger node** (e.g., "When chat message received" or "Manual Trigger") 3. **Add an AI Agent node** to your workflow 4. **Connect the trigger** to the AI Agent node ### Step 2: Add BookStack Tool to AI Agent 1. **Click on the AI Agent node** to configure it 2. **In the Tools section**, click the "+" button to add a new tool 3. **Search for "BookStack"** in the tool selection dropdown 4. **Select the BookStack tool** from the available options 5. **Configure the tool settings**: - **Name**: `bookstack_tool` (or customize as needed) - **Description**: `Tool for interacting with BookStack API to manage documentation` ### Step 3: Configure BookStack API Credentials 1. **Create BookStack API credentials** in n8n: - Go to **Credentials** in the left sidebar - Click **"Add Credential"** - Search for **"BookStack API"** - Fill in your BookStack details: - **Base URL**: Your BookStack instance URL (e.g., `https://wiki.l7cloud.io`) - **Token ID**: Your BookStack API token ID - **Token Secret**: Your BookStack API token secret 2. **Assign credentials to the tool**: - In the BookStack tool configuration - Select your created BookStack API credentials ### Step 4: Configure AI Model 1. **Add a Chat Model** to your AI Agent (if not already present) 2. **Connect it to the Model input** of the AI Agent 3. **Configure your preferred AI model** (OpenAI, Anthropic, etc.) ### Step 5: Test Your AI Agent 1. **Save your workflow** 2. **Execute the workflow** or send a test message 3. **Try AI prompts** that would use BookStack functionality: - "List all books in our documentation" - "Create a new book called 'API Guide'" - "Show me the content of page ID 123" - "Export book ID 5 as PDF" ## Configuration ### Authentication Methods #### Bearer Token (Recommended) ```typescript const config = { baseUrl: 'https://your-bookstack.example.com', authType: 'bearer', token: 'your-api-token-here' }; ``` #### Session Cookie ```typescript const config = { baseUrl: 'https://your-bookstack.example.com', authType: 'session', sessionCookie: 'bookstack_session=your-session-cookie' }; ``` ### n8n GUI Configuration The tool provides a complete configuration interface for n8n: - **BookStack Base URL**: Your BookStack instance URL - **Authentication Method**: Choose between Bearer Token or Session Cookie - **API Token**: Your BookStack API token (for Bearer auth) - **Session Cookie**: Your session cookie (for Session auth) - **Request Timeout**: Timeout for API requests (1000-300000ms) - **Retry Attempts**: Number of retry attempts (0-10) - **Retry Delay**: Delay between retries (100-10000ms) ## Available Commands The tool provides 46+ commands for comprehensive BookStack API interaction. The AI Agent can use any of these commands based on user requests: ### Books - `listBooks` - List all books with optional filtering - `getBook` - Get a specific book by ID - `createBook` - Create a new book - `updateBook` - Update an existing book - `deleteBook` - Delete a book - `exportBookHtml` - Export book as HTML - `exportBookPdf` - Export book as PDF - `exportBookMarkdown` - Export book as Markdown - `exportBookPlainText` - Export book as plain text ### Pages - `listPages` - List all pages with optional filtering - `getPage` - Get a specific page by ID - `createPage` - Create a new page - `updatePage` - Update an existing page - `deletePage` - Delete a page - `exportPageHtml` - Export page as HTML - `exportPagePdf` - Export page as PDF - `exportPageMarkdown` - Export page as Markdown - `exportPagePlainText` - Export page as plain text ### Chapters - `listChapters` - List all chapters - `getChapter` - Get a specific chapter by ID - `createChapter` - Create a new chapter - `updateChapter` - Update an existing chapter - `deleteChapter` - Delete a chapter - `exportChapterHtml` - Export chapter as HTML - `exportChapterPdf` - Export chapter as PDF - `exportChapterMarkdown` - Export chapter as Markdown - `exportChapterPlainText` - Export chapter as plain text ### Shelves, Users, Roles, Attachments & Tags - Complete CRUD operations for all resource types - Export functionality where applicable - Advanced filtering and search capabilities ## AI Agent Usage Examples ### Example 1: Documentation Overview ``` User: "Show me all the books in our documentation system" AI Agent: Uses BookStack tool with command "listBooks" Response: Returns formatted list of all available books ``` ### Example 2: Content Creation ``` User: "Create a new book called 'API Documentation' with description 'REST API reference guide'" AI Agent: Uses BookStack tool with: { "command": "createBook", "parameters": { "name": "API Documentation", "description": "REST API reference guide" } } Response: Confirms book creation with ID and details ``` ### Example 3: Content Export ``` User: "Export the 'User Manual' book as a PDF" AI Agent: 1. First finds the book using "listBooks" with search 2. Then uses "exportBookPdf" with the found book ID Response: Provides download link or export confirmation ``` ### Example 4: Content Search and Update ``` User: "Find the page about user authentication and update its title to 'Advanced Authentication'" AI Agent: 1. Uses "listPages" to search for authentication-related pages 2. Uses "updatePage" to modify the found page Response: Confirms the page update ``` ## Tool Configuration in n8n ### BookStack API Credentials Setup 1. **Generate API Token in BookStack**: - Log into your BookStack instance - Go to **Settings → API Tokens** - Click **"Create Token"** - Copy the **Token ID** and **Token Secret** 2. **Configure in n8n**: - **Base URL**: Full URL to your BookStack instance (e.g., `https://wiki.l7cloud.io`) - **Token ID**: The API token ID from BookStack - **Token Secret**: The API token secret from BookStack ### Tool Parameters The BookStack tool accepts two main parameters: - **command**: The BookStack API command to execute (e.g., `listBooks`, `createPage`) - **parameters**: Object containing command-specific parameters (e.g., `{id: "123", name: "New Title"}`) ## Advanced Usage ### Filtering and Pagination ``` User: "Show me the first 10 books sorted by name" AI Agent: Uses "listBooks" with parameters: {"count": 10, "sort": "name"} ``` ### Complex Operations ``` User: "Create a new chapter in the 'User Guide' book with title 'Getting Started'" AI Agent: 1. Uses "listBooks" to find the "User Guide" book 2. Uses "createChapter" with the book ID and chapter details ``` ### Error Handling The tool provides comprehensive error handling that the AI Agent can interpret and respond to appropriately: - **Authentication errors**: "Invalid API credentials" - **Not found errors**: "Resource with ID X not found" - **Validation errors**: "Missing required field: name" - **Permission errors**: "Insufficient permissions for this operation" ## Caching The tool includes optional caching for improved performance: ```typescript // Get cache statistics const stats = tool.getCacheStats(); console.log('Cache size:', stats.size); // Clear cache tool.clearCache(); // Cache is automatically managed for GET operations // and invalidated on CREATE/UPDATE/DELETE operations ``` ## CLI Usage (Development/Testing) The package includes a CLI tool for testing and development: ```bash # Test connection bookstack-tool test --url https://wiki.l7cloud.io --token YOUR_TOKEN # List available commands bookstack-tool commands # Execute a command bookstack-tool exec listBooks --url https://wiki.l7cloud.io --token YOUR_TOKEN # Create a book bookstack-tool exec createBook --url https://wiki.l7cloud.io --token YOUR_TOKEN --name "Test Book" ``` ## Troubleshooting ### Tool Not Appearing in n8n 1. **Verify installation**: Ensure the package is installed in your n8n environment 2. **Restart n8n**: Restart your n8n instance after installation 3. **Check logs**: Look for any error messages in n8n logs 4. **Version compatibility**: Ensure you're using a compatible n8n version ### API Connection Issues 1. **Verify credentials**: Test your BookStack API token in the BookStack interface 2. **Check URL**: Ensure the Base URL is correct and accessible 3. **Network access**: Verify n8n can reach your BookStack instance 4. **Firewall settings**: Check if your BookStack instance allows API access ### Common Error Messages - **"Connection test failed"**: Check your Base URL and network connectivity - **"Invalid token"**: Verify your Token ID and Token Secret - **"Validation failed"**: Check that required parameters are provided - **"Resource not found"**: Verify the ID exists in your BookStack instance ## Performance Optimization ### Caching The tool includes built-in caching for: - List operations (automatically cached for 5 minutes) - Get operations (cached until related resources are modified) - Automatic cache invalidation on create/update/delete operations ### Rate Limiting - Built-in retry logic with exponential backoff - Configurable retry attempts (default: 3) - Configurable retry delay (default: 1000ms) ## Security Considerations - **API Tokens**: Store securely in n8n credentials, never in workflow code - **Permissions**: Use BookStack API tokens with minimal required permissions - **Network Security**: Ensure secure communication between n8n and BookStack - **Access Control**: Implement proper access controls in your BookStack instance ## MCP Integration The tool is fully compatible with the Model Context Protocol (MCP): ```typescript // Get MCP command metadata const metadata = tool.getCommandMetadata(); // Commands are automatically registered and introspectable const commands = tool.getAvailableCommands(); // Each command includes: // - name: Command identifier // - description: Human-readable description // - inputSchema: JSON schema for parameters // - required: List of required parameters ``` ## TypeScript Support Full TypeScript definitions are included: ```typescript import { BookStackConfig, BookStackError, BookStackErrorType, MCPCommand, ExecutableMethod } from 'n8n-bookstack-agent-tool'; // Type-safe configuration const config: BookStackConfig = { baseUrl: 'https://bookstack.example.com', authType: 'bearer', token: 'token' }; // Type-safe error handling const handleError = (error: BookStackError) => { // TypeScript knows about all error properties }; ``` ## Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests 5. Submit a pull request ## License MIT License - see LICENSE file for details. ## Support For issues and questions: - GitHub Issues: [Repository Issues](https://github.com/devin-ai/n8n-bookstack-agent-tool/issues) - Documentation: [BookStack API Docs](https://demo.bookstackapp.com/api/docs) - n8n Community: [n8n Community Forum](https://community.n8n.io)