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
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import gradio as gr
import requests
import json
import pandas as pd
from datetime import datetime, timedelta
import plotly.express as px
import plotly.graph_objects as go
from typing import Dict, List, Any, Optional
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Configuration
PLAUSIBLE_URL = os.getenv("PLAUSIBLE_URL", "https://plausible.io/api/v2/query")
PLAUSIBLE_KEY = os.getenv("PLAUSIBLE_KEY")

class PlausibleAPI:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
    
    def query(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Make a query to the Plausible API"""

        if not self.api_key:
            return {"error": "PLAUSIBLE_KEY environment variable is not set"}
        
        try:
            response = requests.post(PLAUSIBLE_URL, headers=self.headers, json=payload)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": f"API request failed: {str(e)}"}
        except json.JSONDecodeError as e:
            return {"error": f"Failed to parse JSON response: {str(e)}"}

# Initialize API client
api_client = PlausibleAPI(PLAUSIBLE_KEY)

def basic_stats_query(site_id: str, date_range: str, metrics: List[str]) -> tuple:
    """Get basic site statistics"""
    if not site_id:
        return "Please enter a site ID", None, None
    
    payload = {
        "site_id": site_id,
        "metrics": metrics,
        "date_range": date_range
    }
    
    result = api_client.query(payload)
    
    if "error" in result:
        return result["error"], None, None
    
    # Format results
    if result.get("results"):
        metrics_data = result["results"][0]["metrics"]
        stats_dict = dict(zip(metrics, metrics_data))
        
        # Create a simple bar chart
        fig = px.bar(
            x=list(stats_dict.keys()),
            y=list(stats_dict.values()),
            title=f"Stats for {site_id} ({date_range})"
        )
        fig.update_layout(xaxis_title="Metrics", yaxis_title="Values")
        
        return json.dumps(result, indent=2), stats_dict, fig
    
    return json.dumps(result, indent=2), None, None

def timeseries_query(site_id: str, date_range: str, metrics: List[str], time_dimension: str) -> tuple:
    """Get timeseries data"""
    if not site_id:
        return "Please enter a site ID", None
    
    payload = {
        "site_id": site_id,
        "metrics": metrics,
        "date_range": date_range,
        "dimensions": [time_dimension]
    }
    
    result = api_client.query(payload)
    
    if "error" in result:
        return result["error"], None
    
    # Create timeseries chart
    if result.get("results"):
        df_data = []
        for row in result["results"]:
            row_dict = {"time": row["dimensions"][0]}
            for i, metric in enumerate(metrics):
                row_dict[metric] = row["metrics"][i]
            df_data.append(row_dict)
        
        df = pd.DataFrame(df_data)
        df['time'] = pd.to_datetime(df['time'])
        
        fig = go.Figure()
        for metric in metrics:
            fig.add_trace(go.Scatter(
                x=df['time'],
                y=df[metric],
                mode='lines+markers',
                name=metric
            ))
        
        fig.update_layout(
            title=f"Timeseries for {site_id}",
            xaxis_title="Time",
            yaxis_title="Values"
        )
        
        return json.dumps(result, indent=2), fig
    
    return json.dumps(result, indent=2), None

def geographic_analysis(site_id: str, date_range: str, metrics: List[str]) -> tuple:
    """Analyze traffic by country and city"""
    if not site_id:
        return "Please enter a site ID", None, None
    
    payload = {
        "site_id": site_id,
        "metrics": metrics,
        "date_range": date_range,
        "dimensions": ["visit:country_name", "visit:city_name"],
        "filters": [["is_not", "visit:country_name", [""]]],
        "order_by": [[metrics[0], "desc"]]
    }
    
    result = api_client.query(payload)
    
    if "error" in result:
        return result["error"], None, None
    
    # Create geographic visualization
    if result.get("results"):
        df_data = []
        for row in result["results"]:
            row_dict = {
                "country": row["dimensions"][0],
                "city": row["dimensions"][1]
            }
            for i, metric in enumerate(metrics):
                row_dict[metric] = row["metrics"][i]
            df_data.append(row_dict)
        
        df = pd.DataFrame(df_data)
        
        # Create a bar chart of top countries
        country_stats = df.groupby('country')[metrics[0]].sum().sort_values(ascending=False).head(10)
        
        fig = px.bar(
            x=country_stats.index,
            y=country_stats.values,
            title=f"Top Countries by {metrics[0]} for {site_id}",
            labels={'x': 'Country', 'y': metrics[0]}
        )
        fig.update_xaxes(tickangle=45)
        
        return json.dumps(result, indent=2), fig, df.head(20).to_dict('records')
    
    return json.dumps(result, indent=2), None, None

def utm_analysis(site_id: str, date_range: str) -> tuple:
    """Analyze UTM parameters"""
    if not site_id:
        return "Please enter a site ID", None, None
    
    payload = {
        "site_id": site_id,
        "metrics": ["visitors", "events", "pageviews"],
        "date_range": date_range,
        "dimensions": ["visit:utm_medium", "visit:utm_source"],
        "filters": [["is_not", "visit:utm_medium", [""]]]
    }
    
    result = api_client.query(payload)
    
    if "error" in result:
        return result["error"], None, None
    
    if result.get("results"):
        df_data = []
        for row in result["results"]:
            df_data.append({
                "utm_medium": row["dimensions"][0] or "Direct",
                "utm_source": row["dimensions"][1] or "Direct",
                "visitors": row["metrics"][0],
                "events": row["metrics"][1],
                "pageviews": row["metrics"][2]
            })
        
        df = pd.DataFrame(df_data)
        
        # Create sunburst chart
        fig = px.sunburst(
            df,
            path=['utm_medium', 'utm_source'],
            values='visitors',
            title=f"UTM Analysis for {site_id}"
        )
        
        return json.dumps(result, indent=2), fig, df.to_dict('records')
    
    return json.dumps(result, indent=2), None, None

def custom_query(site_id: str, query_json: str) -> str:
    """Execute a custom JSON query"""
    if not site_id:
        return "Please enter a site ID"
    
    try:
        payload = json.loads(query_json)
        payload["site_id"] = site_id  # Override site_id
        
        result = api_client.query(payload)
        return json.dumps(result, indent=2)
    
    except json.JSONDecodeError as e:
        return f"Invalid JSON: {str(e)}"
    except Exception as e:
        return f"Error: {str(e)}"

# Gradio Interface
with gr.Blocks(title="Plausible Analytics Dashboard", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# πŸ“Š Plausible Analytics Dashboard")
    gr.Markdown("MCP Server to analyze your website statistics using the Plausible Stats API.\n\nSo far this app is 100% vibe coded with the help of Claude Sonnet 4.\n\nTry it out with the site id 'azettl.net' or 'fridgeleftoversai.com'.")
    
    with gr.Tab("Basic Stats"):
        gr.Markdown("### Get basic website statistics")
        
        with gr.Row():
            site_input = gr.Textbox(
                label="Site ID",
                placeholder="example.com",
                info="Your domain as added to Plausible"
            )
            date_range = gr.Dropdown(
                choices=["day", "7d", "28d", "30d", "month", "6mo", "12mo", "year", "all"],
                value="7d",
                label="Date Range"
            )
        
        metrics_input = gr.CheckboxGroup(
            choices=["visitors", "visits", "pageviews", "views_per_visit", "bounce_rate", "visit_duration", "events"],
            value=["visitors", "pageviews", "bounce_rate"],
            label="Metrics to Analyze"
        )
        
        basic_btn = gr.Button("Get Basic Stats", variant="primary")
        
        with gr.Row():
            basic_json = gr.Code(label="API Response", language="json")
            basic_stats = gr.JSON(label="Stats Summary")
        
        basic_chart = gr.Plot(label="Statistics Chart")
        
        basic_btn.click(
            basic_stats_query,
            inputs=[site_input, date_range, metrics_input],
            outputs=[basic_json, basic_stats, basic_chart]
        )
    
    with gr.Tab("Timeseries"):
        gr.Markdown("### View trends over time")
        
        with gr.Row():
            ts_site = gr.Textbox(label="Site ID", placeholder="example.com")
            ts_date_range = gr.Dropdown(
                choices=["day", "7d", "28d", "30d", "month"],
                value="7d",
                label="Date Range"
            )
        
        with gr.Row():
            ts_metrics = gr.CheckboxGroup(
                choices=["visitors", "visits", "pageviews", "events"],
                value=["visitors", "pageviews"],
                label="Metrics"
            )
            ts_time_dim = gr.Dropdown(
                choices=["time:hour", "time:day", "time:week", "time:month"],
                value="time:day",
                label="Time Dimension"
            )
        
        ts_btn = gr.Button("Generate Timeseries", variant="primary")
        
        with gr.Row():
            ts_json = gr.Code(label="API Response", language="json")
            ts_chart = gr.Plot(label="Timeseries Chart")
        
        ts_btn.click(
            timeseries_query,
            inputs=[ts_site, ts_date_range, ts_metrics, ts_time_dim],
            outputs=[ts_json, ts_chart]
        )
    
    with gr.Tab("Geographic Analysis"):
        gr.Markdown("### Analyze traffic by location")
        
        with gr.Row():
            geo_site = gr.Textbox(label="Site ID", placeholder="example.com")
            geo_date_range = gr.Dropdown(
                choices=["day", "7d", "28d", "30d", "month"],
                value="7d",
                label="Date Range"
            )
        
        geo_metrics = gr.CheckboxGroup(
            choices=["visitors", "visits", "pageviews", "bounce_rate"],
            value=["visitors", "pageviews"],
            label="Metrics"
        )
        
        geo_btn = gr.Button("Analyze Geography", variant="primary")
        
        with gr.Row():
            geo_json = gr.Code(label="API Response", language="json")
            geo_chart = gr.Plot(label="Geographic Chart")
        
        geo_table = gr.DataFrame(label="Top Locations")
        
        geo_btn.click(
            geographic_analysis,
            inputs=[geo_site, geo_date_range, geo_metrics],
            outputs=[geo_json, geo_chart, geo_table]
        )
    
    with gr.Tab("UTM Analysis"):
        gr.Markdown("### Analyze marketing campaigns and traffic sources")
        
        with gr.Row():
            utm_site = gr.Textbox(label="Site ID", placeholder="example.com")
            utm_date_range = gr.Dropdown(
                choices=["day", "7d", "28d", "30d", "month"],
                value="7d",
                label="Date Range"
            )
        
        utm_btn = gr.Button("Analyze UTM Parameters", variant="primary")
        
        with gr.Row():
            utm_json = gr.Code(label="API Response", language="json")
            utm_chart = gr.Plot(label="UTM Sunburst Chart")
        
        utm_table = gr.DataFrame(label="UTM Data")
        
        utm_btn.click(
            utm_analysis,
            inputs=[utm_site, utm_date_range],
            outputs=[utm_json, utm_chart, utm_table]
        )
    
    with gr.Tab("Custom Query"):
        gr.Markdown("### Execute custom JSON queries")
        gr.Markdown("Use this tab to run advanced queries with custom filters and dimensions.")
        
        custom_site = gr.Textbox(label="Site ID", placeholder="example.com")
        
        custom_query_input = gr.Code(
            label="JSON Query",
            language="json",
            value="""{
  "metrics": ["visitors", "pageviews"],
  "date_range": "7d",
  "dimensions": ["visit:source"],
  "order_by": [["visitors", "desc"]],
  "pagination": {"limit": 10}
}""",
            lines=15
        )
        
        custom_btn = gr.Button("Execute Query", variant="primary")
        custom_result = gr.Code(label="Query Result", language="json", lines=20)
        
        custom_btn.click(
            custom_query,
            inputs=[custom_site, custom_query_input],
            outputs=[custom_result]
        )
    
    with gr.Tab("Setup & Documentation"):
        gr.Markdown("""
        ## πŸ”§ Setup Instructions
        
        ### For Personal Use (Recommended)
        This MCP server is designed for **personal use only**. Each user should run their own instance.
        
        **Setup Steps:**
        1. **Get your Plausible API key:**
           - Log into your Plausible account
           - Go to Account Settings β†’ API Keys
           - Create a new key, select "Stats API" as type
        
        2. **Set environment variable:**
           ```bash
           # Windows
           set PLAUSIBLE_KEY=your-key-here
           
           # Mac/Linux
           export PLAUSIBLE_KEY=your-key-here
           
           # Or create .env file:
           echo "PLAUSIBLE_KEY=your-key-here" > .env
           ```
        
        2. **Install dependencies:**
           ```bash    
           pip install -r requirements.txt
           ```

        3. **Run the server:**
           ```bash
           python app.py
           ```
        
        4. **Add to Claude Desktop config:**
           ```json
           {
             "mcpServers": {
               "plausible": {
                 "command": "npx",
                 "args": ["mcp-remote", "http://localhost:7860/gradio_api/mcp/sse"]
               }
             }
           }
           ```
        
        ### ⚠️ Security Notice
        - **DO NOT** share your API key with others
        - **DO NOT** run this as a public server with your API key (Like I do here to show you how it works πŸ™ˆ)
        - Each user should run their own instance with their own API key
        
        ---
        
        ## πŸ“– API Reference
        
        **Available Metrics:**
        - `visitors`: Unique visitors
        - `visits`: Number of sessions
        - `pageviews`: Total page views
        - `views_per_visit`: Average pages per session
        - `bounce_rate`: Bounce rate percentage
        - `visit_duration`: Average visit duration
        - `events`: Total events
        
        **Date Ranges:**
        - `day`: Current day
        - `7d`: Last 7 days
        - `28d`: Last 28 days
        - `30d`: Last 30 days
        - `month`: Current month
        - `6mo`: Last 6 months
        - `12mo`: Last 12 months
        - `year`: Current year
        - `all`: All time
        
        **Common Dimensions:**
        - `visit:country_name`: Country
        - `visit:source`: Traffic source
        - `visit:device`: Device type
        - `visit:browser`: Browser
        - `event:page`: Page path
        - `time:day`: Daily grouping
        - `time:hour`: Hourly grouping
        
        **Example Filters:**
        ```json
        [["is", "visit:country_name", ["United States", "Canada"]]]
        [["contains", "event:page", ["/blog"]]]
        [["is_not", "visit:device", ["Mobile"]]]
        ```
        """)

# Launch configuration
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=False,
        mcp_server=True
    )