Skill: lauraytwu-create/tencent-cloud-rum-skill (version 0.1.3)

--- name: tencent-cloud-rum-2.1 description: "Query Tencent Cloud RUM data, analyze Web performance (LCP/FCP/WebVitals), troubleshoot JS/Promise errors, analyze API latency & error rates, diagnose slow static resource loading, and view PV/UV. Supports RUM-APM correlation. Not for: backend-only performance, native mobile performance, or non-Tencent Cloud RUM platforms." homepage: https://console.tencentcloud.com/rum metadata: { "openclaw": { "requires": { "env": ["RUM_TOKEN"] }, "primaryEnv": "RUM_TOKEN", "category": "tencent", "tencentTokenMode": "custom", "tokenUrl": "https://console.tencentcloud.com/cam/capi", "emoji": "📊" } } --- # Tencent Cloud RUM — Frontend Performance Analysis Assistant (v2.1) ## Role & Objective You are a rule-strict **frontend performance analysis expert** specializing in Tencent Cloud Real User Monitoring (RUM). You help users query metrics and logs, then deliver summarized analysis and actionable insights. > **New to Tencent Cloud RUM?** See the [Getting Started](#getting-started-with-tencent-cloud-rum) section below. ## Trigger Conditions ### ✅ Use This Skill When - User mentions RUM, Tencent Cloud RUM, frontend performance, WebVitals, LCP, FCP - Troubleshooting JS errors, Promise errors, resource loading errors - Analyzing API latency, HTTP status codes, retcode error rates - Viewing PV/UV, static resource loading metrics - Generating performance analysis reports ### ❌ Do NOT Use When - Backend-only service performance issues (no frontend RUM data involved) - Native mobile app performance (non-Web) - Non-Tencent Cloud RUM platform queries - General coding tasks unrelated to performance ## Configuration Run `bash setup.sh` for automatic setup. `RUM_TOKEN` format: `SecretId:SecretKey`. Get your credentials at: [Tencent Cloud API Key Management](https://console.tencentcloud.com/cam/capi) ### MCP Server Configuration ```json { "mcpServers": { "rum": { "transportType": "sse", "url": "https://app.rumt-zh.com/sse", "headers": { "SecretId": "<YOUR_SECRET_ID>", "SecretKey": "<YOUR_SECRET_KEY>" } } } } ``` ## Getting Started with Tencent Cloud RUM If you haven't integrated Tencent Cloud RUM yet, follow these steps: 1. **Create an Application**: Go to [Tencent Cloud RUM Console](https://console.tencentcloud.com/rum) and create a new Web application. 2. **Install the SDK**: Follow the [RUM Application Integration Guide](https://www.tencentcloud.com/zh/document/product/1131/44496) to add the SDK to your web project. > 💡 For SDK integration, updating reporting config, enabling white-screen/jank monitoring, or adding custom reporting → use the **[`rum-sdk-setup` Skill](https://skillhub.cn/skills/rum-sdk-setup)** (covers Web / Mini Program / RN / Node.js / Hippy / Cocos and 10 platforms in total) 3. **Try the Demo**: Explore the [RUM Console Demo](https://console.tencentcloud.com/rum/web/demo) to see how RUM dashboards and data look in action. 4. **Get API Keys**: Visit [Tencent Cloud API Key Management](https://console.tencentcloud.com/cam/capi) to obtain your `SecretId` and `SecretKey`. ### Useful Links | Resource | URL | |----------|-----| | RUM Console | https://console.tencentcloud.com/rum | | RUM Console Demo | https://console.tencentcloud.com/rum/web/demo | | Application Integration Guide | https://www.tencentcloud.com/zh/document/product/1131/44496 | | Web SDK Connection Guide | https://www.tencentcloud.com/document/product/1131/44517 | | Getting Started | https://www.tencentcloud.com/document/product/1131/44493 | | API Key Management | https://console.tencentcloud.com/cam/capi | | RUM Product Overview | https://www.tencentcloud.com/document/product/1131/44486 | | RUM Pricing | https://www.tencentcloud.com/document/product/1131/44490 | ## Background Knowledge ### RUM Data Model - **Metrics**: Aggregated user data (LCP, error rates, request counts, etc.) - **Logs**: Raw error logs or custom logs reported by the SDK ### Key Field Definitions - `from` = Page URL (present in all metrics) - `url` = API or resource URL (only in API and resource metrics) - Example: Query slow pages → GroupBy `from`; Query slow APIs → GroupBy `url` ### API Error Classification - **Status Code Errors**: HTTP status code < 0 or > 400 - **Retcode Errors**: HTTP returns OK, but business return code is abnormal - `is_err` field **only filters retcode errors**, does NOT include HTTP status code errors → usually not needed ## Available Tools See `references/rum_tools_docs.md` for detailed parameters: | Tool | Purpose | When to Use | |------|---------|-------------| | `QueryRumWebProjects` | List applications | Get ProjectId (prerequisite for other tools) | | `QueryRumWebMetric` | Query aggregated metrics | Network/exception/PV/UV/performance/resource analysis | | `QueryRumWebLog` | Query logs | Error details, user behavior, root cause analysis | | `QueryResourceByPage` | Query resources by page | View resource loading per page | | `QueryApmLinkId` | Get linked APM app | Bridge RUM and APM (see `references/apm_analysis.md`) | ## 🔴 CRITICAL Rules (Violation causes query failure) 1. **GroupBy MUST be an array**, even for a single field → `["from"]` not `"from"` - Why: The API rejects non-array parameters with a format error 2. **Filters MUST be JSON objects**, not strings - Why: Strings get incorrectly serialized by the MCP framework, causing empty results 3. **Multi-dimensional analysis MUST use separate GroupBy queries**, never pass multiple dimension fields in one query - Why: Multi-field GroupBy produces Cartesian products (100 pages × 30 regions = 3000 rows), exceeding Limit and truncating data 4. **QueryRumWebLog operators (eq/neq/like/nlike/in) differ from QueryRumWebMetric operators (=/!=/like/not like)** - Why: The two tools have different backend implementations; wrong operators cause filter failures 5. **QueryRumWebLog: `level` field only supports eq, neq, in operators** - Why: `level` is an enum; fuzzy matching is not supported ## 🟡 IMPORTANT Rules (Violation affects analysis quality) 1. **QueryRumWebMetric Limit defaults to 100**; QueryRumWebLog Limit **defaults to 10** - Why: Metrics need enough data for TOP ranking; Logs are verbose — 10 entries suffice, more bloats context 2. **Metric sorting defaults by data volume**; sort by metric value manually after query - Why: API doesn't support custom sort fields; raw output may be misleading (highest count ≠ worst value) 3. **Most log info is in the `msg` field**; query URL-related content via `msg` with `like` filter - Why: `url` is not a standalone field — it's embedded in the `msg` JSON 4. **Use RespFields wisely** — only request fields needed for the analysis - Why: Full responses are too large, wasting context space and analysis efficiency 5. **Region field differs**: `region` in QueryRumWebMetric; `city`/`country` in QueryRumWebLog - Why: Different data sources have different field naming ## 🟢 STYLE Rules (Violation affects output quality) 1. **Do NOT use `~` symbol** in output; use `>` and `<` for ranges - Why: Markdown renderers may interpret `~` as strikethrough 2. Include data source attribution (Tencent Cloud RUM MCP) at the end of output ## Execution Decision Tree ``` 1. Receive user request │ 2. Determine application info (see "Application Info Lookup Rules" below for 4 scenarios) │ → Valid ProjectId obtained → Proceed to analysis │ → Not obtained → ⏸ Pause and follow the lookup rules │ 3. Match analysis scenario │ Keywords: "error/exception/JS Error/Promise" → Flow 1 (references/common_queries.md) │ Keywords: "performance/LCP/FCP/slow/white screen" → Flow 2 │ Keywords: "API/endpoint/latency/status code" → Flow 3 │ Keywords: "resource/image/CSS/JS file/slow load" → Flow 4 │ Simple data query → Direct tool call │ 4. Follow corresponding flow in references/common_queries.md │ 5. After each step: Can we drill down further? │ Yes → Continue (region/ISP/platform/version dimensions) │ No → Output conclusions │ 6. If log contains non-empty trace → Correlate with APM (see references/apm_analysis.md) ``` ## Application Info Lookup Rules The only tool to query RUM applications: `QueryRumWebProjects` (returns at most 50 records; `ProjectId` must be a numeric string, e.g. `"123456"`). ### Four scenarios based on what the user provided **Scenario A — Only ProjectId given** 1. Validate format first: if not a pure numeric string → ⏸ Pause and prompt "ProjectId must be numeric (e.g. 123456). The value `<val>` you provided is not valid." 2. Call `QueryRumWebProjects({ProjectId: "<ID>"})` to confirm existence - Hit → Proceed to analysis - Empty → ⏸ Pause and prompt "ProjectId `<ID>` was not found in your account's RUM-WEB applications. It may be incorrect." After user confirms, list all apps for them to choose. **Scenario B — Only app name given** 1. Exact match `QueryRumWebProjects({ProjectName: "<name>"})` - 1 hit → Proceed to analysis - Multiple hits → ⏸ Pause and list for user to choose - No result → Go to step 2 2. Fuzzy match `QueryRumWebProjects({ProjectNameLike: "<name>"})` - 1 hit → Proceed to analysis - Multiple hits → ⏸ Pause and list for user to choose - No result → Go to step 3 3. List all with `QueryRumWebProjects({})` and let the user verify (they may have misremembered the name) - Still no match → ⏸ Pause and prompt "No application containing `<name>` was found. Please verify it exists in the current account." **Scenario C — Both ID and name given** 1. Treat ProjectId as authoritative (it is the required field of the tool); validate per Scenario A 2. If ProjectId exists but its returned ProjectName differs from what the user said → prompt "ProjectId `<ID>` corresponds to the application `<actual-name>`, which differs from `<user-provided-name>`. Please confirm." **Scenario D — Neither given** 1. Call `QueryRumWebProjects({})` to fetch the full list 2. ⏸ Pause and list applications for the user to choose ### Universal fallback rules - `QueryRumWebProjects({})` returns exactly 50 records → prompt "Your application count has reached or exceeded the 50-record limit. Please provide an application-name keyword for precise lookup." - Any downstream tool reports "no permission" → first suspect that `ProjectId` is wrong (may belong to a different account) and return to Scenario A to validate - At any step in the flow, if multiple applications are hit → ⏸ Pause and list for user to choose ## Metric Parameter Quick Reference | User Need | Metric Value | Notes | |-----------|-------------|-------| | API request count/latency/error rate | `network` | — | | HTTP status codes/retcode | `network` | — | | Network errors | `network` | Not `exception` | | All exceptions | `exception` | No level filter | | JS errors | `exception` | level=4 | | JS + Promise errors | `exception` | level in ('4','8') | | Page performance | `performance` | Default: use LCP | | PV / UV | `pv` / `uv` | — | | Static resources | `resource` | Does not support `from` filter | ## Error Handling - Tool error or empty data → First check parameter format and values - No data found → Expand time range and retry - Auth failure → Prompt user to check SecretId/SecretKey configuration - No time parameters → Use tool defaults ## Output Quality Standards ### Good Analysis Report ✅ - Every TOP issue has **specific numbers** ("LCP avg 3.2s, exceeding Good threshold of 2.5s") - Root cause analysis has **evidence chain** ("DNS avg 800ms → regional analysis → Xinjiang DNS 2.3s → CDN not covering this region") - Recommendations are **actionable** ("Add CDN edge nodes in the northwest region" not "optimize CDN") - Multi-dimensional cross-analysis (don't conclude from a single dimension) - Always correlate with APM when trace data is available ### Poor Analysis Report ❌ - Lists raw data without conclusions - Vague recommendations ("optimize performance", "reduce errors") - Concludes from a single dimension only - Misses APM correlation when trace data exists ## Analysis Flow Index See `references/common_queries.md` for detailed steps: | User Need | Corresponding Flow | |-----------|--------------------| | Troubleshoot exceptions/JS errors/Promise errors | Flow 1: TOP Exception Analysis | | Analyze page performance/LCP/FCP/WebVitals | Flow 2: TOP Page Performance Analysis | | Analyze API latency/error rate/stability | Flow 3: TOP API Performance & Stability Analysis | | Analyze slow static resource loading | Flow 4: TOP Slow Resource Loading Analysis | | Query specific metrics/logs/simple data | Direct tool call | ## APM Correlation When log `trace` field is non-empty, correlate with APM for deep analysis. See `references/apm_analysis.md` for detailed steps. ## Notes - Tencent Cloud RUM MCP uses `SSE` protocol - Authentication via `SecretId` and `SecretKey` in HTTP headers — keep them secure - If user hasn't configured credentials, guide them to [Tencent Cloud API Key Management](https://console.tencentcloud.com/cam/capi)

path: setup.sh
content: #!/bin/bash
# Setup script for Tencent Cloud RUM MCP Skill
# Authentication via SecretId + SecretKey

set -e

echo "🚀 Setting up Tencent Cloud RUM MCP Skill..."
echo ""

# 1. Check mcporter
MCPORTER_VERSION="0.9.0"
if ! command -v mcporter &> /dev/null; then
    echo "⚠️  mcporter not found, installing v${MCPORTER_VERSION}..."
    npm install -g "mcporter@${MCPORTER_VERSION}"
    echo "✅ mcporter v${MCPORTER_VERSION} installed"
fi

# 2. Check environment variable
if [ -z "$RUM_TOKEN" ]; then
    echo "⚠️  RUM_TOKEN environment variable not detected"
    echo ""
    echo "📋 Please configure the environment variable first:"
    echo "   export RUM_TOKEN=\"YourSecretId:YourSecretKey\""
    echo ""
    echo "   Format: SecretId and SecretKey separated by a colon (:)"
    echo ""
    echo "🔗 Get credentials: Visit https://console.tencentcloud.com/cam/capi to obtain your SecretId and SecretKey"
    echo ""
    echo "   If using in OpenClaw, enter SecretId:SecretKey in the API key input field"
    exit 1
fi

# 3. Parse RUM_TOKEN (format: SecretId:SecretKey)
RUM_SECRET_ID="${RUM_TOKEN%%:*}"
RUM_SECRET_KEY="${RUM_TOKEN#*:}"

if [ -z "$RUM_SECRET_ID" ] || [ -z "$RUM_SECRET_KEY" ] || [ "$RUM_SECRET_ID" = "$RUM_TOKEN" ]; then
    echo "❌ RUM_TOKEN format error. Please use SecretId:SecretKey format (colon-separated)"
    exit 1
fi

echo "✅ SecretId and SecretKey parsed successfully"

# 4. Add MCP configuration
echo "🔧 Configuring mcporter..."

# Remove old config if exists
mcporter config remove rum --scope home 2>/dev/null || true

# Write mcporter config file, ensuring both headers are correctly passed
MCPORTER_CONFIG="$HOME/.mcporter/mcporter.json"
mkdir -p "$HOME/.mcporter"

# Use node to safely write/merge config (pass SecretId/SecretKey via env vars)
RUM_SID="$RUM_SECRET_ID" RUM_SKEY="$RUM_SECRET_KEY" MCPORTER_CFG="$MCPORTER_CONFIG" node -e "
const fs = require('fs');
const cfgPath = process.env.MCPORTER_CFG;
let config = {};
try { config = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch(e) {}
if (!config.mcpServers) config.mcpServers = {};
config.mcpServers.rum = {
  url: 'https://app.rumt-zh.com/sse',
  transportType: 'sse',
  headers: {
    SecretId: process.env.RUM_SID,
    SecretKey: process.env.RUM_SKEY
  }
};
fs.writeFileSync(cfgPath, JSON.stringify(config, null, 2));
"

echo "✅ Configuration written to $MCPORTER_CONFIG"

echo ""
echo "✅ Setup complete!"
echo ""

# 5. Verify configuration
echo "🧪 Verifying configuration..."
if mcporter list 2>&1 | grep -q "rum"; then
    echo "✅ Configuration verified successfully!"
    echo ""
    mcporter list | grep -A 1 "rum" || true
else
    echo "⚠️  Configuration verification failed. Please check your network or RUM_TOKEN (format: SecretId:SecretKey)"
    echo ""
    echo "🔗 Get SecretId/SecretKey: https://console.tencentcloud.com/cam/capi"
fi

echo ""
echo "─────────────────────────────────────"
echo "🎉 Setup complete!"
echo ""
echo "📖 Usage:"
echo "   mcporter call \"rum.QueryRumWebProjects()\""
echo "   mcporter call \"rum.QueryRumWebMetric(ProjectId:'123456', Metric:'exception', GroupBy:['level'], Limit:100)\""
echo ""
echo "📖 For more information, see SKILL.md"
echo ""
echo "📚 New to Tencent Cloud RUM?"
echo "   Console:   https://console.tencentcloud.com/rum"
echo "   Demo:      https://console.tencentcloud.com/rum/web/demo"
echo "   Docs:      https://www.tencentcloud.com/zh/document/product/1131/44496"
echo ""


path: README.md
content: # Tencent Cloud RUM — Frontend Performance Analysis Skill (v2.1)

## Overview

This Skill is deeply integrated with [Tencent Cloud Real User Monitoring (RUM)](https://www.tencentcloud.com/document/product/1131/44486), providing AI-powered frontend performance analysis. It relies on the RUM MCP (Model Context Protocol) service to query metrics and logs, and delivers actionable analytical insights. The MCP endpoint used by this Skill, `https://app.rumt-zh.com/sse`, is the official Tencent Cloud RUM MCP service.

> Major changes in v2.1 vs v2.0: restructured the "Application Info Lookup Rules" into four scenarios (ID only / name only / ID + name / neither) with fallbacks for the 50-record cap and "no permission" errors; the decision tree has been streamlined to avoid duplication with the lookup rules.

## Directory Structure

```
Tencent Cloud RUM 2.1/
├── SKILL.md                              # Core Skill instruction file
├── setup.sh                              # One-click setup script (MCP config)
├── README.md                             # This file
└── references/                           # Reference docs (AI loads on demand)
    ├── rum_tools_docs.md                 # Parameter reference for the 5 RUM MCP tools
    ├── common_queries.md                 # Detailed steps for the 4 analysis flows
    └── apm_analysis.md                   # APM correlation + log enums + regions
```

## Quick Start

### Prerequisites

1. **Tencent Cloud Account**: Register at [Tencent Cloud](https://www.tencentcloud.com/)
2. **RUM Application**: Create a Web application in the [RUM Console](https://console.tencentcloud.com/rum)
3. **API Credentials**: Get your `SecretId` and `SecretKey` from [API Key Management](https://console.tencentcloud.com/cam/capi)

### Getting Started

1. **Try the Demo**: Visit the [RUM Console Demo](https://console.tencentcloud.com/rum/web/demo) to see RUM in action
2. **Install the SDK**: Follow the [Application Integration Guide](https://www.tencentcloud.com/zh/document/product/1131/44496) to complete SDK setup
   > 💡 For SDK integration, updating reporting config, enabling white-screen/jank monitoring, or adding custom reporting → use the **[`rum-sdk-setup` Skill](https://skillhub.cn/skills/rum-sdk-setup)** (covers 10 platforms)
3. **Configure This Skill**: Run `bash setup.sh`, or configure the MCP manually

### MCP Configuration

```json
{
  "mcpServers": {
    "rum": {
      "transportType": "sse",
      "url": "https://app.rumt-zh.com/sse",
      "headers": {
        "SecretId": "<YOUR_SECRET_ID>",
        "SecretKey": "<YOUR_SECRET_KEY>"
      }
    }
  }
}
```

## Features

### Available Tools

| Tool | Purpose |
|------|---------|
| QueryRumWebProjects | List RUM-WEB applications |
| QueryRumWebMetric | Query network / exception / PV / UV / performance / resource metrics |
| QueryRumWebLog | Full log search |
| QueryResourceByPage | Query resource metrics per page |
| QueryApmLinkId | Get the linked APM application ID |

### Built-in Analysis Flows

| Flow | Description |
|------|-------------|
| TOP Exception Analysis | Diagnose JS / Promise errors and resource loading errors |
| TOP Page Performance Analysis | Analyze LCP / FCP and WebVitals; pinpoint performance bottlenecks |
| TOP API Performance & Stability | Analyze API latency, status-code errors, retcode errors |
| TOP Slow Resource Loading | Diagnose static-resource loading bottlenecks |

### Advanced Capabilities

- **APM correlation**: When logs contain trace info, correlate with APM for deep backend-link analysis
- **Multi-dimensional drill-down**: Break down by region, ISP, platform, version, page, etc.
- **Smart routing**: Automatically match the most suitable analysis flow based on user intent

## Useful Links

| Resource | URL |
|----------|-----|
| RUM Console | https://console.tencentcloud.com/rum |
| RUM Console Demo | https://console.tencentcloud.com/rum/web/demo |
| Application Integration Guide | https://www.tencentcloud.com/zh/document/product/1131/44496 |
| Web SDK Connection Guide | https://www.tencentcloud.com/document/product/1131/44517 |
| Getting Started | https://www.tencentcloud.com/document/product/1131/44493 |
| RUM Product Overview | https://www.tencentcloud.com/document/product/1131/44486 |
| RUM Pricing | https://www.tencentcloud.com/document/product/1131/44490 |
| API Key Management | https://console.tencentcloud.com/cam/capi |

## Notes

1. RUM MCP uses the `SSE` protocol
2. Authentication is done via `SecretId` and `SecretKey` in HTTP headers — keep them secure
3. Recommended timeout: 15–30 seconds


path: references/rum_tools_docs.md
content: # Tencent Cloud RUM MCP Tool Parameter Reference

## MCP Server Configuration

- **URL**: `https://app.rumt-zh.com/sse`
- **Transport Protocol**: `sse`
- **Authentication**: Via HTTP Headers — `SecretId` and `SecretKey` (Obtain at: [Tencent Cloud API Key Management](https://console.tencentcloud.com/cam/capi))

```json
{
  "mcpServers": {
    "rum": {
      "transportType": "sse",
      "url": "https://app.rumt-zh.com/sse",
      "headers": {
        "SecretId": "<YOUR_SECRET_ID>",
        "SecretKey": "<YOUR_SECRET_KEY>"
      }
    }
  }
}
```

---

## Tool 1: QueryRumWebProjects

### Description
Query the list of RUM-WEB applications. Shows up to 50 entries. If you have more than 50 applications, use ProjectName or ProjectId parameters to filter.

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `ProjectId` | string | No | Application ID, numeric string, e.g. "123456" |
| `ProjectName` | string | No | Application name, exact match |
| `ProjectNameLike` | string | No | Fuzzy search, finds all apps containing the specified string. Cannot be used with ProjectName simultaneously |

### Usage Scenarios
- User provided only a ProjectId — call `QueryRumWebProjects({ProjectId: "<ID>"})` first to verify existence
- User doesn't know their ProjectId — call without parameters to get the full list
- View all RUM-WEB applications under the current account
- User provides app name — try exact match (`ProjectName`) first, then fuzzy match (`ProjectNameLike`)

### Calling Notes
- `ProjectId` must be a pure numeric string (e.g. `"123456"`); if the format is invalid, verify with the user first
- If exact name match returns nothing, try `ProjectNameLike` for fuzzy search
- If fuzzy search also returns nothing, call without any parameters to get the full list for comparison
- When the full-list call returns exactly 50 records → the limit has been hit; ask the user for an application-name keyword
- If another tool reports "no permission", come back here to validate the `ProjectId` — it may be wrong
- The complete four-scenario lookup flow is in `SKILL.md` under "Application Info Lookup Rules"

---

## Tool 2: QueryRumWebMetric

### Description
Query RUM-WEB metric data. Supports network metrics (request count, avg API latency, status code error rate, retcode error rate), JS Errors, resource loading exceptions, PV, UV, page performance, and static resources.

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `ProjectId` | string | ✅ Yes | Application ID |
| `Metric` | string(enum) | ✅ Yes | Metric type: `network`/`exception`/`pv`/`uv`/`performance`/`resource` |
| `Limit` | number | ✅ Yes | Number of results, **default recommended 100**, max 1000 |
| `StartTime` | number | No | Start timestamp (seconds), default 12 hours ago |
| `EndTime` | number | No | End timestamp (seconds), default current time |
| `Region` | string | No | Region: `ap-guangzhou`(default)/`ap-singapore`/`na-siliconvalley` |
| `Filters` | array | No | Filter conditions array |
| `GroupBy` | array | No | Aggregation grouping fields (MUST be an array even for single field) |

### Metric Parameter Selection Guide

| User Need | Metric Value | Notes |
|-----------|-------------|-------|
| API request count, latency, error rate | `network` | — |
| HTTP status codes, retcode | `network` | — |
| Network errors | `network` | Not `exception` |
| All exception types | `exception` | No level filter |
| JS errors | `exception` | Filter level=4 |
| JS + Promise errors | `exception` | Filter level in ('4','8') |
| Page performance (LCP/FCP/TTFB, etc.) | `performance` | Default: use LCP |
| PV | `pv` | — |
| UV | `uv` | — |
| Static resource loading | `resource` | Does not support `from` filter |

### Filters

**Supported fields**: `brand`, `browser`, `device`, `env`, `error_msg`(exception only), `ext1`~`ext10`, `from`(resource not supported), `is_abroad`, `is_err`, `isp`, `level`(exception only), `method`, `net_type`, `os`, `platform`, `region`, `ret`, `status`, `url`, `version`

**Operators**: `=`(equals), `!=`(not equals), `like`(fuzzy match), `not like`(fuzzy not match)

**Note**: `is_err` only filters retcode errors; usually not needed.

Filter example:
```json
[
    {"Key": "env", "Operator": "=", "Value": "production"},
    {"Key": "version", "Operator": "=", "Value": "2.0.0"},
    {"Key": "level", "Operator": "in", "Value": "('4','8')"}
]
```

### GroupBy Aggregation Dimensions

**Available values**: `brand`, `browser`, `device`, `env`, `ext1`~`ext10`, `from`, `is_abroad`, `is_err`, `isp`, `method`, `net_type`, `os`, `platform`, `region`, `ret`, `status`, `url`, `version`, `time(1m)`, `time(5m)`, `time(1h)`, `time(1d)`

**Key notes**:
- MUST pass as array even for single field, e.g. `["from"]`
- **For multi-dimensional analysis, query each dimension separately — never GroupBy all dimensions at once**
- Metric sorting defaults by data volume; sort by metric value manually after query

### Critical: `from` vs `url` vs `originFrom` Field Semantics in Queries

When using RUM query tools, these URL-related fields have distinct meanings:

| Field | Meaning in Query Context | Usage |
|-------|--------------------------|-------|
| `from` | **Page URL** — the page where the event occurred (processed by SDK's `urlHandler`) | Use in `GroupBy: ["from"]` or `Filters` to analyze by page dimension. Applies to: performance, network, exception, pv/uv metrics |
| `url` | **API/Resource URL** — the monitored network request or resource address | Use in `GroupBy: ["url"]` or `Filters` to analyze specific API endpoints or resources. Applies to: network and resource metrics. **Note**: `resource` metric does NOT support `from` filter — use `QueryResourceByPage` tool instead |
| `originFrom` | **Raw page URL** (unprocessed, from browser address bar) | NOT available as a GroupBy/Filter dimension in metric queries. Only visible in individual log details (via `QueryRumWebLog`). Web-only; returns empty on RN/Mini Program |

**Common mistakes to avoid**:
- Do NOT confuse `from` (page) with `url` (API/resource) — they answer different questions
- When user asks "which page has the most errors" → use `GroupBy: ["from"]`
- When user asks "which API is slowest" → use `GroupBy: ["url"]`
- When user asks about the "original page URL" in log details → that's `originFrom`

### Common Response Fields

**network type**:
- `allCount` - Total request count
- `duration_avg` - Average latency
- `error_rate_percent` - Status code error rate
- `retcode_error_percent` - Retcode error rate

**performance type**:
- `lcp_avg` - LCP average
- `fcp_avg` - FCP average
- `dns_avg` - DNS lookup time
- `tcp_avg` - TCP connection time
- `ssl_avg` - SSL handshake time
- `ttfb_avg` - TTFB time
- `content_download_avg` - Content download time
- `dom_parse_avg` - DOM parse time
- `resource_download_avg` - Resource download time
- `fmp_avg` - First meaningful paint time

**resource type**:
- `allCount` - Total request count
- `duration_avg` - Average loading time
- `error_rate_percent` - Loading error rate
- `connect_time_avg` - Connection time
- `domain_lookup_avg` - Domain lookup time
- `transfer_size_avg` - Transfer size (negative value means cross-origin prevents size retrieval)

**exception type**:
- `allCount` - Total exception count
- `affectCount` - Affected user count
- `error_rate_percent` - Error rate

---

## Tool 3: QueryRumWebLog

### Description
Query full RUM-WEB logs with rich filtering and pagination support.

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `ProjectId` | string | ✅ Yes | Application ID |
| `Limit` | number | ✅ Yes | Number of results, **default recommended 10**, max 1000 |
| `StartTime` | number | No | Start timestamp (seconds), default 2 hours ago |
| `EndTime` | number | No | End timestamp (seconds), default current time |
| `Region` | string | No | Region, default `ap-guangzhou` |
| `Filters` | array | No | Filter conditions array (**MUST be JSON objects, not strings**) |
| `RespFields` | array | No | Specify return fields; omit to return all (**use wisely to avoid oversized responses**) |
| `LastRowId` | number | No | For pagination — last row_id from previous response |
| `LastTime` | number | No | For pagination — last ts from previous response |

### Filters

**Supported fields**: `aid`, `brand`, `browser`, `city`, `country`, `device`, `env`, `errorMsg`, `ext1`~`ext10`, `from`, `ip`, `isAbroad`, `isp`, `level`, `method`, `msg`, `netType`, `os`, `platform`, `province`, `region`, `sessionId`, `sr`, `trace`, `ts`, `uin`, `userAgent`, `version`, `vp`

**Operators**: `eq`(equals), `neq`(not equals), `like`(fuzzy match), `nlike`(fuzzy not match), `in`

**Key notes**:
- Log tool operators (`eq`/`neq`/`like`/`nlike`/`in`) **differ from Metric tool operators** (`=`/`!=`/`like`/`not like`)
- `level` field **only supports** `eq`, `neq`, `in` operators
- Most info (including urls) is in the `msg` field — use `msg` with `like` to search URLs
- Region fields use `city` and `country` (not `region`)

### RespFields Options

`aid`, `brand`, `browser`, `city`, `country`, `device`, `env`, `errorMsg`, `ext1`~`ext10`, `from`, `ip`, `isAbroad`, `isp`, `level`, `method`, `msg`, `netType`, `os`, `platform`, `province`, `region`, `sessionId`, `sr`, `trace`, `ts`, `uin`, `userAgent`, `version`, `vp`

---

## Tool 4: QueryResourceByPage

### Description
Query resource metrics by page. Filter conditions only support the `from` field. For other filters or GroupBy, use `QueryRumWebMetric`.

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `ProjectId` | string | ✅ Yes | Application ID |
| `From` | string | ✅ Yes | Page URL to query |
| `StartTime` | number | No | Start timestamp (seconds), default 12 hours ago |
| `EndTime` | number | No | End timestamp (seconds), default current time |

### Response Metrics
- `duration_avg` - Average resource loading time
- `connect_time_avg` - Connection time
- `domain_lookup_avg` - Domain lookup time
- `transfer_size_avg` - Transfer size (**negative value means cross-origin prevents retrieval**; suggest configuring `Timing-Allow-Origin` in response headers)
- `error_rate_percent` - Resource loading error rate

---

## Tool 5: QueryApmLinkId

### Description
Get the APM application ID linked to a RUM application, enabling RUM-APM trace correlation.

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `ProjectId` | string | ✅ Yes | RUM application ID |
| `Region` | string | No | Region, default `ap-guangzhou` |

### Usage Scenario
When the `trace` field in logs is non-empty, call this tool to get the linked APM project ID, then use APM tools for deeper backend trace analysis.


path: references/common_queries.md
content: # RUM-WEB Problem Analysis Workflows

This document contains four major analysis workflows. The AI should match the appropriate workflow based on user needs.

---

## Flow 1: TOP Exception Analysis

### Step 1: Get RUM Application Info
- **Goal**: Determine the RUM application ID to analyze
- **Action**: See "Application Info Retrieval Rules" in SKILL.md

### Step 2: Query Exception Metrics Overview (All Types)
- **Goal**: Understand the overall exception landscape
- **Action**: Call `QueryRumWebMetric`
  - `Metric`: `exception`
  - `GroupBy`: `["level"]`
  - `Limit`: `100`
  - No level filter in Filters (query all exception types)
- **Analysis**: Count exceptions by type (level), identify which types are most severe

### Step 3: Analyze TOP JS/Promise Errors
- **Goal**: Find the most frequent JS/Promise errors
- **Action**: Call `QueryRumWebMetric`
  - `Metric`: `exception`
  - `Filters`: `[{"Key":"level","Operator":"in","Value":"('4','8')"}]`
  - `GroupBy`: `["error_msg"]`
  - `Limit`: `100`
- **Output**: TOP JS/Promise errors grouped by error message (count, affected users, error rate)

### Step 4: Analyze Other Important Exception Types
- **Goal**: Analyze other high-frequency exceptions discovered in Step 2
- **Action**: For each notable exception type (e.g., resource loading errors), call `QueryRumWebMetric`
  - `Metric`: `exception`
  - `Filters`: Set corresponding level value (e.g., level=32 for script loading errors)
  - `GroupBy`: Choose appropriate field (e.g., `["from"]`)
  - `Limit`: `100`

### Step 5: Analyze Exception Distribution
- **Goal**: Understand TOP exception distribution patterns
- **Action**: For each TOP exception, run multi-dimensional analysis:
  - By page: `GroupBy`: `["from"]`
  - By platform: `GroupBy`: `["platform"]`
  - By version: `GroupBy`: `["version"]`
- **Note**: Run separate GroupBy queries for each dimension — never combine all dimensions in one query

### Step 6: Query Specific Exception Logs
- **Goal**: Get detailed log info for TOP exceptions to analyze root causes
- **Action**: For each TOP exception, call `QueryRumWebLog`
  - `Filters`: Set conditions based on the specific exception
    - Corresponding level type
    - For JS errors, use `msg` field with `like` to match error_msg
  - `Limit`: `10` (representative samples)
  - `RespFields`: Set based on analysis needs
- **Analysis**: Review full error stack traces, occurrence context, user environment

### Step 7: APM Correlation (If Applicable)
- **Trigger**: Exception is API-related and log `trace` field is non-empty
- **Action**:
  1. Call `QueryApmLinkId` to get the linked APM application ID
  2. Follow "APM Trace Analysis Steps" in apm_analysis.md

### Step 8: Output Analysis Conclusions
- **Output**:
  1. **TOP Exception List**: Ranked by severity (count, affected users, error rate)
  2. **Exception Type Distribution**: Proportions and trends of each type
  3. **Root Cause Analysis per TOP Exception**:
     - Error description and message
     - Most affected pages
     - Most affected user groups (platform, browser, version, etc.)
     - Typical occurrence scenarios
     - Probable root causes
  4. **Optimization Recommendations**: Specific fix suggestions for each TOP exception

---

## Flow 2: TOP Page Performance Analysis

### Step 1: Get RUM Application Info
- **Goal**: Determine the RUM application ID to analyze

### Step 2: Query LCP Performance Metrics by Page
- **Goal**: Identify the worst-performing TOP pages
- **Action**: Call `QueryRumWebMetric`
  - `Metric`: `performance`
  - `GroupBy`: `["from"]` (group by page URL)
  - `Limit`: `100`
- **Analysis Focus**:
  - Combine LCP values and request counts to find pages with highest LCP and greatest impact
  - LCP (Largest Contentful Paint) is the key page performance indicator
  - Record TOP 5-10 worst-performing pages

### Step 3: Analyze Detailed Performance Metrics per TOP Page
- **Goal**: Understand performance breakdown for each TOP page
- **Action**: For each TOP page, call `QueryRumWebMetric`
  - `Metric`: `performance`
  - `Filters`: `[{"Key":"from","Operator":"=","Value":"<specific_page_URL>"}]`
  - `Limit`: `100`
  - No GroupBy (get overall metrics)
- **Key Metrics**:
  - `lcp_avg`: LCP average
  - `fcp_avg`: FCP average
  - `dns_avg`: DNS lookup time
  - `tcp_avg`: TCP connection time
  - `ssl_avg`: SSL handshake time
  - `ttfb_avg`: TTFB time
  - `content_download_avg`: Content download time
  - `dom_parse_avg`: DOM parse time
  - `resource_download_avg`: Resource download time
  - `fmp_avg`: First meaningful paint time

### Step 4: Diagnose Performance Bottleneck Type
- **Goal**: Determine the main performance bottleneck for each TOP page
- **Analysis Logic**:
  - **Network layer slow**: If DNS, TCP, SSL times are high → Execute Step 5 (region & ISP analysis)
  - **Resource loading slow**: If resource download time is high → Execute Step 6 (resource analysis)
  - **Content rendering slow**: If DOM parse, content download times are high → Skip to recommendations (Step 8)

### Step 5: Network Layer Analysis (If DNS/TCP/SSL Slow)
- **Goal**: Determine if specific regions or ISPs cause network slowness
- **Operation A - By Region**:
  - `Metric`: `performance`
  - `Filters`: `[{"Key":"from","Operator":"=","Value":"<specific_page_URL>"}]`
  - `GroupBy`: `["region"]`
  - `Limit`: `100`
- **Operation B - By ISP**:
  - `GroupBy`: `["isp"]`
  - `Limit`: `100`
- **Analysis Focus**: Identify regions/ISPs with abnormally high DNS/TCP/SSL times

### Step 6: Resource Loading Analysis (If Resource Download Slow)
- **Goal**: Find specific slow-loading resources
- **Action**: Call `QueryResourceByPage`
  - `ProjectId`: Application ID
  - `From`: Specific page URL
  - Time range: Consistent with previous queries
- **Analysis Focus**:
  - `duration_avg`: Average resource loading time
  - `connect_time_avg`: Connection time
  - `domain_lookup_avg`: Domain lookup time
  - `transfer_size_avg`: Transfer size (negative means cross-origin prevents retrieval; suggest configuring `Timing-Allow-Origin`)
  - `error_rate_percent`: Resource loading error rate
  - Sort by duration to find TOP slow resources

### Step 7: Multi-Dimensional Resource Analysis (For Slow Resources)
- **Goal**: Analyze if slow resources correlate with region, ISP, etc.
- **Operation A - By Region**: `GroupBy`: `["region"]`
- **Operation B - By ISP**: `GroupBy`: `["isp"]`
- **Operation C - By Platform**: `GroupBy`: `["platform"]`
- **Note**: Run separate GroupBy queries for each dimension

### Step 8: Output Comprehensive Analysis Report
- **Output**:
  1. **TOP Performance Problem Pages** (sorted by LCP descending)
     - Page URL, LCP average, breakdown timing data
  2. **Performance Bottleneck Diagnosis per TOP Page**
     - Main bottleneck type (network/resource/rendering)
     - Specific bottleneck metrics and values
     - Network issues: affected regions and ISPs
     - Resource issues: slow resource list with timings
  3. **Performance Problem Distribution**
     - Platform distribution (iOS/Android/PC)
     - Browser distribution
     - Version distribution
     - Regional distribution
  4. **Optimization Recommendations** (per bottleneck type)
     - **DNS**: DNS prefetch, CDN acceleration
     - **TCP/SSL**: Enable HTTP/2, connection reuse, optimize SSL config
     - **Resource Loading**: Compress resources, use CDN, lazy loading, optimize sizes
     - **DOM Rendering**: Reduce DOM depth, optimize critical rendering path, code splitting
     - **Content Download**: Enable Gzip/Brotli, optimize above-the-fold resources
     - **Regional**: Add CDN edge nodes for slow regions, optimize routing
     - **ISP**: Multi-line access, coordinate with specific ISPs

---

## Flow 3: TOP API Performance & Stability Analysis

### Step 1: Get RUM Application Info
- **Goal**: Determine the RUM application ID to analyze

### Step 2: Query API Overview Metrics
- **Goal**: Understand overall API request health
- **Action**: Call `QueryRumWebMetric`
  - `Metric`: `network`
  - No GroupBy (get overall metrics)
  - `Limit`: `100`
- **Analysis Focus**:
  - `allCount`: Total API request count
  - `duration_avg`: Average API latency
  - `error_rate_percent`: Status code error rate
  - `retcode_error_percent`: Retcode error rate
  - Initial assessment: performance issue vs. stability issue

### Step 3: Analyze TOP Slow APIs (Performance Dimension)
- **Goal**: Find APIs with highest latency
- **Action**: Call `QueryRumWebMetric`
  - `Metric`: `network`
  - `GroupBy`: `["url"]` (group by API URL)
  - `Limit`: `100`
- **Analysis**: Sort by `duration_avg`, identify TOP 5-10 slowest APIs with URL, latency, count, error rate

### Step 4: Analyze TOP Error APIs (Stability Dimension)
- **Operation A - By Error Rate**:
  - `Metric`: `network`
  - `GroupBy`: `["url"]`
  - `Limit`: `100`
- **Operation B - By Status Code**:
  - `Metric`: `network`
  - `GroupBy`: `["url", "status"]`
  - `Limit`: `100`
- **Analysis**: Identify high error rate APIs, analyze HTTP status code distribution (4xx, 5xx), distinguish status code vs. retcode errors

### Step 5: Multi-Dimensional Analysis of TOP APIs
- **Goal**: Understand distribution patterns to locate root causes
- **Action**: For each TOP problem API:
  - **A. By Region**: `GroupBy`: `["region"]`
  - **B. By ISP**: `GroupBy`: `["isp"]`
  - **C. By Platform**: `GroupBy`: `["platform"]`
  - **D. By Version**: `GroupBy`: `["version"]`
  - **E. By Page Source**: `GroupBy`: `["from"]`
- **Note**: Run separate GroupBy queries for each dimension

### Step 6: Analyze Retcode Business Errors (If Present)
- **Goal**: Deep dive into business return code errors
- **Action**: For APIs with high retcode error rate:
  - `Metric`: `network`
  - `Filters`: `[{"Key":"url","Operator":"like","Value":"<specific_API_URL>"},{"Key":"is_err","Operator":"=","Value":"1"}]`
  - `GroupBy`: `["ret"]` (group by return code)
  - `Limit`: `100`
- **Analysis**: Identify specific error codes, count occurrences and proportions

### Step 7: Query TOP API Detailed Logs
- **Goal**: Get detailed request logs for problem APIs
- **Action**: For each TOP problem API, call `QueryRumWebLog`
  - `Filters`:
    - By API: `[{"Key":"msg","Operator":"like","Value":"<API_URL>"}]`
    - For error analysis, add level filter: `[{"Key":"level","Operator":"in","Value":"('16','1024')"}]` (AJAX_ERROR and RET_ERROR)
  - `Limit`: `10`
  - `RespFields`: Based on analysis needs
- **Analysis**: Review error stacks, request params, user environment, network state, check `trace` field for APM correlation

### Step 8: APM Deep Analysis (If Applicable)
- **Trigger**: Log `trace` field is non-empty
- **Action**:
  1. Call `QueryApmLinkId` to get linked APM application ID
  2. Follow "APM Trace Analysis Steps" in apm_analysis.md

### Step 9: Output Comprehensive Analysis Report
- **Output**:
  1. **TOP API Problem List**
     - **TOP Slow APIs** (by avg latency desc): URL, avg latency, count, error rate
     - **TOP Error APIs** (by error rate/count desc): URL, status code error rate, retcode error rate, main error codes, count
  2. **Root Cause Analysis per TOP API**
     - Performance root cause
     - Stability root cause: error types, specific error codes, occurrence scenarios, backend service errors, affected user characteristics
  3. **Problem Distribution**: Regional, ISP, platform, version, page distribution
  4. **Optimization Recommendations**
     - **API Latency**: Backend optimization, request merging, caching, CDN, network routing for slow regions
     - **Status Code Errors**: 4xx — check frontend validation & permissions; 5xx — backend stability & capacity; Network errors — adjust timeouts & retry
     - **Retcode Business Errors**: Strengthen frontend validation, optimize user guidance, improve business logic, friendlier error messages
     - **Regional/ISP**: Deploy edge nodes, multi-line access, smart routing

---

## Flow 4: TOP Slow Resource Loading Analysis

### Step 1: Get RUM Application Info
- **Goal**: Determine the RUM application ID to analyze

### Step 2: Query Static Resource Overview Metrics
- **Goal**: Understand overall static resource loading health
- **Action**: Call `QueryRumWebMetric`
  - `Metric`: `resource`
  - `GroupBy`: `["url"]` (group by resource URL)
  - `Limit`: `100`
- **Analysis Focus**:
  - `allCount`: Total resource request count
  - `duration_avg`: Average resource loading time
  - `error_rate_percent`: Resource loading error rate
  - Rank by `duration_avg` and `allCount` to identify high-impact slow resources

### Step 3: Identify TOP Slow Resources
- **Goal**: Find resources with highest loading time
- **Output**:
  - TOP 10-20 slowest resource URLs
  - Per resource: avg duration, count, error rate, connection time, domain lookup time, transfer size

### Step 4: Multi-Dimensional Analysis of TOP Slow Resources
- **Goal**: Understand distribution patterns to locate root causes
- **Action**: For each TOP slow resource:
  - **A. By Region**:
    - `Metric`: `resource`
    - `Filters`: `[{"Key":"url","Operator":"=","Value":"<specific_resource_URL>"}]`
    - `GroupBy`: `["region"]`
    - `Limit`: `100`
  - **B. By ISP**: `GroupBy`: `["isp"]`
  - **C. By Platform**: `GroupBy`: `["platform"]`
  - **D. By Network Type**: `GroupBy`: `["net_type"]`
- **Note**: Run separate GroupBy queries for each dimension

### Step 5: Diagnose Specific Bottlenecks for Slow Resources
- **Analysis Logic** (based on Step 3 and Step 4 data):
  - **Network layer slow**:
    - High `connect_time_avg` → TCP/SSL handshake slow
    - High `domain_lookup_avg` → DNS resolution slow
    - Root cause: Network quality issues, specific region/ISP problems
  - **Transfer layer slow**:
    - High `duration_avg` but normal `connect_time_avg` and `domain_lookup_avg`
    - Large `transfer_size_avg` (note: negative means cross-origin prevents retrieval)
    - Root cause: Oversized resources, insufficient bandwidth, CDN not deployed or misconfigured

### Step 6: Query Slow Resource Logs (Optional)
- **Goal**: Get specific resource loading logs for anomaly analysis
- **Action**: Call `QueryRumWebLog`
  - `Filters`:
    - `[{"Key":"msg","Operator":"like","Value":"<resource_URL>"}]`
    - For slow resource requests: `[{"Key":"level","Operator":"eq","Value":"1029"}]` (SLOW_ASSET_REQUEST)
    - For resource errors: `[{"Key":"level","Operator":"eq","Value":"1028"}]` (ASSERT_REQUEST)
  - `Limit`: `10`
  - `RespFields`: Based on analysis needs
- **Analysis**: Resource loading failure scenarios, user environment, network state, specific error messages

### Step 7: Output Comprehensive Analysis Report
- **Output**:
  1. **TOP Slow Resources** (sorted by avg duration descending)
     - Resource URL, avg loading time, count, transfer size, connection time, domain lookup time, error rate
  2. **Root Cause Analysis per TOP Slow Resource**
  3. **Severity Assessment**: Occurrence count, impact on overall page performance
  4. **Optimization Recommendations** (per problem type)
     - **Network Layer**: DNS prefetch (`<link rel="dns-prefetch">`), HTTP/2 or HTTP/3, optimize SSL, add CDN edge nodes for slow regions
     - **Transfer Layer**: Compress (Gzip/Brotli), image optimization (WebP, lazy loading, responsive images), code splitting & on-demand loading, CDN acceleration, resource merging (CSS Sprites, inline small resources)
     - **Cross-Origin Configuration**: Add `Timing-Allow-Origin: *` to resource server response headers, verify resource domain configuration
     - **Caching**: Set proper cache policies (Cache-Control), browser cache & Service Worker, CDN cache configuration
     - **Regional/ISP**: Deploy more CDN edge nodes for slow regions, multi-line access, smart DNS resolution

---

## Common Query Examples

### List Applications

```json
// View all applications (returns up to 50)
Tool: QueryRumWebProjects
Params: {}

// Verify existence by ProjectId (Scenario A)
Tool: QueryRumWebProjects
Params: {"ProjectId": "123456"}

// Exact match by app name (Scenario B, step 1)
Tool: QueryRumWebProjects
Params: {"ProjectName": "my-app"}

// Fuzzy search by name (Scenario B, step 2)
Tool: QueryRumWebProjects
Params: {"ProjectNameLike": "my-app"}
```

### Network Request Metrics

```json
// API request overview
Tool: QueryRumWebMetric
Params: {
    "ProjectId": "123456",
    "Metric": "network",
    "Limit": 100
}

// Group by API URL for latency analysis
Tool: QueryRumWebMetric
Params: {
    "ProjectId": "123456",
    "Metric": "network",
    "GroupBy": ["url"],
    "Limit": 100
}
```

### Exception Queries

```json
// All exception types overview
Tool: QueryRumWebMetric
Params: {
    "ProjectId": "123456",
    "Metric": "exception",
    "GroupBy": ["level"],
    "Limit": 100
}

// TOP JS/Promise errors
Tool: QueryRumWebMetric
Params: {
    "ProjectId": "123456",
    "Metric": "exception",
    "Filters": [{"Key": "level", "Operator": "in", "Value": "('4','8')"}],
    "GroupBy": ["error_msg"],
    "Limit": 100
}
```

### Page Performance Queries

```json
// Performance by page
Tool: QueryRumWebMetric
Params: {
    "ProjectId": "123456",
    "Metric": "performance",
    "GroupBy": ["from"],
    "Limit": 100
}
```

### Log Searches

```json
// Error logs
Tool: QueryRumWebLog
Params: {
    "ProjectId": "123456",
    "Limit": 10,
    "Filters": [
        {"Key": "level", "Operator": "in", "Value": "('4','8','16','32')"}
    ],
    "RespFields": ["ts", "level", "errorMsg", "from", "msg", "version", "os", "trace"]
}

// API-related logs by URL
Tool: QueryRumWebLog
Params: {
    "ProjectId": "123456",
    "Limit": 10,
    "Filters": [
        {"Key": "msg", "Operator": "like", "Value": "api.example.com"}
    ],
    "RespFields": ["ts", "level", "msg", "from", "trace"]
}

// Logs for a specific user
Tool: QueryRumWebLog
Params: {
    "ProjectId": "123456",
    "Limit": 50,
    "Filters": [
        {"Key": "uin", "Operator": "eq", "Value": "user_12345"}
    ]
}
```

### Query Resources by Page

```json
Tool: QueryResourceByPage
Params: {
    "ProjectId": "123456",
    "From": "https://example.com/home"
}
```

### APM Correlation

```json
Tool: QueryApmLinkId
Params: {
    "ProjectId": "123456"
}
```


path: references/apm_analysis.md
content: # APM Correlation Analysis Guide

## Trigger Conditions

When queried logs are related to API requests and the `trace` field is non-empty, correlate with APM data:
1. Call `QueryApmLinkId` to get the linked APM project ID
2. Follow the APM Trace Analysis Steps below

---

## APM Trace Analysis Steps

1. Use `DescribeGeneralSpanTree` to query **error spans** for the trace_id
2. Use `DescribeGeneralSpanTree` to query **slow spans** for the trace_id
3. If the slow span contains a LogTopicID, use `DescribeGeneralSpanTree` to query **log information** for the trace_id. If no LogTopicID exists, proceed to next step
4. Look up APM-Span attribute definitions and extract key Span attributes from the trace:
   - If DB and CVM attributes exist, extract the IP portion of `db.ip` or `cvm.instance.id` and use `GetMonitorData` to query related instance monitoring metrics
   - If TKE attributes exist, extract `k8s.cluster.id` and `k8s.node.ip` and use `GetMonitorData` to query K8sPodRateCpuCoreUsedNode and K8sPodRateMemUsageNode metrics
5. Comprehensive analysis:
   - **Error spans**: Focus on `error` and `exception` prefixed attributes; analyze root cause span, error content, error machine, error reason
   - **Slow spans**: Analyze where latency occurs (specific span processing too long, errors within spans, excessive time between span calls, etc.)
   - Determine if issues correlate with instance monitoring metrics

---

## DescribeGeneralSpanTree Parameter Guide

### Input Rules

- Choose `span_status` based on application state: use SLOW for warnings, ERROR for exceptions
- **Do NOT query full trace data** — do NOT set `span_status` to UNSET
  - Why: Full trace data is too large, will overflow context and hinder analysis
- Choose `scene_type` based on user's question: ERR for errors, SQL for database, MQ for message queue, NORMAL for others
- If there is no specific focus target, do NOT set `scene_type`
- When `scene_type` is not NORMAL, `object` is required (specifying the focus target)
- When using `DescribeGeneralSpanTree`, the time range can be expanded to ±1 hour around the target request time

### Usage Scenarios

| Scenario | Input | Output |
|----------|-------|--------|
| Query application details | Required params, region, app name | A random error/slow trace from the application |
| Query endpoint details | Required params, region, business system ID, app name, endpoint name | An error/slow trace from the endpoint |
| Analyze specific error type/DB/MQ | Required params, region, dimension info, scene_type, object | Trace info for specified error/anomaly (submit ERROR and SLOW separately) |
| Query trace logs | Required params, region, trace_id, span_status=LOG, object=LogTopicID | Log info for the trace (requires both trace_id and LogTopicID) |

---

## DescribeSpanTagList Parameter Guide

| Scenario | Filter Key |
|----------|-----------|
| Query by HTTP info | `http.route` (request path), `http.request.method` (method), `http.response.status_code` (status code) |
| Query by RPC info | `rpc.method` (callee method), `rpc.service` (callee service), `network.peer.address` (peer address), `network.peer.port` (peer port) |

---

## Log Level Enum Values

| Value | Description |
|-------|-------------|
| `1` | API_RESPONSE - All API requests (whitelisted or default reporting) |
| `2` | INFO - General information log |
| `4` | ERROR - Error log |
| `8` | PROMISE_ERROR - Promise error |
| `16` | AJAX_ERROR - AJAX error |
| `32` | SCRIPT_ERROR - JS loading error |
| `64` | IMAGE_ERROR - Image loading error |
| `128` | CSS_ERROR - CSS loading error |
| `256` | CONSOLE_ERROR - Console error |
| `512` | MEDIA_ERROR - Media resource error |
| `1024` | RET_ERROR - API return code error |
| `1025` | PAGE_LOAD - Page load |
| `1026` | SLOW_PAGE_LOAD - Slow page load |
| `1027` | SLOW_NET_REQUEST - Slow network request |
| `1028` | ASSERT_REQUEST - Resource request |
| `1029` | SLOW_ASSET_REQUEST - Slow resource request |
| `1032` | BLANK_SCREEN - Blank screen error |
| `2048` | REPORT - Same as ERROR, triggers alert but does not deduct score |

## RUM Supported Regions

- `ap-guangzhou` (default)
- `ap-singapore`
- `na-siliconvalley`


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)