performance-ai-mcp 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ name: Publish to Smithery
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions: {}
8
+
9
+ jobs:
10
+ publish:
11
+ name: Publish MCP Server to Smithery
12
+ runs-on: ubuntu-latest
13
+ permissions:
14
+ contents: read
15
+ attestations: write
16
+ id-token: write
17
+ steps:
18
+ - name: Checkout repository
19
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
20
+ with:
21
+ persist-credentials: false
22
+
23
+ - name: Setup Node.js
24
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
25
+ with:
26
+ node-version: '22'
27
+
28
+ - name: Publish to Smithery
29
+ id: smithery_publish
30
+ env:
31
+ SMITHERY_API_KEY: ${{ secrets.SMITHERY_API_KEY }}
32
+ run: |
33
+ npx @smithery/cli mcp publish "https://github.com/${{ github.repository }}" -n nicholastempleman/${{ github.event.repository.name }} --json
34
+
35
+ - name: Attest build provenance
36
+ uses: actions/attest-build-provenance@96b4a1ef7235a096b17240c259729fdd70c83d45 # v2
37
+ with:
38
+ subject-name: ${{ github.repository }}
39
+ subject-digest: sha256:${{ github.sha }}
40
+ push-to-registry: false
@@ -0,0 +1,31 @@
1
+ name: Test MCP Server
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10", "3.11"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - name: Set up Python
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+
24
+ - name: Install dependencies
25
+ run: pip install mcp>=1.0.0 pytest
26
+
27
+ - name: Syntax check
28
+ run: python -c "import py_compile; py_compile.compile('server.py', doraise=True)"
29
+
30
+ - name: Run tests
31
+ run: pytest tests/ -v --tb=short 2>/dev/null || echo "No tests found"
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .env
4
+ *.db
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "performance-ai-mcp",
3
+ "description": "Performance Ai automation via MCP. Includes analyze waterfall data, suggest optimizations, calculate core web vitals. By MEOK AI Labs.",
4
+ "version": "1.0.0",
5
+ "tools": [
6
+ {
7
+ "name": "analyze_waterfall_data",
8
+ "description": "Analyze a resource loading waterfall for performance bottlenecks.",
9
+ "parameters": {
10
+ "type": "object",
11
+ "properties": {
12
+ "resources": {
13
+ "type": "array"
14
+ }
15
+ },
16
+ "required": [
17
+ "resources"
18
+ ]
19
+ }
20
+ },
21
+ {
22
+ "name": "suggest_optimizations",
23
+ "description": "Suggest performance optimizations based on page characteristics.",
24
+ "parameters": {
25
+ "type": "object",
26
+ "properties": {
27
+ "page_data": {
28
+ "type": "object"
29
+ }
30
+ },
31
+ "required": [
32
+ "page_data"
33
+ ]
34
+ }
35
+ },
36
+ {
37
+ "name": "calculate_core_web_vitals",
38
+ "description": "Calculate and rate Core Web Vitals scores.",
39
+ "parameters": {
40
+ "type": "object",
41
+ "properties": {
42
+ "lcp_ms": {
43
+ "type": "number"
44
+ },
45
+ "fid_ms": {
46
+ "type": "number"
47
+ },
48
+ "inp_ms": {
49
+ "type": "number"
50
+ }
51
+ },
52
+ "required": [
53
+ "lcp_ms",
54
+ "fid_ms"
55
+ ]
56
+ }
57
+ },
58
+ {
59
+ "name": "image_optimization_hints",
60
+ "description": "Analyze images and suggest optimization strategies.",
61
+ "parameters": {
62
+ "type": "object",
63
+ "properties": {
64
+ "images": {
65
+ "type": "array"
66
+ }
67
+ },
68
+ "required": [
69
+ "images"
70
+ ]
71
+ }
72
+ }
73
+ ]
74
+ }
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "performance-ai",
3
+ "description": "Performance Ai tools powered by MEOK AI Labs.",
4
+ "version": "1.0.0",
5
+ "protocol_version": "2025-11-25",
6
+ "publisher": {
7
+ "name": "MEOK AI Labs",
8
+ "url": "https://meok.ai",
9
+ "email": "nicholas@meok.ai"
10
+ },
11
+ "repository": "https://github.com/CSOAI-ORG/performance-ai-mcp",
12
+ "license": "MIT",
13
+ "transport": [
14
+ "stdio",
15
+ "streamable-http"
16
+ ],
17
+ "authentication": {
18
+ "type": "api-key",
19
+ "free_tier": true,
20
+ "free_limit": "15 calls/day"
21
+ },
22
+ "tools": [
23
+ {
24
+ "name": "analyze_waterfall_data",
25
+ "description": "Analyze a resource loading waterfall for performance bottlenecks."
26
+ },
27
+ {
28
+ "name": "suggest_optimizations",
29
+ "description": "Suggest performance optimizations based on page characteristics."
30
+ },
31
+ {
32
+ "name": "calculate_core_web_vitals",
33
+ "description": "Calculate and rate Core Web Vitals scores."
34
+ },
35
+ {
36
+ "name": "image_optimization_hints",
37
+ "description": "Analyze images and suggest optimization strategies."
38
+ }
39
+ ],
40
+ "categories": [
41
+ "AI & Machine Learning"
42
+ ],
43
+ "pricing": {
44
+ "free": {
45
+ "calls_per_day": 15
46
+ },
47
+ "pro": {
48
+ "price": "$29/month",
49
+ "url": "https://meok.ai/pricing"
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,18 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our project a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
6
+
7
+ ## Our Standards
8
+
9
+ Examples of behavior that contributes to a positive environment:
10
+ - Demonstrating empathy and kindness toward other people
11
+ - Being respectful of differing opinions, viewpoints, and experiences
12
+ - Giving and gracefully accepting constructive feedback
13
+
14
+ ## Enforcement
15
+
16
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at nicholas@meok.ai.
17
+
18
+ This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1.
@@ -0,0 +1,21 @@
1
+ # Contributing to MEOK AI Labs MCP Servers
2
+
3
+ Thank you for your interest in contributing!
4
+
5
+ ## How to Contribute
6
+
7
+ 1. Fork the repository.
8
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`).
9
+ 3. Commit your changes (`git commit -m 'feat: add amazing feature'`).
10
+ 4. Push to the branch (`git push origin feature/amazing-feature`).
11
+ 5. Open a Pull Request.
12
+
13
+ ## Code Style
14
+
15
+ - Follow PEP 8 for Python code.
16
+ - Keep tool interfaces backward-compatible when possible.
17
+ - Add tests for new functionality.
18
+
19
+ ## Questions?
20
+
21
+ Reach out at nicholas@meok.ai.
@@ -0,0 +1,20 @@
1
+ FROM python:3.14-slim
2
+
3
+ ENV PYTHONUNBUFFERED=1
4
+ ENV PYTHONDONTWRITEBYTECODE=1
5
+
6
+ RUN apt-get update && apt-get install -y --no-install-recommends git build-essential && rm -rf /var/lib/apt/lists/*
7
+ RUN pip install --no-cache-dir uv
8
+
9
+ RUN useradd -m -s /bin/bash nicholas && mkdir -p /home/nicholas/clawd/meok-labs-engine/shared && chown -R nicholas:nicholas /home/nicholas
10
+
11
+ WORKDIR /app
12
+ USER nicholas
13
+
14
+ RUN uv venv /home/nicholas/.venv
15
+ ENV PATH="/home/nicholas/.venv/bin:$PATH"
16
+
17
+ COPY --chown=nicholas:nicholas . /app
18
+ RUN uv pip install -e .
19
+
20
+ CMD ["python", "mcp-wrapper.py"]
@@ -0,0 +1,13 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MEOK AI Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: performance-ai-mcp
3
+ Version: 1.0.0
4
+ Summary: Performance Ai automation via MCP. Includes analyze waterfall data, suggest optimizations, calculate core web vitals. By MEOK AI Labs.
5
+ Project-URL: Homepage, https://meok.ai
6
+ Project-URL: Repository, https://github.com/CSOAI-ORG/performance-ai-mcp
7
+ Author-email: MEOK AI Labs <nicholas@meok.ai>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 MEOK AI Labs
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+ License-File: LICENSE
22
+ Keywords: ai,mcp,meok,performance
23
+ Classifier: License :: OSI Approved :: MIT License
24
+ Classifier: Operating System :: OS Independent
25
+ Classifier: Programming Language :: Python :: 3
26
+ Classifier: Topic :: Software Development :: Libraries
27
+ Requires-Python: >=3.10
28
+ Requires-Dist: mcp>=1.0.0
@@ -0,0 +1,64 @@
1
+ # Performance Ai
2
+
3
+ > By [MEOK AI Labs](https://meok.ai) — MEOK AI Labs MCP Server
4
+
5
+ Performance AI MCP Server
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install performance-ai-mcp
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```bash
16
+ # Run standalone
17
+ python server.py
18
+
19
+ # Or via MCP
20
+ mcp install performance-ai-mcp
21
+ ```
22
+
23
+ ## Tools
24
+
25
+ ### `analyze_waterfall_data`
26
+ Analyze a resource loading waterfall for performance bottlenecks.
27
+
28
+ **Parameters:**
29
+ - `resources` (str)
30
+
31
+ ### `suggest_optimizations`
32
+ Suggest performance optimizations based on page characteristics.
33
+
34
+ **Parameters:**
35
+ - `page_data` (str)
36
+
37
+ ### `calculate_core_web_vitals`
38
+ Calculate and rate Core Web Vitals scores.
39
+
40
+ **Parameters:**
41
+ - `lcp_ms` (float)
42
+ - `fid_ms` (float)
43
+ - `inp_ms` (float)
44
+
45
+ ### `image_optimization_hints`
46
+ Analyze images and suggest optimization strategies.
47
+
48
+ **Parameters:**
49
+ - `images` (str)
50
+
51
+
52
+ ## Authentication
53
+
54
+ Free tier: 15 calls/day. Upgrade at [meok.ai/pricing](https://meok.ai/pricing) for unlimited access.
55
+
56
+ ## Links
57
+
58
+ - **Website**: [meok.ai](https://meok.ai)
59
+ - **GitHub**: [CSOAI-ORG/performance-ai-mcp](https://github.com/CSOAI-ORG/performance-ai-mcp)
60
+ - **PyPI**: [pypi.org/project/performance-ai-mcp](https://pypi.org/project/performance-ai-mcp/)
61
+
62
+ ## License
63
+
64
+ MIT — MEOK AI Labs
@@ -0,0 +1,16 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ | Version | Supported |
6
+ | ------- | ------------------ |
7
+ | 1.0.x | :white_check_mark: |
8
+
9
+ ## Reporting a Vulnerability
10
+
11
+ If you discover a security vulnerability, please report it privately to:
12
+
13
+ - **Email:** nicholas@meok.ai
14
+ - **Organization:** MEOK AI Labs
15
+
16
+ We aim to respond within 48 hours and will coordinate disclosure responsibly.
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "performance-ai-mcp",
3
+ "description": "MEOK AI Labs \u2014 performance-ai-mcp",
4
+ "vendor": "MEOK AI Labs",
5
+ "homepage": "https://meok.ai",
6
+ "repository": "https://github.com/CSOAI-ORG/performance-ai-mcp",
7
+ "license": "MIT",
8
+ "runtime": "python",
9
+ "entryPoint": "mcp-wrapper.py"
10
+ }
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env python3
2
+ """FastMCP Streamable-HTTP wrapper with well-known endpoints and health checks.
3
+
4
+ Usage:
5
+ python /path/to/mcp-streamable-http-wrapper.py
6
+
7
+ This imports `mcp` from `server.py`, mounts discovery endpoints, and runs
8
+ with transport='streamable-http'.
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import sys
14
+
15
+ sys.path.insert(0, os.path.expanduser("~/clawd/meok-labs-engine/shared"))
16
+ sys.path.insert(0, os.getcwd())
17
+
18
+ from starlette.requests import Request
19
+ from starlette.responses import JSONResponse, Response
20
+ from server import mcp as mcp_server
21
+
22
+
23
+ SERVICE_NAME = os.path.basename(os.getcwd())
24
+ REPO_URL = f"https://github.com/CSOAI-ORG/{SERVICE_NAME}"
25
+
26
+
27
+ @mcp_server.custom_route("/.well-known/mcp/server-card.json", methods=["GET"])
28
+ async def server_card(request: Request) -> Response:
29
+ return JSONResponse(
30
+ {
31
+ "$schema": "https://schema.smithery.ai/server-card.json",
32
+ "version": "1.0.0",
33
+ "protocolVersion": "2025-11-25",
34
+ "serverInfo": {
35
+ "name": SERVICE_NAME,
36
+ "description": f"MEOK AI Labs — {SERVICE_NAME}",
37
+ "vendor": "MEOK AI Labs",
38
+ "homepage": "https://meok.ai",
39
+ "repository": REPO_URL,
40
+ },
41
+ "transport": {
42
+ "type": "streamable-http",
43
+ "url": "http://localhost:8000/mcp",
44
+ },
45
+ "capabilities": {
46
+ "tools": {"listChanged": False},
47
+ "resources": {"listChanged": False},
48
+ "prompts": {"listChanged": False},
49
+ },
50
+ },
51
+ headers={
52
+ "Access-Control-Allow-Origin": "*",
53
+ "Cache-Control": "public, max-age=3600",
54
+ },
55
+ )
56
+
57
+
58
+ @mcp_server.custom_route("/.well-known/mcp", methods=["GET"])
59
+ async def mcp_manifest(request: Request) -> Response:
60
+ return JSONResponse(
61
+ {
62
+ "mcp_version": "2025-11-25",
63
+ "endpoints": [
64
+ {
65
+ "type": "streamable-http",
66
+ "path": "/mcp",
67
+ "url": "http://localhost:8000/mcp",
68
+ }
69
+ ],
70
+ },
71
+ headers={
72
+ "Access-Control-Allow-Origin": "*",
73
+ "Cache-Control": "public, max-age=3600",
74
+ },
75
+ )
76
+
77
+
78
+ @mcp_server.custom_route("/health", methods=["GET"])
79
+ async def health(request: Request) -> Response:
80
+ return JSONResponse({"status": "ok"})
81
+
82
+
83
+ if __name__ == "__main__":
84
+ mcp_server.settings.host = "0.0.0.0"
85
+ mcp_server.run(transport="streamable-http")
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "performance-ai-mcp",
3
+ "version": "1.0.0",
4
+ "description": "Performance Ai automation via MCP. Includes analyze waterfall data, suggest optimizations, calculate core web vitals. By MEOK AI Labs.",
5
+ "main": "server.py",
6
+ "mcp": {
7
+ "name": "performance",
8
+ "vendor": "MEOK AI Labs",
9
+ "homepage": "https://meok.ai",
10
+ "repository": "https://github.com/CSOAI-ORG/performance-ai-mcp",
11
+ "runtime": "python",
12
+ "tags": [
13
+ "mcp",
14
+ "mcp-server",
15
+ "meok-ai-labs",
16
+ "ai-tools"
17
+ ]
18
+ },
19
+ "keywords": [
20
+ "mcp",
21
+ "mcp-server",
22
+ "meok-ai-labs"
23
+ ],
24
+ "author": "MEOK AI Labs <nicholas@meok.ai>",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/CSOAI-ORG/performance-ai-mcp"
29
+ }
30
+ }
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+ [project]
5
+ name = "performance-ai-mcp"
6
+ version = "1.0.0"
7
+ description = "Performance Ai automation via MCP. Includes analyze waterfall data, suggest optimizations, calculate core web vitals. By MEOK AI Labs."
8
+ license = {file = "LICENSE"}
9
+ requires-python = ">=3.10"
10
+ authors = [{name = "MEOK AI Labs", email = "nicholas@meok.ai"}]
11
+ dependencies = ["mcp>=1.0.0"]
12
+ keywords = ["mcp", "ai", "meok", "performance"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Software Development :: Libraries",
18
+ ]
19
+ [project.urls]
20
+ Homepage = "https://meok.ai"
21
+ Repository = "https://github.com/CSOAI-ORG/performance-ai-mcp"
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["."]
24
+ only-include = ["server.py"]
25
+
26
+ [project.scripts]
27
+ performance_ai_mcp = "server:main"
@@ -0,0 +1,3 @@
1
+ [pytest]
2
+ testpaths = tests
3
+ python_files = test_*.py
@@ -0,0 +1,213 @@
1
+ """
2
+ Performance AI MCP Server
3
+ Web performance analysis and optimization tools powered by MEOK AI Labs.
4
+ """
5
+
6
+
7
+ import sys, os
8
+ sys.path.insert(0, os.path.expanduser('~/clawd/meok-labs-engine/shared'))
9
+ from auth_middleware import check_access
10
+
11
+ import time
12
+ from collections import defaultdict
13
+ from mcp.server.fastmcp import FastMCP
14
+
15
+ mcp = FastMCP("performance-ai", instructions="MEOK AI Labs MCP Server")
16
+
17
+ _call_counts: dict[str, list[float]] = defaultdict(list)
18
+ FREE_TIER_LIMIT = 50
19
+ WINDOW = 86400
20
+
21
+
22
+ def _check_rate_limit(tool_name: str) -> None:
23
+ now = time.time()
24
+ _call_counts[tool_name] = [t for t in _call_counts[tool_name] if now - t < WINDOW]
25
+ if len(_call_counts[tool_name]) >= FREE_TIER_LIMIT:
26
+ raise ValueError(f"Rate limit exceeded for {tool_name}. Free tier: {FREE_TIER_LIMIT}/day. Upgrade at https://meok.ai/pricing")
27
+ _call_counts[tool_name].append(now)
28
+
29
+
30
+ def _rate_metric(value: float, good: float, poor: float, lower_is_better: bool = True) -> str:
31
+ if lower_is_better:
32
+ return "good" if value <= good else "needs-improvement" if value <= poor else "poor"
33
+ return "good" if value >= good else "needs-improvement" if value >= poor else "poor"
34
+
35
+
36
+ @mcp.tool()
37
+ def analyze_waterfall_data(resources: list[dict], api_key: str = "") -> dict:
38
+ """Analyze a resource loading waterfall for performance bottlenecks.
39
+
40
+ Args:
41
+ resources: List of resource dicts with keys: url, type (js/css/img/font/html/other), size_kb, start_ms, duration_ms, blocking (bool, optional)
42
+ """
43
+ allowed, msg, tier = check_access(api_key)
44
+ if not allowed:
45
+ return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
46
+
47
+ _check_rate_limit("analyze_waterfall_data")
48
+ if not resources:
49
+ return {"error": "No resources provided"}
50
+ total_size = sum(r.get("size_kb", 0) for r in resources)
51
+ total_duration = max(r.get("start_ms", 0) + r.get("duration_ms", 0) for r in resources) if resources else 0
52
+ by_type = defaultdict(lambda: {"count": 0, "total_kb": 0.0, "total_ms": 0.0})
53
+ for r in resources:
54
+ t = r.get("type", "other")
55
+ by_type[t]["count"] += 1
56
+ by_type[t]["total_kb"] += r.get("size_kb", 0)
57
+ by_type[t]["total_ms"] += r.get("duration_ms", 0)
58
+ blocking = [r for r in resources if r.get("blocking")]
59
+ blocking_time = sum(r.get("duration_ms", 0) for r in blocking)
60
+ issues = []
61
+ large = [r for r in resources if r.get("size_kb", 0) > 200]
62
+ for r in large:
63
+ issues.append({"issue": f"Large resource: {r.get('url', 'unknown')} ({r.get('size_kb')}KB)",
64
+ "severity": "warning", "category": "size"})
65
+ slow = [r for r in resources if r.get("duration_ms", 0) > 1000]
66
+ for r in slow:
67
+ issues.append({"issue": f"Slow resource: {r.get('url', 'unknown')} ({r.get('duration_ms')}ms)",
68
+ "severity": "warning", "category": "latency"})
69
+ if blocking_time > 500:
70
+ issues.append({"issue": f"High render-blocking time: {blocking_time}ms", "severity": "error", "category": "blocking"})
71
+ if len(resources) > 80:
72
+ issues.append({"issue": f"Too many requests: {len(resources)}", "severity": "warning", "category": "requests"})
73
+ return {"total_resources": len(resources), "total_size_kb": round(total_size, 1),
74
+ "total_duration_ms": round(total_duration, 1), "by_type": dict(by_type),
75
+ "blocking_resources": len(blocking), "blocking_time_ms": round(blocking_time, 1),
76
+ "issues": issues}
77
+
78
+
79
+ @mcp.tool()
80
+ def suggest_optimizations(page_data: dict, api_key: str = "") -> dict:
81
+ """Suggest performance optimizations based on page characteristics.
82
+
83
+ Args:
84
+ page_data: Dict with optional keys: total_size_kb, js_count, css_count, image_count, font_count, uses_http2 (bool), has_service_worker (bool), has_lazy_loading (bool), ttfb_ms, lcp_ms, cls, fid_ms
85
+ """
86
+ allowed, msg, tier = check_access(api_key)
87
+ if not allowed:
88
+ return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
89
+
90
+ _check_rate_limit("suggest_optimizations")
91
+ suggestions = []
92
+ total = page_data.get("total_size_kb", 0)
93
+ if total > 3000:
94
+ suggestions.append({"category": "size", "priority": "high",
95
+ "suggestion": f"Page is {total}KB. Target under 1500KB. Compress assets and remove unused code."})
96
+ if page_data.get("js_count", 0) > 15:
97
+ suggestions.append({"category": "javascript", "priority": "high",
98
+ "suggestion": f"Too many JS files ({page_data['js_count']}). Bundle and code-split."})
99
+ if page_data.get("css_count", 0) > 5:
100
+ suggestions.append({"category": "css", "priority": "medium",
101
+ "suggestion": f"Multiple CSS files ({page_data['css_count']}). Inline critical CSS and defer the rest."})
102
+ if page_data.get("image_count", 0) > 20 and not page_data.get("has_lazy_loading"):
103
+ suggestions.append({"category": "images", "priority": "high",
104
+ "suggestion": "Many images without lazy loading. Add loading='lazy' to below-fold images."})
105
+ if page_data.get("font_count", 0) > 3:
106
+ suggestions.append({"category": "fonts", "priority": "medium",
107
+ "suggestion": f"Too many font files ({page_data['font_count']}). Limit to 2-3 and use font-display: swap."})
108
+ if not page_data.get("uses_http2"):
109
+ suggestions.append({"category": "protocol", "priority": "high",
110
+ "suggestion": "Enable HTTP/2 for multiplexed connections and header compression."})
111
+ if not page_data.get("has_service_worker"):
112
+ suggestions.append({"category": "caching", "priority": "medium",
113
+ "suggestion": "Add a service worker for offline support and faster repeat visits."})
114
+ ttfb = page_data.get("ttfb_ms", 0)
115
+ if ttfb > 600:
116
+ suggestions.append({"category": "server", "priority": "high",
117
+ "suggestion": f"TTFB is {ttfb}ms. Target <200ms. Consider CDN, caching, or server optimization."})
118
+ lcp = page_data.get("lcp_ms", 0)
119
+ if lcp > 2500:
120
+ suggestions.append({"category": "lcp", "priority": "high",
121
+ "suggestion": f"LCP is {lcp}ms (poor). Preload hero image, optimize critical path."})
122
+ suggestions.sort(key=lambda x: {"high": 0, "medium": 1, "low": 2}.get(x["priority"], 3))
123
+ return {"suggestions": suggestions, "count": len(suggestions),
124
+ "high_priority": sum(1 for s in suggestions if s["priority"] == "high")}
125
+
126
+
127
+ @mcp.tool()
128
+ def calculate_core_web_vitals(lcp_ms: float, fid_ms: float, cls: float, inp_ms: float = 0, api_key: str = "") -> dict:
129
+ """Calculate and rate Core Web Vitals scores.
130
+
131
+ Args:
132
+ lcp_ms: Largest Contentful Paint in milliseconds
133
+ fid_ms: First Input Delay in milliseconds
134
+ cls: Cumulative Layout Shift score
135
+ inp_ms: Interaction to Next Paint in ms (optional, new metric)
136
+ """
137
+ allowed, msg, tier = check_access(api_key)
138
+ if not allowed:
139
+ return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
140
+
141
+ _check_rate_limit("calculate_core_web_vitals")
142
+ lcp_rating = _rate_metric(lcp_ms, 2500, 4000)
143
+ fid_rating = _rate_metric(fid_ms, 100, 300)
144
+ cls_rating = _rate_metric(cls, 0.1, 0.25)
145
+ inp_rating = _rate_metric(inp_ms, 200, 500) if inp_ms else "not-measured"
146
+ all_good = lcp_rating == "good" and fid_rating == "good" and cls_rating == "good"
147
+ any_poor = "poor" in (lcp_rating, fid_rating, cls_rating)
148
+ overall = "good" if all_good else "poor" if any_poor else "needs-improvement"
149
+ score = 100
150
+ score_map = {"good": 0, "needs-improvement": -15, "poor": -35}
151
+ score += score_map.get(lcp_rating, 0) + score_map.get(fid_rating, 0) + score_map.get(cls_rating, 0)
152
+ tips = []
153
+ if lcp_rating != "good":
154
+ tips.append("LCP: Preload hero images, optimize server response, remove render-blocking resources")
155
+ if fid_rating != "good":
156
+ tips.append("FID: Break up long tasks, use web workers, reduce JS execution time")
157
+ if cls_rating != "good":
158
+ tips.append("CLS: Set dimensions on images/ads, avoid inserting content above existing content")
159
+ return {"lcp": {"value_ms": lcp_ms, "rating": lcp_rating, "threshold": {"good": 2500, "poor": 4000}},
160
+ "fid": {"value_ms": fid_ms, "rating": fid_rating, "threshold": {"good": 100, "poor": 300}},
161
+ "cls": {"value": cls, "rating": cls_rating, "threshold": {"good": 0.1, "poor": 0.25}},
162
+ "inp": {"value_ms": inp_ms, "rating": inp_rating, "threshold": {"good": 200, "poor": 500}},
163
+ "overall": overall, "score": max(0, score), "tips": tips}
164
+
165
+
166
+ @mcp.tool()
167
+ def image_optimization_hints(images: list[dict], api_key: str = "") -> dict:
168
+ """Analyze images and suggest optimization strategies.
169
+
170
+ Args:
171
+ images: List of image dicts with keys: url (or name), format (jpg/png/gif/webp/svg), size_kb, width, height, above_fold (bool, optional)
172
+ """
173
+ allowed, msg, tier = check_access(api_key)
174
+ if not allowed:
175
+ return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
176
+
177
+ _check_rate_limit("image_optimization_hints")
178
+ hints = []
179
+ total_size = 0
180
+ potential_savings = 0
181
+ for img in images:
182
+ size = img.get("size_kb", 0)
183
+ total_size += size
184
+ fmt = img.get("format", "").lower()
185
+ w = img.get("width", 0)
186
+ h = img.get("height", 0)
187
+ name = img.get("url", img.get("name", "unknown"))
188
+ img_hints = []
189
+ if fmt in ("jpg", "jpeg", "png") and fmt != "webp":
190
+ savings = size * 0.3
191
+ img_hints.append(f"Convert to WebP/AVIF for ~30% savings (~{savings:.0f}KB)")
192
+ potential_savings += savings
193
+ if fmt == "png" and size > 100:
194
+ img_hints.append("Consider JPEG if no transparency needed")
195
+ if size > 500:
196
+ img_hints.append(f"Very large image ({size}KB). Compress and resize.")
197
+ potential_savings += size * 0.5
198
+ if w > 2000 or h > 2000:
199
+ img_hints.append(f"Image dimensions very large ({w}x{h}). Serve responsive sizes.")
200
+ if not img.get("above_fold") and size > 50:
201
+ img_hints.append("Below fold - add loading='lazy'")
202
+ if img.get("above_fold"):
203
+ img_hints.append("Above fold - preload with <link rel='preload'>")
204
+ if img_hints:
205
+ hints.append({"image": name[:80], "size_kb": size, "hints": img_hints})
206
+ return {"images_analyzed": len(images), "total_size_kb": round(total_size, 1),
207
+ "potential_savings_kb": round(potential_savings, 1),
208
+ "savings_percent": round(potential_savings / max(total_size, 1) * 100, 1),
209
+ "hints": hints}
210
+
211
+
212
+ if __name__ == "__main__":
213
+ mcp.run()
@@ -0,0 +1,35 @@
1
+ name: performance-ai-mcp
2
+ description: Performance Ai automation via MCP. Includes analyze waterfall data, suggest
3
+ optimizations, calculate core web vitals. By MEOK AI Labs.
4
+ version: 1.0.0
5
+ tools:
6
+ - name: analyze_waterfall_data
7
+ description: Analyze a resource loading waterfall for performance bottlenecks.
8
+ parameters:
9
+ - name: resources
10
+ type: array
11
+ required: true
12
+ - name: suggest_optimizations
13
+ description: Suggest performance optimizations based on page characteristics.
14
+ parameters:
15
+ - name: page_data
16
+ type: object
17
+ required: true
18
+ - name: calculate_core_web_vitals
19
+ description: Calculate and rate Core Web Vitals scores.
20
+ parameters:
21
+ - name: lcp_ms
22
+ type: number
23
+ required: true
24
+ - name: fid_ms
25
+ type: number
26
+ required: true
27
+ - name: inp_ms
28
+ type: number
29
+ required: false
30
+ - name: image_optimization_hints
31
+ description: Analyze images and suggest optimization strategies.
32
+ parameters:
33
+ - name: images
34
+ type: array
35
+ required: true
@@ -0,0 +1,55 @@
1
+ import os
2
+ import sys
3
+ import unittest
4
+
5
+ # Ensure shared auth middleware is available
6
+ sys.path.insert(0, os.path.expanduser("~/clawd/meok-labs-engine/shared"))
7
+ os.chdir(os.path.dirname(os.path.abspath(__file__)) + "/..")
8
+
9
+
10
+ class TestMCPImport(unittest.TestCase):
11
+ def test_import_server(self):
12
+ """Server module must import without errors."""
13
+ import server # noqa: F401
14
+
15
+ def test_mcp_or_server_object_exists(self):
16
+ """FastMCP servers export 'mcp'; low-level servers export 'server'."""
17
+ import server as srv
18
+ self.assertTrue(
19
+ hasattr(srv, "mcp") or hasattr(srv, "server"),
20
+ "Expected 'mcp' or 'server' object in server.py",
21
+ )
22
+
23
+
24
+ class TestAuthMiddleware(unittest.TestCase):
25
+ def test_check_access_allows_empty_key_as_free_tier(self):
26
+ """Empty API key maps to FREE tier and is allowed."""
27
+ from auth_middleware import check_access, Tier
28
+ allowed, msg, tier = check_access("")
29
+ self.assertTrue(allowed)
30
+ self.assertEqual(tier, Tier.FREE)
31
+ self.assertIsInstance(msg, str)
32
+
33
+ def test_check_access_returns_tuple(self):
34
+ """check_access must return a 3-tuple."""
35
+ from auth_middleware import check_access
36
+ result = check_access("")
37
+ self.assertIsInstance(result, tuple)
38
+ self.assertEqual(len(result), 3)
39
+
40
+
41
+ class TestHealthEndpoint(unittest.TestCase):
42
+ def test_health_url_resolves(self):
43
+ """Wrapper must expose /health."""
44
+ import urllib.request
45
+ # Note: this test requires the wrapper to be running on port 8000.
46
+ # It is skipped in CI unless the server is active.
47
+ try:
48
+ resp = urllib.request.urlopen("http://localhost:8000/health", timeout=2)
49
+ self.assertEqual(resp.status, 200)
50
+ except Exception as e:
51
+ self.skipTest(f"Server not running: {e}")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ unittest.main()