ansys-workbench-cpython-mcp-server

cth1975/ansys-workbench-cpython-mcp-server

3.1

If you are the rightful owner of ansys-workbench-cpython-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

A comprehensive Model Context Protocol (MCP) server that provides AI models with specialized resources, examples, and tools for Ansys Workbench CPython scripting automation.

Tools
4
Resources
0
Prompts
0

Ansys Workbench CPython MCP Server

A comprehensive Model Context Protocol (MCP) server that provides AI models with specialized resources, examples, and tools for Ansys Workbench CPython scripting automation. This server showcases the advantages of modern CPython over the legacy IronPython system introduced in Ansys Workbench 2024.

🎯 Overview

This MCP server enables AI models to excel at Ansys Workbench automation by providing:

  • 📚 Curated Examples Collection - 5 comprehensive categories with production-ready CPython code
  • 🔍 Live Documentation Scraping - Real-time access to latest Ansys documentation
  • 📝 Specialized Prompt Templates - Pre-built templates for common automation tasks
  • 🛡️ Security Controls - Domain validation, input sanitization, and timeout handling
  • 🚀 CPython Features - Modern Python capabilities not available in IronPython

🏗️ Architecture

MCP Protocol Integration

AI Model ←→ MCP Client ←→ MCP Server ←→ Ansys Documentation
                ↓                ↓
            Resources         Tools & Examples

Core Components

  1. Resource Providers

    • ansys://examples/{category} - Curated code examples
    • ansys://documentation/{topic} - Live documentation access
    • ansys://prompts/{task_type} - Specialized prompt templates
  2. Tools

    • scrape_ansys_documentation - Extract content from Ansys websites
    • search_ansys_cpython_examples - Intelligent example search
    • generate_ansys_script_template - Custom script generation
    • get_ansys_cpython_best_practices - Expert guidance and tips
  3. Security Layer

    • Domain allowlist for safe web scraping
    • Input validation and sanitization
    • Content length limits and timeout handling

🚀 Quick Start

Prerequisites

  • Python 3.11+
  • Required packages: mcp, requests, trafilatura

Installation

  1. Clone the repository:

    git clone https://github.com/cth1975/ansys-workbench-cpython-mcp-server.git
    cd ansys-workbench-cpython-mcp-server
    
  2. Install dependencies:

    pip install mcp requests trafilatura
    
  3. Run the server:

    python ansys_mcp_server.py
    

Connect with AI Models

The server can be used with any MCP-compatible AI client:

  • Claude Desktop - Add to your MCP configuration
  • Custom MCP Clients - Connect via stdin/stdout transport
  • AI Development Tools - Integrate with your workflow

📚 Example Categories

1. Geometry Creation

Advanced parametric geometry with modern Python features:

import ansys.workbench.core as wb
import numpy as np
from pathlib import Path

# Create parametric geometry with numpy arrays
dimensions = np.array([100.0, 50.0, 25.0])
geometry = project.create_parametric_model(dimensions)

2. Mesh Generation

Quality-controlled meshing with adaptive refinement:

import numpy as np

# Configure mesh controls with numpy
refinement_areas = np.array([
    {'face': 'Face1', 'size': 2.0},
    {'face': 'Face2', 'size': 1.5}
])

for area in refinement_areas:
    mesh.add_sizing_control(area['face'], area['size'])

3. Solver Automation

Parameter sweeps with progress monitoring:

import pandas as pd
from concurrent.futures import ThreadPoolExecutor

# Run parametric study with pandas DataFrames
results_df = pd.DataFrame()
with ThreadPoolExecutor() as executor:
    futures = {executor.submit(run_analysis, params): params 
               for params in parameter_sets}

4. Post-Processing

Advanced visualization with matplotlib and pandas:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

# Create comprehensive analysis dashboard
results_df = extract_results()
correlation_matrix = results_df.corr()
sns.heatmap(correlation_matrix, annot=True)

5. Enterprise Automation

Batch processing with parallel execution:

from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import logging

# Enterprise-grade batch processing
with ProcessPoolExecutor(max_workers=4) as executor:
    futures = {executor.submit(process_project, proj): proj 
               for proj in project_files}

🔧 API Reference

Resources

Get Examples
Resource: ansys://examples/{category}
Categories: geometry, meshing, solving, post-processing, automation
Returns: Formatted examples with code, descriptions, and CPython features
Get Documentation
Resource: ansys://documentation/{topic}
Topics: geometry, mesh, solver, post-processing, automation
Returns: Live documentation with examples and source links
Get Prompt Templates
Resource: ansys://prompts/{task_type}
Task Types: geometry-creation, mesh-generation, solver-setup, post-analysis
Returns: Specialized prompt templates with variables and instructions

Tools

Scrape Documentation
result = await client.call_tool(
    "scrape_ansys_documentation",
    {
        "url": "https://ansyshelp.ansys.com/...",
        "topic": "geometry"
    }
)
Search Examples
results = await client.call_tool(
    "search_ansys_cpython_examples",
    {"query": "parametric geometry creation"}
)
Generate Script Template
template = await client.call_tool(
    "generate_ansys_script_template",
    {
        "task": "parametric_study",
        "parameters": {"param1": [1, 2, 3]}
    }
)

🔒 Security Features

Domain Allowlist

Only trusted Ansys domains are accessible:

  • ansys.com
  • ansyshelp.ansys.com
  • pyansys.com
  • apdl.docs.pyansys.com
  • mapdl.docs.pyansys.com
  • fluent.docs.pyansys.com
  • mechanical.docs.pyansys.com

Input Validation

  • String length limits (100 chars for queries, 200 for URLs)
  • Character sanitization (removes <>"\\)
  • URL validation with proper parsing

Content Protection

  • Maximum content length: 50,000 characters
  • Request timeout: 10 seconds
  • Automatic content truncation with warnings

💡 CPython Advantages

This server showcases modern Python features unavailable in IronPython:

Advanced Libraries

  • NumPy - Numerical computing with arrays
  • Pandas - Data analysis and manipulation
  • Matplotlib - Advanced plotting and visualization
  • Concurrent.futures - Parallel processing capabilities

Modern Python Features

  • Type hints for better code quality
  • F-strings for readable formatting
  • Pathlib for cross-platform file handling
  • Context managers for resource cleanup
  • Async/await for concurrent operations

Development Tools

  • Full standard library access
  • Virtual environments support
  • Third-party packages from PyPI
  • Modern debugging tools and profilers

🛠️ Configuration

Customizing Security Settings

Modify these constants in ansys_mcp_server.py:

ALLOWED_DOMAINS = [
    'ansys.com',
    'your-custom-domain.com'  # Add your domains
]

REQUEST_TIMEOUT = 15  # Increase timeout if needed
MAX_CONTENT_LENGTH = 75000  # Adjust content limits

Adding Custom Examples

Extend the load_examples_for_category function:

def load_examples_for_category(category: str) -> Dict[str, Any]:
    examples = {
        'your_category': {
            'description': 'Your custom examples',
            'examples': [
                {
                    'title': 'Your Example',
                    'code': 'your_python_code_here',
                    'description': 'What this example does',
                    'complexity': 'basic',
                    'cpython_features': ['feature1', 'feature2']
                }
            ]
        }
    }
    return examples.get(category, default_response)

🧪 Testing

MCP Client Testing

import asyncio
from mcp import Client, StdioServerTransport

async def test_mcp_server():
    # Connect to MCP server
    transport = StdioServerTransport("python", ["ansys_mcp_server.py"])
    
    async with Client(transport) as client:
        # Test resource access
        resources = await client.list_resources()
        print(f"Available resources: {len(resources)}")
        
        # Test geometry examples
        geometry = await client.read_resource("ansys://examples/geometry")
        assert 'CPython' in geometry.contents[0].text
        
        # Test documentation scraping tool
        scrape_result = await client.call_tool(
            "scrape_ansys_documentation",
            {"url": "https://ansyshelp.ansys.com/", "topic": "general"}
        )
        assert scrape_result is not None

asyncio.run(test_mcp_server())

🚀 Deployment

Local Development

python ansys_mcp_server.py

Docker Deployment

FROM python:3.11-slim

# Install required dependencies directly
RUN pip install mcp requests trafilatura

COPY ansys_mcp_server.py .
CMD ["python", "ansys_mcp_server.py"]

Cloud Deployment

The server can be deployed on any cloud platform that supports Python:

  • Replit - Direct execution with workflow configuration
  • AWS Lambda - Serverless MCP server
  • Google Cloud Run - Containerized deployment
  • Azure Functions - Event-driven execution

🤝 Contributing

Adding New Examples

  1. Follow the existing code structure
  2. Include comprehensive docstrings
  3. Showcase CPython-specific features
  4. Add complexity ratings and feature tags

Improving Documentation Scraping

  1. Add new allowed domains to ALLOWED_DOMAINS
  2. Enhance keyword extraction in extract_keywords
  3. Improve content categorization logic

Security Enhancements

  1. Test input validation thoroughly
  2. Monitor for new security vulnerabilities
  3. Update dependency versions regularly

📋 Troubleshooting

Common Issues

Server won't start:

# Check Python version
python --version  # Should be 3.11+

# Install missing dependencies
pip install mcp requests trafilatura

Scraping fails:

# Check domain allowlist - must be exact match from:
# ansys.com, ansyshelp.ansys.com, pyansys.com
# apdl.docs.pyansys.com, mapdl.docs.pyansys.com
# fluent.docs.pyansys.com, mechanical.docs.pyansys.com
# Check internet connectivity

Examples not loading:

# Verify examples are properly formatted
# Check for syntax errors in example code
# Ensure all required categories are implemented

Performance Optimization

Large content handling:

  • Increase MAX_CONTENT_LENGTH if needed
  • Implement content caching for frequently accessed resources
  • Use async processing for multiple scraping operations

Memory management:

  • Clear cached content periodically
  • Limit number of concurrent scraping operations
  • Monitor memory usage in production

📄 License

This project is open source and available under the .

🔗 Related Resources

👥 Support

For questions, issues, or contributions:

  • GitHub Issues - Report bugs and request features
  • Discussions - Community Q&A and examples sharing
  • Documentation - Comprehensive guides and API reference

Built with ❤️ for the Ansys automation community

This MCP server demonstrates the power of modern CPython for Ansys Workbench automation, providing AI models with comprehensive resources and examples for advanced engineering workflows.