Python API

Complete Python SDK for webMCP. Perfect for data science, automation, and server-side AI optimization.

Installation

Install the Python SDK via pip

Core Library

pip install webmcp-core

CLI Tools (Optional)

pip install webmcp-cli

Requirements

Python 3.8+, with support for Pydantic, asyncio, and type hints

Code Examples

Learn the Python API with practical examples

Basic Usage

Simple HTML to webMCP conversion in Python

from webmcp_core import WebMCPProcessor, OptimizationOptions

processor = WebMCPProcessor()
html_content = """
<form>
    <input name="email" type="email" />
    <button type="submit">Login</button>
</form>
"""

webmcp_data = processor.parse_webmcp(html_content)
print(webmcp_data.elements)

AI Optimization

Optimize for specific AI models with comprehensive options

options = OptimizationOptions(
    target_model='gpt-4o',
    compression_level='advanced',
    goal_description='User login with email and password'
)

optimized = processor.optimize_for_ai(
    webmcp_data.elements, 
    options
)

# Results in 67.6% token reduction
print(f"Token savings: {optimized.token_reduction}")
print(f"Cost savings: ${optimized.cost_savings:.4f }")

Security Configuration

Enable advanced security features

from webmcp_core import SecurityConfig, JWTConfig

security_config = SecurityConfig(
    enable_csrf=True,
    encryption='jwe',
    jwt_config=JWTConfig(
        secret=os.getenv('JWT_SECRET'),
        expires_in=3600,  # 1 hour
        scopes=['auth:login', 'user:read']
    )
)

secure_processor = WebMCPProcessor(security=security_config)
secure_data = secure_processor.parse_webmcp(html_content)

Async Processing

Process multiple forms concurrently

import asyncio
from webmcp_core import AsyncWebMCPProcessor

async def process_forms(html_forms):
    async_processor = AsyncWebMCPProcessor()
    
    tasks = [
        async_processor.parse_webmcp_async(html)
        for html in html_forms
    ]
    
    results = await asyncio.gather(*tasks)
    return results

# Process multiple forms efficiently
html_forms = [login_form, signup_form, contact_form]
results = asyncio.run(process_forms(html_forms))

Classes & Methods

Complete reference for all Python classes and methods

WebMCPProcessor

Main processor class for webMCP operations

Methods:

parse_webmcp(html: str, options: ParseOptions = None)WebMCPData

Parse HTML content and convert to webMCP format

optimize_for_ai(elements: List[WebMCPElement], options: OptimizationOptions)OptimizedResult

Optimize webMCP elements for AI consumption

validate_schema(data: WebMCPData)ValidationResult

Validate webMCP data against schema

calculate_tokens(data: WebMCPData, model: str)TokenCalculation

Calculate token count for specific AI model

OptimizationOptions

Configuration options for AI optimization

Attributes:

target_modelstr

Target AI model (gpt-4o, claude-3.5-sonnet, etc.)

compression_levelstr

Compression level: basic, standard, advanced

goal_descriptionstr

Description of the optimization goal

preserve_semanticsbool

Whether to preserve semantic meaning

WebMCPData

Parsed webMCP data structure

Attributes:

elementsList[WebMCPElement]

List of parsed webMCP elements

metadataDict

Additional metadata about the parsing

security_tokensDict

Security tokens and CSRF information

schema_versionstr

webMCP schema version used

Data Science Integration

Use webMCP with pandas, Jupyter, and other data science tools

Pandas Integration

Convert webMCP data to DataFrames for analysis

import pandas as pd
from webmcp_core import WebMCPProcessor

processor = WebMCPProcessor()
webmcp_data = processor.parse_webmcp(html_content)

# Convert to DataFrame for analysis
df = pd.DataFrame([
    {
        'element_type': elem.element_type,
        'role': elem.role,
        'name': elem.name,
        'token_count': len(elem.description.split())
    }
    for elem in webmcp_data.elements
])

print(df.groupby('element_type')['token_count'].sum())

Jupyter Notebook

Interactive webMCP analysis in Jupyter

# Cell 1: Setup
%pip install webmcp-core matplotlib seaborn
import webmcp_core as wcp
import matplotlib.pyplot as plt
import seaborn as sns

# Cell 2: Analysis
processor = wcp.WebMCPProcessor()
results = []

for html_file in html_files:
    data = processor.parse_webmcp(html_file)
    optimized = processor.optimize_for_ai(data.elements, options)
    results.append({
        'file': html_file,
        'original_tokens': optimized.original_tokens,
        'optimized_tokens': optimized.optimized_tokens,
        'reduction': optimized.token_reduction
    })

# Cell 3: Visualization
df = pd.DataFrame(results)
plt.figure(figsize=(10, 6))
sns.barplot(data=df, x='file', y='reduction')
plt.title('Token Reduction by File')
plt.xticks(rotation=45)
plt.show()

Ready to Automate?

Start building AI-optimized automation with the Python SDK