Skip to main content
Glama

VTK API Validation via MCP

Post-generation validation of VTK Python code using Model Context Protocol (MCP).

Overview

This module provides automatic validation of generated VTK code to catch API hallucinations:

  • ✅ Direct API lookups - No vector search overhead, exact class/method verification

  • ✅ Method existence validation - Detects when LLM invents non-existent methods

  • ✅ Import validation - Verifies VTK classes are imported from correct modules

  • ✅ Fast in-memory index - Loads ~2,900 VTK classes at startup

  • ✅ Structured error reporting - Clear error messages with suggestions


Related MCP server: mcp-server-analyzer

Quick Start

1. Install the Package

From PyPI (recommended once published):

pip install vtkapi-mcp

For local development we standardize on uv to manage the virtualenv and extras:

uv venv .venv
source .venv/bin/activate
uv sync --extra dev      # runtime + pytest + ruff

Note: The 64 MB data/vtk-python-docs.jsonl file is required at runtime but is not bundled in the wheel. Place it under data/ (or pass --api-docs /path/to/file) before launching the MCP server.

Prefer automation? ./setup.sh now wraps the same uv workflow and accepts --dev to include the testing toolchain.

2. Test MCP Integration (Optional)

uv run python demo_mcp_integration.py

This runs a complete demo showing how to use vtkapi-mcp as an MCP server (not as standalone Python library). It demonstrates all 18 MCP tools and error detection.

3. Developer Workflow (uv-native)

Task

Command

Run unit + integration tests

uv run pytest

Run tests with coverage report

uv run pytest --cov=vtkapi_mcp --cov-report=term-missing

Run Ruff lint & format checks

uv run ruff check / uv run ruff format --check

These commands automatically reuse the .venv created via uv venv / uv sync. No manual activation is required.

3. Configure MCP Client

Add to your MCP settings (e.g., Claude Desktop config):

{
  "mcpServers": {
    "vtk-api": {
      "command": "python",
      "args": [
        "-m",
        "vtkapi_mcp",
        "--api-docs",
        "/absolute/path/to/vtkapi-mcp/data/vtk-python-docs.jsonl"
      ]
    }
  }
}

4. Use VTK Tools

The MCP server provides 18 tools for VTK API validation and lookup. See MCP Tools below.


Project Structure

Package Organization

vtkapi_mcp/
├── core/              # API indexing and data loading
│   └── api_index.py
├── validation/        # Code validation logic
│   ├── models.py
│   ├── validator.py
│   ├── import_validator.py
│   ├── class_validator.py
│   └── method_validator.py
├── server/           # MCP server implementation
│   ├── mcp_server.py
│   └── tools.py
└── utils/            # Utilities for parsing and search
    ├── extraction.py
    └── search.py

Supporting Files

File

Purpose

demo_mcp_integration.py

Demo showing proper MCP integration (not standalone)

pyproject.toml

Python package configuration and dependencies

README.md

This file

Data

File

Purpose

Size

data/vtk-python-docs.jsonl

VTK API documentation (~2,900 classes)

~64 MB


Architecture

VTKAPIIndex (vtkapi_mcp/core/api_index.py)

Fast in-memory index of all VTK classes and methods:

VTKAPIIndex
├── Classes Dict: {class_name → {module, methods, docs}}
├── Modules Dict: {module_name → [class_names]}
└── Load Time: <1 second for ~2,900 classes

Key Methods:

  • get_class_info(class_name) - Get module and documentation

  • search_classes(query) - Search by name or keyword

  • get_module_classes(module) - List classes in module

  • class_exists(class_name) - Check if class exists

VTKCodeValidator (vtkapi_mcp/validation/validator.py)

AST-based validation of generated Python code:

VTKCodeValidator
├── Parse Code: Uses Python's ast module
├── Extract VTK Usage:
│   ├── Import statements
│   ├── Class instantiations
│   └── Method calls
├── Validate Against Index:
│   ├── Check classes exist
│   ├── Check imports correct
│   └── Check methods exist
└── Generate Error Report

Validation Types:

  1. Import Validation - Verifies module paths

  2. Class Validation - Checks class existence

  3. Method Validation - Detects hallucinated methods


MCP Tools Provided

When running as MCP server, provides these 18 tools:

1. vtk_get_class_info

Get complete information about a VTK class.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "module": "vtkmodules.vtkRenderingCore",
  "content_preview": "vtkPolyDataMapper - map vtkPolyData to graphics primitives..."
}

2. vtk_search_classes

Search for VTK classes by name or keyword.

Input:

{
  "query": "reader",
  "limit": 5
}

Output:

[
  {
    "class_name": "vtkSTLReader",
    "module": "vtkmodules.vtkIOGeometry",
    "description": "Read ASCII or binary stereo lithography files."
  }
]

5. vtk_validate_import

Validate and correct VTK import statements.

Input:

{
  "import_statement": "from vtkmodules.vtkCommonDataModel import vtkPolyDataMapper"
}

Output:

{
  "valid": false,
  "message": "Incorrect module. 'vtkPolyDataMapper' is in 'vtkmodules.vtkRenderingCore'",
  "suggested": "from vtkmodules.vtkRenderingCore import vtkPolyDataMapper"
}

6. vtk_get_method_info

Get full information about a specific method including section context.

Input:

{
  "class_name": "vtkPolyDataMapper",
  "method_name": "SetInputData"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "method_name": "SetInputData",
  "content": "SetInputData(vtkDataObject) - Set the input data...",
  "section": "Methods defined here"
}

7. vtk_get_method_doc

Get just the docstring for a specific method.

Input:

{
  "class_name": "vtkPolyDataMapper",
  "method_name": "SetInputData"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "method_name": "SetInputData",
  "docstring": "SetInputData(vtkDataObject) - Set the input data...",
  "found": true
}

8. vtk_get_class_doc

Get the class documentation string.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "class_doc": "vtkPolyDataMapper - map vtkPolyData to graphics primitives. Superclass: vtkMapper",
  "found": true
}

9. vtk_get_class_synopsis

Get a brief synopsis/summary of what a class does.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "synopsis": "Maps polygonal data (vtkPolyData) to graphics primitives for rendering.",
  "found": true
}

10. vtk_get_class_action_phrase

Get the action phrase describing what a class does.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "action_phrase": "polygon mapping",
  "found": true
}

11. vtk_get_class_role

Get the functional role/category of a class.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "role": "rendering",
  "found": true
}

12. vtk_get_class_visibility

Get the visibility/exposure level of a class.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "visibility": "likely",
  "found": true
}

13. vtk_get_module_classes

List all classes in a specific module.

Input:

{
  "module": "vtkmodules.vtkRenderingCore"
}

Output:

{
  "module": "vtkmodules.vtkRenderingCore",
  "classes": ["vtkActor", "vtkPolyDataMapper", ...],
  "count": 42
}

14. vtk_get_class_module

Return the vtkmodules.* import path for a given VTK class.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "module": "vtkmodules.vtkRenderingCore",
  "found": true
}

15. vtk_get_class_input_datatype

Get the input data type for a VTK class.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "input_datatype": "vtkPolyData",
  "found": true
}

16. vtk_get_class_output_datatype

Get the output data type for a VTK class.

Input:

{
  "class_name": "vtkContourFilter"
}

Output:

{
  "class_name": "vtkContourFilter",
  "output_datatype": "vtkPolyData",
  "found": true
}

17. vtk_get_class_semantic_methods

Get semantically tagged methods for a VTK class (input setters, output getters, configuration methods).

Input:

{
  "class_name": "vtkContourFilter"
}

Output:

{
  "class_name": "vtkContourFilter",
  "semantic_methods": {
    "input_setters": ["SetInputData", "SetInputConnection"],
    "output_getters": ["GetOutput", "GetOutputPort"],
    "configuration": ["SetValue", "SetNumberOfContours"]
  },
  "found": true
}

18. vtk_is_a_class

Check if a given name is a valid VTK class.

Input:

{
  "class_name": "vtkPolyDataMapper"
}

Output:

{
  "class_name": "vtkPolyDataMapper",
  "is_vtk_class": true
}

Benefits Over RAG Retrieval

Aspect

RAG Retrieval

MCP Validation

Speed

Vector search + reranking

Direct hash lookup (instant)

Accuracy

Semantic similarity (can drift)

Exact API match (100%)

Coverage

Top-K only (~10 results)

All ~2,900 classes available

Tokens

Consumes prompt tokens

Tool calls (minimal cost)

Errors

Silent hallucinations

Explicit error messages


Validation Examples

Example 1: Method Hallucination (CAUGHT ✅)

Generated Code:

stencil = vtkImageStencilToImage()
stencil.SetOutputWholeExtent([0, 10, 0, 10, 0, 10])  # ❌ Doesn't exist!

Validation Error:

UNKNOWN_METHOD: Method 'SetOutputWholeExtent' not found on class 'vtkImageStencilToImage'
Suggestion: Did you mean SetOutputOrigin or SetOutputSpacing?

Example 2: Wrong Import Module (CAUGHT ✅)

Generated Code:

from vtkmodules.vtkCommonDataModel import vtkPolyDataMapper  # ❌ Wrong module!

Validation Error:

IMPORT_ERROR: 'vtkPolyDataMapper' is not in module 'vtkmodules.vtkCommonDataModel'
Correct import: from vtkmodules.vtkRenderingCore import vtkPolyDataMapper

Example 3: Non-existent Class (CAUGHT ✅)

Generated Code:

converter = vtkImageDataToPolyDataConverter()  # ❌ Class doesn't exist!

Validation Error:

UNKNOWN_CLASS: Class 'vtkImageDataToPolyDataConverter' not found in VTK
Suggestion: Did you mean vtkImageDataGeometryFilter?

Data Source

Input: data/vtk-python-docs.jsonl

Each line is a VTK class documentation in JSON format:

{
  "class_name": "vtkPolyDataMapper",
  "module_name": "vtkmodules.vtkRenderingCore",
  "class_doc": "vtkPolyDataMapper - map vtkPolyData to graphics primitives. Superclass: vtkMapper",
  "synopsis": "Maps polygonal data (vtkPolyData) to graphics primitives for rendering.",
  "action_phrase": "polygon mapping",
  "role": "rendering",
  "visibility_score": "likely",
  "input_datatype": "vtkPolyData",
  "output_datatype": "",
  "semantic_methods": { "input_setters": [...], "output_getters": [...] },
  "structured_docs": { "sections": { ... } }
}

Coverage: ~2,900 VTK classes from VTK Python API


Future Enhancements

  • Method signature validation - Check parameter types and counts

  • Deprecation warnings - Flag deprecated VTK methods

  • Pipeline validation - Verify data flow compatibility

  • Auto-fix suggestions - Generate corrected code automatically

  • Performance profiling - Track validation overhead

  • Cache layer - Cache frequent lookups for speed


License

This is a standalone MCP server for VTK API validation. Extracted from the vtk-rag project.


Status: Production ready MCP server for VTK API validation.

Available Tools

18 tools
vtk_get_class_action_phraseB

Get the action phrase describing what a VTK class does (e.g., 'data reading', 'mesh filtering')

Inputs: class_name (required).

vtk_get_class_docB

Get the class documentation string for a VTK class

Inputs: class_name (required).

vtk_get_class_infoB

Get complete information about a VTK class including module path, description, and methods

Inputs: class_name (required).

vtk_get_class_input_datatypeA

Get the input data type for a VTK class (e.g., 'vtkPolyData', 'vtkImageData')

Inputs: class_name (required).

vtk_get_class_methodsA

List all methods (with signatures) for a VTK class and optionally verify a specific method

Inputs: class_name (required), method_name.

vtk_get_class_moduleA

Return the vtkmodules.* import path for a given VTK class

Inputs: class_name (required).

vtk_get_class_output_datatypeA

Get the output data type for a VTK class (e.g., 'vtkPolyData', 'vtkImageData')

Inputs: class_name (required).

vtk_get_class_roleA

Get the pipeline role of a VTK class. Returns one of: input, filter, properties, renderer, scene, infrastructure, output, utility, color

Inputs: class_name (required).

vtk_get_class_semantic_methodsA

Get non-boilerplate callable methods for a VTK class. Excludes dunder methods, private methods, and VTK infrastructure methods.

Inputs: class_name (required).

vtk_get_class_synopsisA

Get a brief synopsis/summary of what a VTK class does

Inputs: class_name (required).

vtk_get_class_visibilityA

Get the visibility score of a VTK class (0.0-1.0). Higher scores indicate classes more likely to be used directly.

Inputs: class_name (required).

vtk_get_method_docA

Get just the docstring for a specific method of a VTK class

Inputs: class_name (required), method_name (required).

vtk_get_method_infoB

Get documentation for a specific method of a VTK class

Inputs: class_name (required), method_name (required).

vtk_get_method_signatureA

Return only the canonical signature for a specific method of a VTK class (minimal payload)

Inputs: class_name (required), method_name (required).

vtk_get_module_classesC

List all VTK classes in a specific module

Inputs: module (required).

vtk_is_a_classA

Check if a given name is a valid VTK class. Returns true if it exists in the VTK API, false otherwise.

Inputs: class_name (required).

vtk_search_classesC

Search for VTK classes by name or keyword

Inputs: query (required), limit.

vtk_validate_importC

Validate if a VTK import statement is correct and suggest corrections

Inputs: import_statement (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

    TDQS

    A3.8/5.0

    Scored across 18 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose, querying different aspects of VTK classes (e.g., action phrase, doc, methods, module). Overlaps are minimal and well-defined (e.g., three method-query tools differentiate by payload: doc only, doc+signature, signature only).

    Naming Consistency5/5

    All tools follow a consistent snake_case pattern with 'vtk_' prefix, verb (mostly 'get', plus 'is_a', 'search', 'validate'), and specific resource. Naming is predictable and uniform.

    Tool Count5/5

    With 18 tools, the set is well-scoped for a reference API server that provides detailed class metadata. Each tool serves a clear need without clutter.

    Completeness5/5

    The tool surface covers all key aspects of VTK class information: identification, documentation, methods, module path, input/output types, role, visibility, search, import validation, and per-module listing. No obvious gaps for the stated purpose.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      An MCP server that exposes Pyright language server functionality for Python, providing tools for type checking, code completions, and finding definitions. It enables AI models to perform static analysis and code formatting through the Model Context Protocol.
      7
      34 PyPI
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      An MCP server that performs comprehensive Python code analysis using Ruff, ty, and Vulture for linting, type checking, and dead code detection.
      8
      121 PyPI
      11
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that fixes, validates, and generates visual text content for AI coding assistants.
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      An MCP server that validates generated code against project structure and installed dependencies, catching undefined symbols, wrong API calls, dead code, and type mismatches in real time. It provides tools for project indexing, symbol/API checking, sandboxed execution, file scanning, and code analysis.
      1
      MIT