Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion deploy.json
Original file line number Diff line number Diff line change
Expand Up @@ -430,5 +430,14 @@
"veo/**",
"shared/**"
]
},
"microsoft-clarity": {
"site": "microsoft-clarity",
"entrypoint": "./dist/server/main.js",
"platformName": "kubernetes-bun",
"watch": [
"microsoft-clarity/**",
"shared/**"
]
}
}
}
33 changes: 33 additions & 0 deletions microsoft-clarity/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Dependencies
node_modules/

# Build output
dist/

# Environment
.env
.env.local

# OS files
.DS_Store
Thumbs.db

# IDE
.vscode/
.idea/

# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Data
data/
*.db
*.sqlite

# Template files
# Note: Keep app.json.example, ignore app.json if it's just a copy
# app.json

42 changes: 42 additions & 0 deletions microsoft-clarity/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Microsoft Clarity MCP Server

Official Microsoft Clarity integration for the Model Context Protocol (MCP). This server allows AI agents to query analytics data, list session recordings, and access documentation using natural language.

## Features

- **query-analytics-dashboard**: Get metrics like scroll depth, engagement time, and traffic segments.
- **list-session-recordings**: Filter and find specific user sessions based on behavior and technical criteria.
- **query-documentation-resources**: Search official Clarity guides and troubleshooting steps.

## Installation

When installing in Deco Mesh, you will be prompted for your **Microsoft Clarity API Token**.

### 🔑 Obtaining an API Token
1. Log in to your [Microsoft Clarity](https://clarity.microsoft.com/) project.
2. Navigate to **Settings** -> **Data Export**.
3. Select **Generate new API token**.
4. Copy and store the token safely.

## Usage Guidelines & Limits

> [!IMPORTANT]
> The Microsoft Clarity Data Export API has several built-in constraints:
> - **Quota**: 10 API requests per project per day.
> - **Horizon**: Access up to the last 3 days of analytics data.
> - **Dimensions**: Filter by up to 3 dimensions per query.

### Example Queries
- "Show me the top pages by traffic for the last 3 days."
- "List mobile sessions from the last 24 hours that had rage clicks."
- "How do I set up custom tags in Clarity?"

## Development

```bash
bun install
bun run dev
```

## License
MIT
32 changes: 32 additions & 0 deletions microsoft-clarity/app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"scopeName": "deco",
"name": "microsoft-clarity",
"friendlyName": "Microsoft Clarity",
"connection": {
"type": "HTTP",
"url": "https://sites-microsoft-clarity.decocache.com/mcp"
},
"description": "official Microsoft Clarity MCP integration for analytics, session recordings, and documentation access.",
"icon": "https://claritystatic.azureedge.net/images/logo.ico",
"unlisted": false,
"auth": {
"type": "token",
"header": "Authorization",
"prefix": "Bearer"
},
"metadata": {
"categories": [
"Analytics",
"Productivity"
],
"official": true,
"tags": [
"clarity",
"analytics",
"ux",
"microsoft"
],
"short_description": "Microsoft Clarity analytics and recordings",
"mesh_description": "**Microsoft Clarity MCP Server** provides AI-driven access to your website analytics and user behavioral data. \n\n**Key Features**\n- **Natural Language Analytics**: Query traffic, engagement, and scroll depth metrics using plain English.\n- **Session Search**: List and filter session recordings based on advanced behavior criteria (rage clicks, dead clicks, device type, etc.).\n- **Expert Documentation**: Get instant answers about Clarity setup and features directly from the official documentation.\n\n**Use Cases**\n- Marketing analysis to optimize campaign performance.\n- UX research to identify navigation friction and drop-off points.\n- Technical debugging using JavaScript error reports and performance heatmaps.\n\n**Authentication**\nRequires a **Microsoft Clarity API token** generated from your project settings (Settings -> Data Export).\n\n**Limits**\nEach project allows **10 API requests per day**, with a limit of **3 days' data** and up to **3 dimensions per request**."
}
}
25 changes: 25 additions & 0 deletions microsoft-clarity/app.json.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"scopeName": "deco",
"name": "my-mcp",
"friendlyName": "My MCP",
"connection": {
"type": "HTTP",
"url": "https://sites-my-mcp.decocache.com/mcp"
},
"description": "Short description of what this MCP does (1-2 sentences)",
"icon": "https://assets.decocache.com/mcp/{uuid}/icon.png",
"unlisted": false,
"auth": {
"type": "token",
"header": "Authorization",
"prefix": "Bearer"
},
"metadata": {
"categories": ["Productivity"],
"official": false,
"tags": ["example", "template", "mcp"],
"short_description": "Short description of what this MCP does",
"mesh_description": "Detailed description of your MCP (max 1500 characters). Explain what it does, key features, use cases, and authentication method. Use **bold** for feature names. Example: **Key Features** - Feature 1 description. **Use Cases** - Use case description. **Authentication** - How to authenticate. Perfect for developers who need [your use case]. Provides [your benefit]."
}
}

27 changes: 27 additions & 0 deletions microsoft-clarity/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "microsoft-clarity",
"version": "1.0.0",
"description": "MCP server for Microsoft Clarity analytics and session recordings",
"private": true,
"type": "module",
"scripts": {
"dev": "bun run --hot server/main.ts",
"check": "tsc --noEmit",
"build:server": "NODE_ENV=production bun build server/main.ts --target=bun --outfile=dist/server/main.js",
"build": "bun run build:server",
"publish": "cat app.json | deco registry publish -w /shared/deco -y"
},
"dependencies": {
"@decocms/runtime": "1.2.5",
"zod": "^4.0.0"
},
"devDependencies": {
"@decocms/mcps-shared": "workspace:*",
"@modelcontextprotocol/sdk": "^1.25.1",
"deco-cli": "^0.28.0",
"typescript": "^5.7.2"
},
"engines": {
"node": ">=22.0.0"
}
}
70 changes: 70 additions & 0 deletions microsoft-clarity/server/instructions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
export const SYSTEM_INSTRUCTIONS_PROMPT = `
This MCP server provides access to Microsoft Clarity analytics dashboard data, documentation resources and session recordings.

### 1. Session Recordings Tool: \`list-session-recordings\`
Lists Microsoft Clarity session recordings with metadata including session links, duration, and user interaction timelines.

**Parameters:**
- filters: Optional filters for sessions (date range, device type, etc.)
- sortBy: Sort option using SortOptions enum (default: SessionStart_DESC)
- count: Number of sessions to retrieve (1-250, default: 100)

**Sort Options:**
- SessionStart_DESC (newest first - default)
- SessionStart_ASC (oldest first)
- SessionDuration_ASC (shortest duration first)
- SessionDuration_DESC (longest duration first)
- SessionClickCount_ASC (fewest clicks first)
- SessionClickCount_DESC (most clicks first)
- PageCount_ASC (fewest pages first)
- PageCount_DESC (most pages first)

**Example Usage:**
- Get 10 newest sessions: { "count": 10, "sortBy": "SessionStart_DESC" }
- Get 20 longest sessions from date range: { "filters": { "date": { "start": "2024-01-01T00:00:00.000Z", "end": "2024-01-31T23:59:59.999Z" } }, "sortBy": "SessionDuration_DESC", "count": 20 }
- Get 15 mobile sessions with most clicks: { "filters": { "deviceType": ["Mobile"] }, "sortBy": "SessionClickCount_DESC", "count": 15 }
- Get oldest sessions first: { "sortBy": "SessionStart_ASC", "count": 100 }
- Get sessions with most page views: { "sortBy": "PageCount_DESC", "count": 100 }

### 2. Analytics Dashboard Tool: \`query-analytics-dashboard\`
This tool is your **primary and authoritative data source** for all dashboard-related insights and must be used to retrieve accurate, real-time data from the Microsoft Clarity dashboard.

#### Capabilities & Output
Microsoft Clarity dashboard provides comprehensive insights into the behavior and performance of the website, including:
- **User Analytics**: Unique and returning users, sessions, device types, browsers, operating systems
- **Geographic Data**: Countries, regions, traffic sources
- **Content Performance**: Popular pages, referrers, channels, campaigns, sources
- **User Behavior**: Smart events, scroll depth, click patterns
- **Technical Metrics**: JavaScript errors, URL performance
- **Performance Indicators**: Core Web Vitals
- **User Experience**: Quick backs, dead clicks, rage clicks, session duration

**IMPORTANT GUIDELINES:**
- Use SIMPLE, SINGLE-PURPOSE queries only
- Always specify time ranges, full URLs and parameters explicitly; prompt the user if not provided
- Break complex requests into multiple separate queries
- Focus on ONE trend or aggregated metric per query
- **LIMITS**: Each project allows 10 API requests per day, with a limit of 3 days' data and up to 3 dimensions per request.

**Good Examples:**
- "Page views count for the last 3 days"
- "Top javascript errors for PC in the last 2 days"
- "Top pages for mobile in the last 24 hours"

### 3. Documentation Tool: \`query-documentation-resources\`
Authoritative answers to Clarity setup, features, troubleshooting, and integrations. The tool covers topics including:
- Getting Started & Installation (Setup, Verification, Troubleshooting)
- Clarity for Mobile Apps (Android, iOS, SDKs)
- Dashboard & Insights (Overview, Features)
- Session Recordings & Heatmaps (Inline player, Click maps, Scroll maps)
- Filters & Segments (Exclusion filters, Regex)
- Settings & Management (Masking, IP blocking, Funnels)
- Copilot in Clarity (Overview, Chat, Insights)
- API Reference & Troubleshooting

**Best Practices:**
✅ Be specific about topics
✅ Focus on one specific question per query
✅ Use clear, actionable language
❌ Don't combine multiple unrelated topics
`;
43 changes: 43 additions & 0 deletions microsoft-clarity/server/lib/clarity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { Env } from "../main.ts";

const API_BASE_URL = "https://clarity.microsoft.com/mcp";

interface ClarityRequestOptions {
method: string;
body?: any;
token?: string;
}

export async function callClarityApi(
env: Env,
endpoint: string,
options: ClarityRequestOptions,
) {
const state = env.state as any;
const token =
options.token ||
state.API_CREDENTIALS?.API_KEY ||
process.env.CLARITY_API_TOKEN;

if (!token) {
throw new Error(
"Clarity API token not configured. Please provide it in the tool parameters or MCP configuration.",
);
}

const response = await fetch(`${API_BASE_URL}${endpoint}`, {
method: options.method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: options.body ? JSON.stringify(options.body) : undefined,
});

if (!response.ok) {
const errorText = await response.text();
throw new Error(`Clarity API error (${response.status}): ${errorText}`);
}

return response.json();
}
31 changes: 31 additions & 0 deletions microsoft-clarity/server/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Microsoft Clarity MCP Server
*
* This MCP provides tools for interacting with Microsoft Clarity Data Export API,
* including analytics dashboard, session recordings, and documentation access.
*/
import { withRuntime } from "@decocms/runtime";
import { serve } from "@decocms/mcps-shared/serve";

import { tools } from "./tools/index.ts";
import { type Env, StateSchema } from "./types/env.ts";

// Export Env type for use in other files
export type { Env };

/**
* Configure the MCP runtime
*/
const runtime = withRuntime<Env, typeof StateSchema>({
configuration: {
state: StateSchema,
},

// Register tools using the factory pattern for each tool
tools: (env: Env) => tools.map((createTool) => createTool(env)),
});

// Start the server
if (runtime.fetch) {
serve(runtime.fetch);
}
26 changes: 26 additions & 0 deletions microsoft-clarity/server/tools/analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { createPrivateTool } from "@decocms/runtime/tools";
import { SearchRequest } from "../types/clarity.ts";
import { callClarityApi } from "../lib/clarity.ts";
import { z } from "zod";
import type { Env } from "../main.ts";

export const queryAnalyticsDashboard = (env: Env) =>
createPrivateTool({
id: "query-analytics-dashboard",
description:
"This tool is your primary and authoritative data source for all dashboard-related insights and must be used to retrieve accurate, real-time data from the Microsoft Clarity dashboard. Capabilities include User Analytics, Geographic Data, Content Performance, User Behavior, Technical Metrics, and Performance Indicators.",
inputSchema: SearchRequest,
outputSchema: z.any().describe("Clarity analytics data output"),
execute: async ({ context }) => {
const { query, token } = context;
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

const result = await callClarityApi(env, "/dashboard/query", {
method: "POST",
token,
body: { query, timezone },
});

return result;
},
});
27 changes: 27 additions & 0 deletions microsoft-clarity/server/tools/docs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createPrivateTool } from "@decocms/runtime/tools";
import { SearchRequest } from "../types/clarity.ts";
import { callClarityApi } from "../lib/clarity.ts";
import { z } from "zod";
import type { Env } from "../main.ts";

export const queryDocumentationResources = (env: Env) =>
createPrivateTool({
id: "query-documentation-resources",
description:
"Authoritative answers to Clarity setup, features, troubleshooting, and integrations. This tool retrieves snippets from Microsoft Clarity documentation to find answers to user questions.",
inputSchema: SearchRequest,
outputSchema: z
.any()
.describe("Clarity documentation snippets and answers"),
execute: async ({ context }) => {
const { query, token } = context;

const result = await callClarityApi(env, "/documentation/query", {
method: "POST",
token,
body: { query },
});

return result;
},
});
Loading