MCPInstall

alibabacloud-sls-query

Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL scan/pipeline statements through the aliyun CLI. Triggers: "SLS 查询", "SLS 分析", "日志查询", "日志分析", "log query", "analyze sls logs", "aliyun log query".

Installs
2K
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-sls-query
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads alibabacloud-sls-query automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Alibaba Cloud SLS Query & Analysis

Scenario Description

Use this skill when the user wants to:

  • Explain, rewrite, optimize or execute an existing query
  • Translate a natural-language requirement into an SLS index query, SQL, or SPL statement

Prerequisites

Install Aliyun CLI

Run aliyun version to verify if version >= 3.3.8. If not installed or outdated, follow the doc references/cli-installation-guide.md to install or update.

Update Plugins

aliyun plugin update

Check Alibaba Cloud credentials configured

Run aliyun configure list to check if credentials configured. If no valid profile is shown, STOP here and ask the user to run aliyun configure outside of this session.

Security rules:

  • NEVER read, echo, or print AK/SK values
  • NEVER ask the user to paste AK/SK into the conversation
  • ONLY use aliyun configure list to check credential status

RAM Permission Requirements

APICLIActionPurpose
GetLogsV2get-logs-v2log:GetLogStoreLogsRun query / SQL / SPL and read results
GetIndexget-indexlog:GetIndexRead index config to verify prerequisites

For the minimum and complete RAM policy JSON, see references/ram-policies.md.

Permission failure handling: If a call returns Unauthorized permission error, stop and surface references/ram-policies.md to the user. Do not retry with a different account without explicit user confirmation.


Observability (MUST follow for every aliyun api command)

Upon loading this skill, generate a random session ID (32-char lowercase hex string) once for the entire session. Use it as {session-id} below.

Rule: Every aliyun CLI command that calls a cloud API MUST include the --user-agent flag. Local utility commands (e.g. configure, plugin, version) do not support this flag and should be excluded.

--user-agent "AlibabaCloud-Agent-Skills/alibabacloud-sls-query/{session-id}"

Example (assuming session-id is a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6):

aliyun sls get-logs-v2 --project my-project --logstore my-logstore \
  --from 1740000000 --to 1740003600 --query '*' \
  --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-sls-query/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6"

Do not skip, alter the format, or omit --user-agent on any aliyun API command invocation.


Core Workflow

  1. Read index configuration (GetIndex)
  2. Pick query mode
  3. Build statement
  4. Resolve time range
  5. Execute query
  6. Extract data from response
  7. Present CLI command and results

Step 1: Read the Index Configuration (Mandatory)

Always call get-index first — the index config decides which query modes are available in Step 2.

aliyun sls get-index \
  --project <project> --logstore <logstore>

Two sections in the response drive every later decision:

SectionMeaning
lineFull-text index — absence means full-text search is disabled
keysField indexes — map of field → { type, doc_value, token, caseSensitive, chn, ... }. doc_value: true means statistics are enabled on that field

If the call returns IndexConfigNotExist (HTTP 404), or the response has neither line nor keys populated, the Logstore has no index at all — stop immediately and tell the user they must create an index before any query / SQL / SPL can run.

  • The response can be large — extract only the fields relevant to the current query. Cache per logstore and reuse within the session.

For field types, tokenization, and how get-index maps to capabilities, see references/related-apis.md and references/query-analysis.md.


Step 2: Pick the Query Mode (Critical)

The query statement takes one of the following forms:

PriorityModeStatement FormUse whenRequires
1Index search<index-search>Filtering raw logs; return time-ordered and paginated logsFull-text (line) or any field index (keys.<field>)
2SQL<index-search> | <SQL>Aggregation, GROUP BY, sort, window, top-N, projection, and other analytical operationsTarget field has keys.<field> with doc_value: true
3SQL scan<index-search> | <SQL scan>User requestedNone
4SPL<index-search> | <SPL>User requestedNone

Selection rule:

  • Always prefer Index search for fastest speed.
  • Use Index search + SQL when the user needs analytical operations or field projection rather than full raw-log retrieval, such as aggregation, GROUP BY, sorting, window analysis, top-N, or returning only the required fields/columns.
  • Do not proactively choose SQL scan or SPL; use them only when the user explicitly requests.

For the full decision guide, see references/query-analysis.md.


Step 3: Write the Statement

3.1 Build the index-search segment first (left of |)

Collect every filter that can be expressed in index-search syntax and place it before the first |. Use * if no filter applies.

* and "payment failed" and status: "500" and not path: "/healthz"
  • * matches all; "..." is full-text (needs full-text index).
  • key: "value" is a field filter (needs field index).
  • Combine with and / or / not; group with parentheses.
  • key: * means field exists. Range (>, >=, [a, b]) works only on long / double.

If the requirement can be fully answered without aggregation or row-level processing, stop here — this is already a complete index search. For full index-search syntax, see references/query-analysis.md.

3.2 Append SQL — for aggregation / analytics

status: 500 | SELECT date_trunc('minute', __time__) AS minute,
                    count(*) AS errors
              FROM log
              GROUP BY minute
              ORDER BY minute
  • Read references/query-analysis.md for Query & SQL rules
  • Table name is log (recommended to omit).
  • SQL respects the indexed field type from get-index — a long / double field can be compared directly (status >= 500). Cast only when a field is indexed as text but numeric semantics are needed (try_cast to suppress errors).
  • Read references/functions-guide.md for unusual Function selection (aggregate, JSON, regex, datetime, IP geo …)

3.3 Append SPL — for row-level processing / flexible filtering

status: 500 and service: payment
| where try_cast(latency as BIGINT) > 1000
| extend latency_ms = try_cast(latency as BIGINT)
| project service, latency_ms, message

For SPL syntax, pipeline commands, and field-handling rules, read references/spl-guide.md.

3.4 Append SQL scan — fallback when the target field has no index / statistics

Syntax follows regular SQL (see 3.2), with one difference: every field is varchar, so always cast() / try_cast() before numeric comparison or arithmetic. See references/query-analysis.md for scan semantics.

* | set session mode=scan; SELECT api, count(1) AS pv FROM log GROUP BY api

Step 4: Resolve the Time Range

Generate --from / --to as Unix timestamps in seconds before building the CLI command. --from is inclusive and --to is exclusive.

Choose one of three input patterns:

  1. Relative time — user says "recent / last N minutes|hours|days".
  2. Natural-language absolute time without timezone — normalize to YYYY-MM-DD HH:MM:SS, then parse using the machine's local timezone.
  3. Absolute time with explicit timezone — parse using the customer-provided timezone or UTC offset.

1. Relative time

# recent 15 minutes
FROM=$(($(date +%s) - 900))
TO=$(date +%s)

2. Natural-language absolute time without timezone

If the user gives a date/time but no timezone, use the machine's local timezone. First normalize natural language such as 2026年3月13日12点 to 2026-03-13 12:00:00, then parse it as local time.

# Example: 2026年3月13日12点 -> 2026-03-13 12:00:00

# Linux (GNU date): local timezone
FROM=$(date -d "2026-03-13 12:00:00" +%s)

# macOS (BSD date): local timezone
FROM=$(date -j -f "%Y-%m-%d %H:%M:%S" "2026-03-13 12:00:00" +%s)

For a time range such as "2026年3月13日12点到13点", compute both endpoints the same way. For a single point-in-time request, infer a practical window from the user's intent; if unclear, ask for the range before executing.

3. Absolute time with explicit timezone

To convert a local date/time to a Unix timestamp: parse the input as UTC with date -u, then subtract the timezone's UTC offset in seconds.

Formula: unix_ts = date_utc_parse(input) − (UTC_offset_hours × 3600)

# Example: 2025-01-15 10:30:00 Beijing Time (UTC+8)
# Beijing is UTC+8, so subtract 8 × 3600 = 28800

# Linux (GNU date)
FROM=$(( $(date -u -d "2025-01-15 10:30:00" +%s) - 28800 ))

# macOS (BSD date)
FROM=$(( $(date -u -j -f "%Y-%m-%d %H:%M:%S" "2025-01-15 10:30:00" +%s) - 28800 ))
# Example: 2025-01-15 10:30:00 New York Time (UTC-5)
# New York is UTC-5, so subtract -5 × 3600 = subtract -18000 = add 18000

# Linux (GNU date)
FROM=$(( $(date -u -d "2025-01-15 10:30:00" +%s) + 18000 ))

# macOS (BSD date)
FROM=$(( $(date -u -j -f "%Y-%m-%d %H:%M:%S" "2025-01-15 10:30:00" +%s) + 18000 ))

Common UTC offsets (value to subtract):

TimezoneUTC offset hoursSeconds to subtract
Beijing (UTC+8)+828800
Tokyo (UTC+9)+932400
London (UTC)00
New York (UTC-5)-5-18000

Step 5: Execute via get-logs-v2

Use aliyun sls get-logs-v2 to execute queries. Run aliyun help sls get-logs-v2 to see CLI parameter usage; read references/related-apis.md for detailed API parameter descriptions.

Required CLI flags:

  • --project: SLS project name
  • --logstore: Logstore name within the project
  • --from: Start of time range, Unix timestamp in seconds (inclusive)
  • --to: End of time range, Unix timestamp in seconds (exclusive)
  • --query: Statement built in Step 3

Pagination works differently depending on whether the statement has a |:

5.1 Index-search only — paginate with --offset / --line

aliyun sls get-logs-v2 \
  --project my-project --logstore my-logstore \
  --from 1740000000 --to 1740003600 \
  --query '* and "payment failed" and status: "500"' \
  --line 100 --offset 0 --reverse true
  • Pagination: --line is page size (1–100, required); --offset is the start row (optional, default 0).
  • Ordering: --reverse true returns newest first; default false is oldest first.

5.2 With SQL — paginate with LIMIT inside the statement

aliyun sls get-logs-v2 \
  --project my-project --logstore my-logstore \
  --from 1740000000 --to 1740003600 \
  --query 'status: "500" | SELECT request_uri, count(*) AS cnt FROM log GROUP BY request_uri ORDER BY cnt DESC LIMIT 20'
  • SQL default result cap is 100 rows. To get more results or paginate:
    • LIMIT count — raise the cap (e.g., LIMIT 500 returns up to 500 rows)
    • LIMIT offset, count — paginate (e.g., LIMIT 20, 20 for rows 21–40; LIMIT 40, 20 for rows 41–60). Max offset+count is 1000000.
    • Do not use LIMIT count OFFSET offset syntax — it is not supported. Always use LIMIT offset, count.
  • Ordering: use ORDER BY <field> DESC/ASC to sort.

Result completeness check: every response contains meta.progress. If it is Incomplete, re-issue the same request until it returns Complete.


Step 6: Extract Data from the Response

get-logs-v2 returns:

{
  "meta": { "progress": "Complete", "count": 10, ... },
  "data": [ { "field1": "value1", ... }, ... ]
}
FieldMeaning
meta.progressComplete or Incomplete (see Step 5)
meta.countNumber of rows returned
dataArray of log entries or aggregation rows; may contain __time__ (Unix seconds, string)

Use jq (preferred) or --cli-query (JMESPath) to extract the fields the user needs:

Extractjq--cli-query (JMESPath)
Data rows| jq '.data'--cli-query 'data'
Progress| jq '.meta.progress'--cli-query 'meta.progress'
Row count| jq '.meta.count'--cli-query 'meta.count'
Specific fields| jq '.data[] | {LogStore, read_mb}'--cli-query 'data[].{LogStore: LogStore, read_mb: read_mb}'

Step 7: Present the CLI Command and Results

CLI command — always show the full, copy-paste-ready aliyun sls get-logs-v2 ... command. Redact any AK/SK. If the query was not executed (write / explain scenario), present the command the user should run.

Results — when a query was executed, use Step 6 to extract data and format according to the user's request (table, list, summary, etc.). Append one sentence explaining the query mode choice.


Global Rules

  • Always prefer Index search for fastest raw-log retrieval, and use Index search + SQL for analysis or field projection.
  • When the user only needs specific fields, use SELECT to project them rather than fetching full raw logs — this reduces network overhead. Requires doc_value: true on the target fields (confirmed in Step 1).
  • Do not hard-code __time__ filters — pass time range via --from / --to.
  • Deprecated API: never call get-logs; always use get-logs-v2.

Troubleshooting

When the user reports "no data", "wrong result", or a CLI error, walk through the checklist in this exact order:

  1. Time range — wrong --from/--to? Milliseconds instead of seconds? Recent writes still indexing?
  2. Index configuration — field index missing? Full-text index off? Target field not in keys?
  3. Field type / statistics — range query on a text field? SQL on a field without doc_value?
  4. Syntax — mixed SQL and SPL? Leading * in fuzzy match? SPL string escaping?
  5. Mode choice — scanning when an index-based query would do? Aggregating in SPL instead of SQL?
  6. Completeness — meta.progress = Incomplete, caller did not retry (see Step 5).
  7. ProjectNotExist — region or endpoint is wrong. Use cross-region discovery to locate the project automatically, or ask the user to confirm the region. Before calling get-project --cross-region true, you MUST read the Cross-Region Discovery section in references/regions.md — this API is only available via cn-zhangjiakou.log.aliyuncs.com endpoint.
  8. Network failure (timeout, connection refused) — try switching to internal endpoint. See references/regions.md.

For the full catalog of failure modes and error codes, see references/troubleshooting.md and the Common Errors table in references/related-apis.md.


Reference Documents

DocumentDescription
references/query-analysis.mdMode decision, index-search / SQL rules, scan semantics
references/spl-guide.mdSPL pipeline syntax, common commands, field handling
references/functions-guide.mdFunction categories, SQL/SPL differences, templates
references/troubleshooting.md"No data / wrong result / error" playbook
references/related-apis.mdGetLogsV2 and GetIndex API & CLI reference
references/ram-policies.mdMinimum and complete RAM policies
references/cli-installation-guide.mdAliyun CLI install, auth modes, profiles
references/regions.mdRegion / endpoint configuration, internal endpoint, cross-region discovery (get-project --cross-region true, only cn-zhangjiakou)
references/acceptance-criteria.mdCLI invocation acceptance tests
references/query_analysis/*.yaml · references/spl/*.yaml · references/functions/*.yamlSource-of-truth YAMLs bundled with this skill

FAQ

What does the alibabacloud-sls-query skill do?

Alibaba Cloud SLS (Simple Log Service) log query & analysis skill. Use this skill to help users write, explain, optimize, execute, or troubleshoot SLS index search, SQL analytics, and SPL scan/pipeline statements through the aliyun CLI. Triggers: "SLS 查询", "SLS 分析", "日志查询", "日志分析", "log query", "analyze sls logs", "aliyun log query".

How do I install alibabacloud-sls-query?

Run npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-sls-query in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/alibabacloud-sls-query/ (personal) or .claude/skills/alibabacloud-sls-query/ (project).

Which AI agents can use alibabacloud-sls-query?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is alibabacloud-sls-query safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains alibabacloud-sls-query?

It is published by aliyun in aliyun/alibabacloud-aiops-skills. It has 2,049 recorded installs.

More from aliyun/alibabacloud-aiops-skills

View all →

alibabacloud-find-skills

aliyun/alibabacloud-aiops-skills

Use this skill when users want to search, discover, browse, or find Alibaba Cloud (阿里云) agent skills. Triggers include: "find a skill for X", "search alicloud skills", "阿里云有什么 skill","阿里云", "搜索阿里云技能", "有没有管理 ECS/RDS/OSS 的 skill", "阿里云 skills 有哪些类目", "帮我找一个 skill", "browse alicloud skills", "list alicloud skill categories", "is there an alicloud skill that can...", "what alicloud skills are available", "XX Skill 的内容是什么", "我想了解阿里云 XX Skill 具体做什么","帮我安装阿里云 Skill","使用阿里云相关的skill", "阿里云 agent skill 市场", "搜一下阿里云的 skill", "建一个数据分析项目有没有相关 skill".

AI & Agents2.2K installs

alibabacloud-dms-skill

aliyun/alibabacloud-aiops-skills

Alibaba Cloud DMS Database Read/Write Skill. Use this skill to search for target databases in DMS and execute SQL queries and data modifications. Triggers: "DMS query", "database query", "execute SQL", "search database", "DMS SQL", "insert data", "update data".

Data & Databases2.1K installs

alibabacloud-workbench-cli

aliyun/alibabacloud-aiops-skills

Agent-native CLI for managing ECS instances without public IPs, primarily for single-instance operations. It supports millisecond-level remote command execution, large file transfers up to 1GB, and TCP port forwarding. It offers four authentication modes: AK, RamRoleArn, CredentialsCmd, and CredentialsURI. Use it to run commands, deploy code, view logs, check processes, transfer files, set up port forwarding, or query and filter ECS instance lists.

DevOps & Cloud717 installs

alibabacloud-ecs-diagnose

aliyun/alibabacloud-aiops-skills

Comprehensive Alibaba Cloud ECS instance diagnostics skill. Performs systematic troubleshooting including cloud platform status checks and GuestOS internal diagnostics via Cloud Assistant. Use when users report server connectivity issues, SSH timeout, instance lag, website unavailability, disk full, CPU/memory alerts, system event notifications, or abnormal instance status. Triggers: "ECS", "instance", "server", "cannot connect", "SSH", "timeout", "slow", "disk full", "network", "CPU high", "memory high", "status check", "system event", "diagnose", "troubleshoot", "disk performance", "disk IO slow", "IOPS", "IO latency"

Backend & APIs686 installs

alibabacloud-cli-guidance

aliyun/alibabacloud-aiops-skills

Guide users to manage Alibaba Cloud resources using the Aliyun CLI command-line tool. Covers CLI installation, credential configuration, plugin management, command construction, and error troubleshooting. Use this skill when the user wants to operate Alibaba Cloud services from the terminal — including ECS (云服务器, cloud servers), Function Compute (函数计算, serverless), RDS (云数据库, databases), OSS (对象存储, object storage), SLS (日志服务, log service), VPC (专有网络, networking), ESS (弹性伸缩, auto scaling), and any other Alibaba Cloud product. Also use when the user mentions "aliyun", "阿里云", "阿里云CLI", "命令行", asks about CLI plugin installation, encounters Aliyun CLI errors (InvalidAccessKeyId, SignatureDoesNotMatch, Throttling), or needs help constructing aliyun commands with correct parameter syntax.

585 installs

alibabacloud-ram-permission-diagnose

aliyun/alibabacloud-aiops-skills

Alibaba Cloud RAM permission diagnosis and repair assistant. When an agent encounters any permission-related error while operating Alibaba Cloud resources (403, NoPermission, Forbidden, AccessDenied, InvalidSecurityToken, etc.), or when the user describes an Alibaba Cloud RAM permission issue, use this skill immediately. Do not wait for the user to explicitly request it — proactively start the diagnostic process whenever a permission error appears. Also applies when: a developer encounters permission issues while writing Alibaba Cloud SDK code, the user asks how to configure minimum permissions for an operation, or the user wants to know which permissions the current identity is missing.

Docs & Writing552 installs

Popular data & databases skills

View category →

Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pgcron, pgmq), vector/semantic search (pgvector), and restoring dumps (pgrestore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.

OfficialData & Databases462.2K installs

prisma-client-api

prisma/skills

Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".

OfficialData & Databases393.5K installs

Deprecated compatibility name for prisma-orm-setup. Use only when a user or existing integration explicitly invokes prisma-database-setup; otherwise select prisma-orm-setup.

OfficialData & Databases392.3K installs

prisma-cli

prisma/skills

Prisma ORM 7 CLI reference for existing Prisma 7 applications or explicitly selected Prisma 7 workflows. Covers prisma init, generate, migrate, db, dev, studio, and mcp. For setup, connection repair, or Prisma 8, use prisma-orm-setup; not the Prisma Platform CLI.

OfficialData & Databases390.8K installs

prisma-postgres

prisma/skills

Deprecated compatibility name for prisma-postgres-setup. Use only when a user or existing integration explicitly invokes prisma-postgres; otherwise select prisma-postgres-setup.

OfficialData & Databases384.4K installs

Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.

OfficialData & Databases378.9K installs