fetch_documentation_tool
Retrieves and formats narrative documentation from Ilograph. Provides tutorials, examples, and explanations for learning Ilograph concepts and implementation patterns.
Instructions
Fetches and formats narrative documentation from Ilograph website.
This tool provides detailed explanations, tutorials, and examples for learning
Ilograph concepts and implementation patterns. Content is fetched from the official
Ilograph documentation site and converted to clean markdown format.
Args:
section: Documentation section to fetch. Supported sections:
- 'resources' -> Resource tree organization, hierarchies, instanceOf patterns
- 'relation-perspectives' -> Arrow connections, from/to properties, routing, labels
- 'sequence-perspectives' -> Time-based diagrams with steps, bidirectional flows
- 'references' -> Resource reference patterns and advanced referencing
- 'advanced-references' -> Complex reference scenarios and usage patterns
- 'resource-sizes-and-positions' -> Layout control, resource sizing, visual hierarchy
- 'parent-overrides' -> Resource parent overrides in perspectives with scale properties
- 'perspectives-other-properties' -> Additional perspective properties and options
- 'icons' -> Icon system with iconStyle, icon paths, and categorization
- 'walkthroughs' -> Interactive step-by-step guides through diagrams
- 'contexts' -> Multiple context views with roots, extends inheritance
- 'imports' -> Namespace management with from/namespace properties, component reuse
- 'markdown' -> Rich text support in descriptions, notes, and diagram text
- 'tutorial' -> Complete tutorial for learning Ilograph diagram creation
Returns:
str: Clean markdown content with detailed explanations, examples, and best practices
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| section | Yes |
Implementation Reference
- The main handler function 'fetch_documentation_tool' - an async FastMCP tool that fetches Ilograph documentation sections. It validates the section parameter, checks against supported sections via fetcher.get_supported_documentation_sections(), fetches content via fetcher.fetch_documentation_section(), and returns markdown-formatted content with metadata header and error handling.
async def fetch_documentation_tool(section: str, ctx: Context) -> str: """ Fetches and formats narrative documentation from Ilograph website. This tool provides detailed explanations, tutorials, and examples for learning Ilograph concepts and implementation patterns. Content is fetched from the official Ilograph documentation site and converted to clean markdown format. Args: section: Documentation section to fetch. Supported sections: - 'resources' -> Resource tree organization, hierarchies, instanceOf patterns - 'relation-perspectives' -> Arrow connections, from/to properties, routing, labels - 'sequence-perspectives' -> Time-based diagrams with steps, bidirectional flows - 'references' -> Resource reference patterns and advanced referencing - 'advanced-references' -> Complex reference scenarios and usage patterns - 'resource-sizes-and-positions' -> Layout control, resource sizing, visual hierarchy - 'parent-overrides' -> Resource parent overrides in perspectives with scale properties - 'perspectives-other-properties' -> Additional perspective properties and options - 'icons' -> Icon system with iconStyle, icon paths, and categorization - 'walkthroughs' -> Interactive step-by-step guides through diagrams - 'contexts' -> Multiple context views with roots, extends inheritance - 'imports' -> Namespace management with from/namespace properties, component reuse - 'markdown' -> Rich text support in descriptions, notes, and diagram text - 'tutorial' -> Complete tutorial for learning Ilograph diagram creation Returns: str: Clean markdown content with detailed explanations, examples, and best practices """ # Validate and normalize section parameter if not section or not isinstance(section, str): error_msg = "Section parameter is required and must be a non-empty string" await ctx.error(error_msg) return f"Error: {error_msg}" section = section.strip().lower() # Get fetcher instance fetcher = get_fetcher() supported_sections = fetcher.get_supported_documentation_sections() # Validate section name if section not in supported_sections: available_sections = ", ".join(sorted(supported_sections.keys())) error_msg = f"Unsupported section '{section}'. Available sections: {available_sections}" await ctx.error(error_msg) return f"Error: {error_msg}" try: # Log the request await ctx.info(f"Fetching Ilograph documentation for section: {section}") # Fetch documentation content content = await fetcher.fetch_documentation_section(section) if content is None: error_msg = f"Failed to fetch documentation for section '{section}'. The content may be temporarily unavailable." await ctx.error(error_msg) return f"Error: {error_msg}" # Add metadata header to the content section_description = supported_sections[section] content_with_header = f"""# Ilograph Documentation: {section.replace('-', ' ').title()} **Section:** {section} **Description:** {section_description} **Source:** https://www.ilograph.com/docs/editing/{section.replace('-', '/')}/ **Last Updated:** Fetched on demand from official Ilograph documentation --- {content} --- *This documentation was fetched from the official Ilograph website and converted to markdown format for easy consumption. For the most up-to-date information, visit the official documentation at https://www.ilograph.com/docs/* """ await ctx.info( f"Successfully fetched documentation for section '{section}' ({len(content)} characters)" ) return content_with_header except Exception as e: error_msg = f"Unexpected error fetching documentation for section '{section}': {str(e)}" await ctx.error(error_msg) return f"Error: An unexpected error occurred while fetching the documentation. Please try again later." - Related companion tool 'list_documentation_sections' - lists all available documentation sections with descriptions, registered alongside fetch_documentation_tool in the same registration function.
@mcp.tool( annotations={ "title": "List Available Documentation Sections", "readOnlyHint": True, "description": "Lists all available Ilograph documentation sections with descriptions", } ) async def list_documentation_sections(ctx: Context) -> str: """ Lists all available Ilograph documentation sections with descriptions. This tool provides an overview of all available documentation sections that can be fetched using the fetch_documentation_tool. Returns: str: Formatted list of available documentation sections with descriptions """ try: await ctx.info("Listing available Ilograph documentation sections") fetcher = get_fetcher() supported_sections = fetcher.get_supported_documentation_sections() # Format the sections list sections_md = "# Available Ilograph Documentation Sections\n\n" sections_md += "The following documentation sections are available for fetching:\n\n" for section, description in sorted(supported_sections.items()): url = f"https://www.ilograph.com/docs/editing/{section.replace('-', '/')}/" sections_md += f"## {section}\n" sections_md += f"**Description:** {description} \n" sections_md += f"**URL:** {url} \n" sections_md += f"**Usage:** Use `fetch_documentation_tool(section='{section}')` to fetch this content\n\n" sections_md += "---\n\n" sections_md += "*To fetch any of these sections, use the `fetch_documentation_tool` with the section name as the parameter.*" await ctx.info(f"Listed {len(supported_sections)} available documentation sections") return sections_md except Exception as e: error_msg = f"Error listing documentation sections: {str(e)}" await ctx.error(error_msg) return f"Error: {error_msg}" - Related companion tool 'check_documentation_health' - checks health/connectivity of the documentation fetching service, registered alongside fetch_documentation_tool.
@mcp.tool( annotations={ "title": "Check Documentation Service Health", "readOnlyHint": True, "description": "Checks the health and connectivity of the documentation fetching service", } ) async def check_documentation_health(ctx: Context) -> str: """ Checks the health and connectivity of the documentation fetching service. This tool performs connectivity tests and returns status information about the documentation fetching capabilities, including cache statistics. Returns: str: Health status report with service connectivity and cache information """ try: await ctx.info("Performing documentation service health check") fetcher = get_fetcher() health_info = await fetcher.health_check() # Format health report health_md = "# Documentation Service Health Report\n\n" health_md += f"**Overall Status:** {health_info['status'].upper()}\n\n" # Service status health_md += "## Service Connectivity\n\n" for service, info in health_info["services"].items(): status_emoji = "✅" if info["status"] == "healthy" else "❌" health_md += f"{status_emoji} **{service.title()}**: {info['status'].upper()}\n" health_md += f" - URL: {info['url']}\n" if "error" in info: health_md += f" - Error: {info['error']}\n" health_md += "\n" # Cache statistics cache_stats = health_info["cache_stats"] health_md += "## Cache Statistics\n\n" health_md += f"- **Total Entries:** {cache_stats['total_entries']}\n" health_md += f"- **Valid Entries:** {cache_stats['valid_entries']}\n" health_md += f"- **Expired Entries:** {cache_stats['expired_entries']}\n" if cache_stats["keys"]: health_md += f"- **Cached Keys:** {', '.join(cache_stats['keys'])}\n" health_md += "\n---\n\n" if health_info["status"] == "healthy": health_md += "*All services are operational and ready to fetch documentation.*" elif health_info["status"] == "degraded": unhealthy = health_info.get("unhealthy_services", []) health_md += f"*Some services are experiencing issues: {', '.join(unhealthy)}. Documentation fetching may be limited.*" await ctx.info(f"Health check completed - Status: {health_info['status']}") return health_md except Exception as e: error_msg = f"Error performing health check: {str(e)}" await ctx.error(error_msg) return f"Error: {error_msg}" - The @mcp.tool decorator with annotations providing the tool schema - includes title 'Fetch Ilograph Documentation', readOnlyHint, and a description for the fetch_documentation_tool.
@mcp.tool( annotations={ "title": "Fetch Ilograph Documentation", "readOnlyHint": True, "description": "Fetches narrative documentation from ilograph.com with explanations and examples", } ) - src/ilograph_mcp/server.py:16-16 (registration)Import of register_fetch_documentation_tool from the registration module.
from ilograph_mcp.tools.register_fetch_documentation_tools import register_fetch_documentation_tool - src/ilograph_mcp/server.py:61-62 (registration)Registration call where register_fetch_documentation_tool(mcp) is invoked in create_server() to register the tool with the FastMCP server.
register_fetch_documentation_tool(mcp) logger.info("Registered fetch_documentation_tool") - IlographContentFetcher.fetch_documentation_section - the underlying helper that fetches documentation HTML via HTTP client, converts to markdown, and caches the result.
async def fetch_documentation_section(self, section: str) -> Optional[str]: """ Fetch and convert documentation section to markdown with caching. Args: section: Documentation section name (e.g., 'resources', 'relation-perspectives') Returns: Markdown content or None if unavailable """ cache_key = f"docs_{section}" # Check cache first cached_content = self.cache.get(cache_key) if cached_content is not None: logger.debug(f"Returning cached documentation for section: {section}") return str(cached_content) try: logger.info(f"Fetching documentation section: {section}") # Fetch HTML content html_content = await self.http_client.fetch_documentation_html(section) if html_content is None: logger.error(f"Failed to fetch HTML for section: {section}") return None # Get source URL for link resolution source_url = self.http_client.get_documentation_url(section) # Convert to markdown markdown_content = self.markdown_converter.convert_html_to_markdown( html_content, source_url ) # Cache the result self.cache.set(cache_key, markdown_content, self.cache_ttl["documentation"]) logger.info(f"Successfully processed documentation for section: {section}") return markdown_content except Exception as e: logger.error(f"Error fetching documentation section '{section}': {e}") return None - IlographContentFetcher.get_supported_documentation_sections - returns the dict of all 14 supported documentation sections with descriptions, used by the tool for validation.
def get_supported_documentation_sections(self) -> Dict[str, str]: """ Get the list of supported documentation sections with descriptions. Returns: Dictionary mapping section names to descriptions """ return { "resources": "Resource tree organization, hierarchies, instanceOf patterns, abstract resources", "relation-perspectives": "Arrow connections, from/to properties, routing, labels, directions", "sequence-perspectives": "Time-based diagrams with steps, bidirectional flows, async operations", "references": "Resource reference patterns and advanced referencing techniques", "advanced-references": "Complex reference scenarios and advanced usage patterns", "resource-sizes-and-positions": "Layout control, resource sizing, visual hierarchy management", "parent-overrides": "Resource parent overrides in perspectives with scale properties", "perspectives-other-properties": "Additional perspective properties and configuration options", "icons": "Icon system with iconStyle, icon paths, and categorization", "walkthroughs": "Interactive step-by-step guides through diagrams", "contexts": "Multiple context views with roots, extends inheritance, context switching", "imports": "Namespace management with from/namespace properties, component reuse", "markdown": "Rich text support in descriptions, notes, and diagram text", "tutorial": "Complete tutorial for learning Ilograph diagram creation", } - get_fetcher() global singleton accessor used by the tool to obtain the fetcher instance.
def get_fetcher() -> IlographContentFetcher: """Get the global fetcher instance.""" return fetcher - IlographHTTPClient.fetch_documentation_html - fetches raw HTML for a documentation section via HTTP, called by the fetcher helper.
async def fetch_documentation_html(self, section: str) -> Optional[str]: """ Fetch HTML content for a documentation section. Args: section: Documentation section name Returns: HTML content as string if successful, None otherwise """ url = self.get_documentation_url(section) response = await self.fetch_with_retry(url) if response is None: return None try: return response.text except Exception as e: logger.error(f"Error reading response text from {url}: {e}") return None - IlographMarkdownConverter.convert_html_to_markdown - converts HTML documentation to clean markdown format for LLM consumption.
def convert_html_to_markdown(self, html: str, source_url: Optional[str] = None) -> str: """ Convert HTML content to clean markdown format. Args: html: HTML content to convert source_url: Source URL for link resolution Returns: Clean markdown content optimized for LLM consumption """ try: # Parse HTML soup = BeautifulSoup(html, "lxml") # Update base URL if source URL provided if source_url: self.base_url = source_url # Remove unwanted elements self.remove_unwanted_elements(soup) # Find main content main_content = self.find_main_content(soup) if main_content is None: logger.warning("No main content found, using entire document") # Use body as fallback, or create a wrapper body = soup.find("body") if isinstance(body, Tag): main_content = body else: # Create a temporary wrapper tag for processing main_content = soup.new_tag("div") # Move all body content into our wrapper for child in list(soup.children): if hasattr(child, "extract"): child.extract() main_content.append(child) # Resolve relative links self.resolve_links(main_content) # Process content structure self.convert_headers(main_content) self.process_lists(main_content) self.format_tables(main_content) # Extract and preserve code blocks code_blocks = self.extract_code_blocks(main_content) # Get clean text content_text = main_content.get_text() # Clean and format markdown_content = self.clean_and_format_text(content_text) # Add code blocks back if they were found if code_blocks: markdown_content += "\n\n## Code Examples\n\n" for language, code in code_blocks: markdown_content += f"```{language}\n{code}\n```\n\n" logger.info( f"Successfully converted HTML to markdown ({len(markdown_content)} characters)" ) return markdown_content except Exception as e: logger.error(f"Error converting HTML to markdown: {e}") # Return a safe fallback try: soup = BeautifulSoup(html, "lxml") return self.clean_and_format_text(soup.get_text()) except: return "Error: Unable to process HTML content"