Cortex Code CLI 可扩展性

Cortex Code CLI 可以通过自定义行为、专用代理、生命周期 hook 以及外部工具集成进行扩展。本主题介绍四种主要的可扩展机制:

Skills

将特定领域的知识和指令注入对话中的 Markdown 文件。使用 Skills 向 Cortex Code 传授您组织的最佳实践、编码规范或专业化工作流程。

Subagents

自主且专业化的 AI 代理,可独立处理特定任务。Subagents 支持并行执行、专注化的专业能力以及复杂的多步骤工作流程。

Hooks

在关键生命周期阶段拦截并自定义 Cortex Code 行为的脚本。使用钩子验证工具输入、记录操作或强制执行策略。

MCP (Model Context Protocol)

一种开放标准,用于将 Cortex Code 连接到外部工具和数据源,例如 GitHub、Jira 和数据库。

Skill

Skill 通过注入专门指令并启用附加工具,以特定领域的知识和能力扩展 Cortex Code。

什么是 Skill?

Skill 是包含以下内容的 Markdown 文件:

  • 特定领域的指令和最佳实践
  • 何时利用 Skill
  • 示例工作流程
  • 可选工具配置

当您调用某个 Skill 时,其指令会被注入到对话上下文中。

使用 Skill

Run /skill list to list available skills, and invoke them by name to load the skill into the conversation.

Skill 位置

Skill 从多个位置加载,下面按优先级从高到低列出:

位置路径范围
项目.cortex/skills/ or .claude/skills/项目
用户~/.snowflake/cortex/skills/ or ~/.claude/skills/用户
全局~/.snowflake/cortex/skills/系统
会话临时添加会话
远程克隆自 Git缓存
捆绑内置于 Cortex Code系统

For a complete reference of all bundled skills and how to use them, see Cortex Code CLI bundled skills.

创建自定义 Skill

Skills are directories containing a SKILL.md file with skill instructions, and optional examples and templates. You can create skills in one of the following locations:

范围路径
项目.cortex/skills/ or .claude/skills/ in the project directory
全局~/.snowflake/cortex/skills/
用户~/.claude/skills/

要开始构建自定义 Skill,请执行以下操作:

  1. 创建 Skill 目录。此示例在项目位置创建一个名为“my-skill”的 Skill 目录:

    mkdir -p .cortex/skills/my-skill
  2. Create SKILL.md in this directory and add skill instructions. This example shows the basic structure:

    ---
    name: my-skill
    description: Brief description of what this skill does
    tools:
    - optional_tool_name
    ---
    
    # When to Use
    
    - Describe when this skill should be invoked
    - List specific user intents or scenarios
    
    # What This Skill Provides
    
    Explain the capabilities and knowledge this skill adds.
    
    # Instructions
    
    Step-by-step guidance for the AI when this skill is active.
    
    ## Best Practices
    
    - Best practice 1
    - Best practice 2
    
    ## Common Patterns
    
    ### Pattern 1
    
    Description and example.
    
    ### Pattern 2
    
    Description and example.
    
    # Examples
    
    ## Example 1: Basic Usage
    
    User: $my-skill Do something Assistant: [Expected behavior]
    
    ## Example 2: Advanced Usage
    
    User: $my-skill Complex task with @file.txt Assistant: [Expected behavior]
  3. Verify that your skill appears in the listing using the $$ command:

    > $$

如果您的 Skill 出现在列表中,则说明其已正确加载并可供使用。

  1. 在对话中使用您的 Skill:
    > $my-skill Test it out

自定义 Skill 设置

Each skill’s options are defined in the YAML frontmatter at the top of SKILL.md. The following options are supported:

此示例展示了使用两种工具的 Skill:

---
name: database-admin
description: Database administration tasks
tools:
- snowflake_sql_execute
- snowflake_object_search
---

技能最佳实践

要编写高效的 Skill,请遵循以下准则:

  • 具体明确:清晰的指令可产生更好的效果
  • 提供示例:展示预期的输入和输出
  • 包括边缘情况:处理常见错误和异常
  • 保持专注:一个 Skill 等于一个领域或能力

管理 Skill

斜杠命令描述
/skill交互式 Skill 管理器
/skill list列出所有技能
/skill sync <name>同步到全局位置
/skill add <path>Add a skill from a local path, Git repository, tarball, or Snowflake stage

Skill 冲突

When the same skill exists in multiple supported locations, and the contents differ, a conflict occurs, and a conflict indicator appears in the skill listing. Use /skill sync to resolve conflicts by syncing the local scope to the global scope.

组合 Skill

自定义 Skill 可以引用其他 Skill,或将 Skill 与文件上下文相结合:

> $code-review Review @src/auth.py following $security-guidelines

Snowflake recommends sharing skills through either a Git repository or a Snowflake stage.

Git repositories

Use a Git repository when your team already stores versioned skills in Git. A repository can contain any number of skills. The layout should match the local skill structure.

/skill add https://github.com/org/my-skills.git

Git-based skills are cached locally.

Snowflake stages

Use a Snowflake stage when you want to distribute skills through Snowflake and control access with Snowflake roles. Publish one or more local skills to a stage, let users add skills directly from that stage, or publish a profile that references the same shared stage.

cortex skill publish ./my-skills --to-stage @MY_DB.MY_SCHEMA.MY_STAGE/skills/
cortex skill add @MY_DB.MY_SCHEMA.MY_STAGE/skills/
cortex profile publish data-analyst --skill-stage @MY_DB.MY_SCHEMA.MY_STAGE/skills/

For internal stages, grant READ to users who load skills and WRITE to users who publish them. To grant WRITE, grant READ first. For more information, see GRANT <privileges> … TO ROLE and Managing Snowflake stages.

Snowflake Git repositories

To mirror an external Git repository into Snowflake, create a Snowflake Git repository and then add skills from the repository branch path that contains the skill files.

cortex skill publish --from-git https://github.com/org/my-skills.git \
  --to-repo MY_DB.MY_SCHEMA.MY_SKILLS_REPO
cortex skill add @MY_DB.MY_SCHEMA.MY_SKILLS_REPO/branches/main/

For setup requirements, see Setting up Snowflake to use Git and CREATE GIT REPOSITORY.

Skill 命令参考

CLI 命令:

cortex skill list
cortex skill add <path>
cortex skill update <source>
cortex skill publish [path] --to-stage <stage>
cortex skill publish --from-git <url> --to-repo <repo>
cortex skill remove <path>

斜杠命令:

/skill list
/skill add <path>

Skill 故障排除

Skill not activating
  • 使用与 Skill 目的相关的特定语言
  • 明确提及 Skill:“Use semantic-view-optimization”
  • Check availability: /skill list
Unexpected behavior
  • 提供有关目标的更多背景信息
  • 尝试更具体的请求
  • Submit feedback: /feedback

Subagent

Subagent 是自治的、专业化的 AI 代理,可独立处理特定任务。它们支持并行执行、专注的专业能力以及复杂的多步骤工作流程。

Subagent:

  • 独立于主对话执行
  • 拥有自己的上下文和工具访问权限
  • 可以在前台或后台运行
  • 专注于特定领域或任务

内置 Subagent 类型

general-purpose

可以访问所有工具的多用途代理。最适合:

  • 复杂的研究任务
  • 多步骤代码更改
  • 需要多种工具的任务

explore

快速代码库探索专家。最适合用于:

  • 按模式查找文件
  • 在代码中搜索关键字
  • 了解代码库结构
  • 快速侦察

您可以指定 Explore 代理的搜索深度:

  • "quick": Basic search
  • "medium": Moderate exploration
  • "very thorough": Comprehensive analysis

plan

设计并概述复杂的实施计划。最适合用于:

  • 设计实施策略
  • 识别关键文件
  • 评估架构权衡
  • 创建分步计划

feedback

结构化反馈收集。最适合用于:

  • 收集用户输入
  • 结构化问题
  • 会话反馈

运行 Subagent

Cortex Code 会在适当情况下自动委派给 Subagent。例如,此查询委托给 Explore 代理:

> Find all files that import the authentication module

您还可以按名称显式请求特定的 Subagent 类型:

> Use an Explore agent to find all database query definitions
> Use the Explore agent to find all API endpoint definitions
> Launch a Plan agent to design the authentication refactor

您还可以请求多个 Subagent 并行运行,以处理任务的不同方面:

> In parallel, search for all test files and all config files

代理可以在后台运行,同时您继续工作:

> Run a background agent to refactor all the test files

代理立即启动,并返回代理 ID 用于跟踪。代理完成后,您可以使用其 ID 获取输出:

> Get the output from agent abc1234

To monitor the status of all running subagents, use the /agents command (or press Ctrl-B) to open the background process viewer. You can stop a running agent using its ID, or with the /agents interface:

> kill agent abc1234

被终止的代理会停止运行,但其上下文会被无限期保留。您可以使用其 ID 恢复已终止的代理:

> Resume agent abc1234 and continue from where it left off

代理类型

Autonomous

自治代理无需用户交互即可运行。代理:

  • 独立完成
  • 不会阻塞提问
  • 适合明确定义的任务
Non-Autonomous

非自治代理可以暂停执行以向用户提问。代理:

  • 可能会提出澄清性问题
  • 可以交互式请求权限
  • 适合需要指导的任务
Custom

自定义代理是用户定义的 Subagent,具有专门的提示和配置。您可以在 Markdown 文件中创建针对特定领域或工作流程的代理,类似于自定义 Skill。

创建自定义 Subagent

自定义子代理在带有 YAML 前置信息的 Markdown 文件中定义。前置信息指定了代理的名称、描述、工具访问权限和模型。正文包含指导代理行为的系统提示。

您可以将自定义代理 Markdown 文件存储在以下三个位置之一:

ScopePath
Project.cortex/agents/ or .claude/agents/
Global~/.snowflake/cortex/agents/
User~/.claude/agents/

代理定义的格式如下所示:

---
name: my-agent
description: What this agent specializes in
tools:

- Bash
- Read
- Write

model: claude-sonnet-4-5
---

# System Prompt

You are a specialized agent for [domain].

## Your Responsibilities

1. Task 1
2. Task 2

## Guidelines

- Guideline 1
- Guideline 2

## Output Format

Describe expected output format.

示例:测试运行器代理

以下 Markdown 文件定义了一个自定义测试运行器代理,用于运行测试并汇总结果:

---
name: test-runner
description: Runs tests and reports results
tools:
- Bash
- Read
- Grep
---

# Test Runner Agent

You run tests and provide clear reports of the results.

## Process

1. Identify the test framework (pytest, jest, go test, etc.)
2. Run appropriate test command
3. Parse and summarize results
4. Highlight failures with relevant code context

## Output Format

## Test Results Summary

- Total: X
- Passed: Y
- Failed: Z

## Failures

### Test Name

- File: path/to/file.py
- Error: Description
- Relevant code snippet

代理配置

自定义代理的配置在 Markdown 文件的 YAML 前置信息中指定。

Tool access

代理可以指定可访问的工具:

tools:
- "*"           # All tools
- Bash          # Specific tools
- Read
- Write
Model selection

您可以为特定代理选择模型。这将替换会话的默认模型。

model: claude-sonnet-4-5   # Specific model
model: auto                # Cost-optimized

工作树隔离

Agents can be run in isolated git worktrees, or branches. When you request worktree isolation, Cortex Code CLI creates a separate git worktree for the agent to operate in. This allows multiple agents to run in parallel without conflicting changes, and is easy to clean up afterward. Isolated worktrees are particularly useful for exploration and experimentation. The git branch created by the agent is named agent/<agentId>.

要使用工作树隔离,只需在提示中包含它:

> Run a background agent with worktree isolation to implement feature X

蜂群模式

您可以启动一组代理并行处理复杂任务的不同方面。每个代理独立工作,所有代理完成后,结果会被汇总。所有类型的代理都可以参与蜂群模式。

蜂群的用例包括:

  • 代码分析:多个代理分析不同方面
  • 重构:并行代理处理不同文件
  • 测试:代理运行不同测试套件
  • 文档:代理记录不同组件

要创建蜂群模式,只需描述要启动的不同代理:

> Launch a swarm of agents:
> 1. Explore agent to find all database queries
> 2. Explore agent to find all API endpoints
> 3. Explore agent to find all test files

Subagent 最佳实践

将 Subagent 用于以下用途:

  • 复杂任务:分解为可并行执行的子任务
  • 探索:使用 Explore 代理进行代码库搜索
  • 规划:在重大变更之前使用 Plan 代理
  • 后台工作:不需要关注的长时间运行的任务

Subagent 可能不适合以下情况:

  • 简单查询:直接使用工具更快
  • 单文件编辑:主代理更高效
  • 交互式工作:当您需要即时反馈时

详细提示通常更有效:

良好查找包含数据库查询的所有 Python 文件,并按行号列出
更优使用 Explore 代理(非常彻底)查找所有包含数据库查询的 Python 文件。对于每个文件,提取查询模式并识别潜在的 SQL 注入风险。

查看活动 Subagent

/agents command

Issue the /agents command in a Cortex Code session to open the interactive agent viewer. This interface shows all running agents, their types, statuses, and output previews.

Background process viewer

在 Cortex Code CLI 会话中,按 Ctrl-B 可查看:

  • 所有后台进程
  • 代理会话
  • Bash 进程

代理限制

以下限制适用于 Cortex Code CLI 中的 Subagent:

  • 最多 50 个并发后台代理
  • 代理继承会话权限
  • 后台代理无法生成其他后台代理

Hook

Hook 允许您在生命周期关键点拦截并自定义 Cortex Code 的行为。Hook 是为响应事件而执行的提示或 Shell 脚本:

  • 使用工具之前:验证或修改工具输入
  • 使用工具之后:添加上下文或日志结果
  • 用户输入时:注入会话上下文
  • 会话事件发生时:初始化或清理

Hook 事件

以下事件可以触发 Hook:

事件描述可以阻止
PreToolUse工具执行前
PostToolUse工具执行后
PermissionRequest需要权限时
UserPromptSubmit用户提交提示时
SessionStart会话开始时
SessionEnd会话结束时
PreCompact上下文压缩之前
Stop用户停止 Claude 时
SubagentStopSubagent 停止时
通知系统通知时
设置初始化期间

配置 Hook

Hook 在设置文件中配置,这些文件可以位于任意配置目录(按优先级从高到低列出):

位置路径
本地.claude/settings.local.json or .cortex/settings.local.json
项目.claude/settings.json or .cortex/settings.json
用户~/.claude/settings.json
全局~/.snowflake/cortex/hooks.json

Hook 以 JSON 格式定义,指定事件、工具匹配器和 Hook 操作。下面显示了一个工具使用前 Hook 的简单示例:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "bash .claude/hooks/validate-bash.sh",
            "timeout": 60
          }
        ]
      }
    ]
  }
}

支持两种 Hook 类型:命令 Hook 和提示 Hook。

  • 命令 Hook 运行 Shell 命令或脚本。

    {
      "type": "command",
      "command": "bash /path/to/script.sh",
      "timeout": 60,
      "enabled": true
    }
  • 提示 Hook 被评估为语言模型的自然语言提示。

    {
      "type": "prompt",
      "prompt": "Is this command safe? $ARGUMENTS",
      "timeout": 30
    }

To execute your hook only on specific tools, place tool names or patterns in the matcher field. For example, to match all SQL tools, use "matcher": "SQL*". You can use regular expressions to match multiple tools.

模式匹配项
*所有工具
Bash仅 Bash
Edit|Write编辑或写入
mcp__.*所有 MCP 工具
Notebook.*NotebookEdit、 NotebookExecute

编写 Hook 脚本

Hook 脚本通过标准输入接收 JSON 输入,并通过标准输出返回 JSON 输出。输出中包含一个字段,用于指示操作是被允许还是被拒绝。(可选)Hook 脚本可以返回工具输入的修改版本。

示例输入:

{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript.json",
  "cwd": "/working/directory",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "ls -la"
  }
}

示例输出:

{
  "decision": "allow",
  "systemMessage": "Note: This operation was validated.",
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "updatedInput": {
      "command": "ls -la --color=never"
    }
  }
}

返回代码指示是否阻止操作:

  • 0:不阻止
  • 2:阻止

此信息也可以作为 JSON 输出的一部分返回,如下所示。

{
  "decision": "block",
  "reason": "Operation not allowed"
}

Hook 脚本中提供以下环境变量:

变量描述
CORTEX_PROJECT_DIR项目目录路径
CORTEX_CODE_REMOTE"true" if web context
CORTEX_ENV_FILE持久环境文件路径

Hook 示例

以下示例展示了常见 Hook 用例的可能输出。

修改工具输入

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "updatedInput": {
      "command": "modified command"
    }
  }
}

添加上下文

{
  "hookSpecificOutput": {
    "hookEventName": "PostToolUse",
    "additionalContext": "Note: File was recently modified."
  }
}

显示系统消息

{
  "systemMessage": "Warning: This operation may take a while."
}

权限决策

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "Auto-approved by policy"
  }
}

远程 Hook

您可以引用 Git 存储库中的脚本,如下所示:

{
  "type": "command",
  "command": "bash",
  "source": {
    "source": "github:org/hooks-repo/scripts/validate.sh",
    "ref": "main"
  }
}

Hook 最佳实践

  • 保持 Hook 快速:超时默认为 60 秒
  • 优雅地处理错误:如果不确定,则返回 exit 0
  • 用于调试的日志:写入文件以进行故障排除
  • 使用匹配器:针对特定工具,而非全部工具
  • 彻底测试:使用 Hook 管理器验证行为

模型上下文协议 (MCP)

您可以使用模型上下文协议 (MCP) 将 Cortex Code CLI 连接到外部工具和数据源。MCP 是用于将 AI 代理连接到外部工具(如 GitHub、Jira 和数据库)的开放标准。配置完成后, MCP 服务器使 Cortex Code 能够访问内置功能之外的托管工具。

传输类型

Cortex Code 支持三种 MCP 传输类型:

类型用例连接
stdio本地工具,CLI 包装器使用 stdin/stdout 的子进程
httpWeb 服务、APIsHTTP 请求
sse实时服务服务器发送的事件

You can use OAuth to authenticate to HTTP MCP servers. The first time you connect to a server configured for OAuth, Cortex Code CLI opens a browser window, where the user authenticates. The resulting token is stored in ~/.snowflake/cortex/mcp_oauth/ and automatically refreshed as needed. The following is a sample OAuth configuration:

{
   "oauth": {
      "client_id": "pre-registered-client-id",
      "client_name": "My Client",
      "redirect_port": 8585,
      "scope": "openid mcp read write",
      "authorization_server_url": "https://auth.example.com"
   }
}

管理 MCP 服务器

You can issue the /mcp command in an interactive Cortex Code CLI session to open an interactive MCP status viewer. Use the cortex mcp command to manage MCP server configurations from the command line.

命令描述
命令行Description
cortex mcp add添加新服务器(见下文)
cortex mcp list列出已配置的服务器
cortex mcp get <server>获取特定服务器的详细信息
cortex mcp remove <server>移除服务器
cortex mcp start <server>检查服务器状态和可用工具

添加服务器

The cortex mcp add command accepts options for configuring servers.

cortex mcp add <name> <command> [args...]

选项:

--transport, -t    Transport type (stdio, http, sse)
--type             Alias for --transport
--env, -e          Environment variable (KEY=value)
--header, -H       HTTP header
--timeout          Connection timeout in ms

Note

MCP 工具使用命名空间以避免冲突,格式如下:

mcp__{server-name}__{tool-name}

For example, a tool called search from server github is given the name mcp__github__search.

MCP 配置

MCP server configuration is stored in ~/.snowflake/cortex/mcp.json under the key mcpServers. The following example shows the structure of a configuration file with a single MCP server:

{
   "mcpServers": {
      "server-name": {
         "type": "stdio",
         "command": "command-to-run",
         "args": ["arg1", "arg2"]
      }
   }
}

环境变量

Use the ${VAR} or $VAR syntax to insert the values of environment variables into the configuration file.

{
"mcpServers": {
   "my-server": {
      "type": "http",
      "url": "https://api.example.com",
      "headers": {
      "Authorization": "Bearer ${MY_API_TOKEN}"
      }
   }
}

Important

It is a best practice to use environment variables for credentials. Never hardcode tokens in mcp.json. Add a line to your shell’s profile, such as ~/.bashrc or ~/.zshrc, like the following:

export GITHUB_TOKEN="your_token_here"

通过命令行进行配置

To add an MCP server from the command line, use the cortex mcp add command. For example:

操作命令
添加 stdio 服务器cortex mcp add git-server uvx mcp-server-git
添加 HTTP 服务器cortex mcp add api-server https://api.example.com --type http
通过环境变量添加cortex mcp add my-server npx my-mcp-server -e API_KEY=secret
通过标头添加cortex mcp add my-server https://api.example.com -H "Authorization: Bearer token"

使用 MCP 工具

配置完成后,MCP 工具会在 Cortex Code CLI 会话中自动可用。您可通过自然语言命令调用它们:

Show me recent GitHub pull requests
Create a Jira ticket for this bug
Query the PostgreSQL database for user activity

Permissions are requested on first use. Configure defaults in ~/.snowflake/cortex/permissions.json:

{
  "allow": ["mcp__github__read_file", "mcp__github__list_repos"],
  "deny": ["mcp__github__delete_repo"]
}

MCP 配置示例

以下示例展示了常见用例的 MCP 服务器配置。

Git 服务器 (stdio)

{
  "mcpServers": {
    "git": {
      "type": "stdio",
      "command": "uvx",
      "args": ["mcp-server-git", "--repository", "/path/to/repo"]
    }
  }
}

带 OAuth 的 HTTP API

{
  "mcpServers": {
    "my-api": {
      "type": "http",
      "url": "https://api.example.com/mcp",
      "oauth": {
        "client_id": "my-client-id",
        "redirect_port": 8585,
        "scope": "openid mcp"
      }
    }
  }
}

带标头的 SSE 服务器

{
  "mcpServers": {
    "realtime": {
      "type": "sse",
      "url": "https://realtime.example.com/events",
      "headers": {
        "Authorization": "Bearer ${API_TOKEN}",
        "X-Custom-Header": "value"
      },
      "timeout": 30000
    }
  }
}

Sourcegraph 集成

{
  "mcpServers": {
    "sourcegraph": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@sourcegraph/mcp-server"],
      "env": {
        "SRC_ACCESS_TOKEN": "${SOURCEGRAPH_TOKEN}",
        "SRC_ENDPOINT": "https://sourcegraph.company.com"
      }
    }
  }
}

MCP 故障排除

Server not connecting
  • Check /mcp during a session to make sure it is listed
  • Use cortex mcp start <server> to test connectivity
  • 确保在环境变量中正确设置凭据
  • cat ~/.snowflake/cortex/logs/mcp.log to review the log for clues
Tools not appearing
  • Run cortex mcp list to verify configuration
  • 确保工具名称有效(仅包含字母、数字、下划线和连字符)
  • 检查工具名称是否少于 64 个字符
OAuth issues
  • Clear cached tokens: rm ~/.snowflake/cortex/mcp_oauth/{server}*
  • 重新连接以触发新的 OAuth 流程
  • 检查重定向端口是否可用(默认 8585)
Environment variables not expanding
  • Use ${VAR} syntax (with braces) rather than $VAR
  • Ensure variable is set in your shell (echo $VAR)
  • 检查变量名称中的拼写错误

MCP 最佳实践

  • 使用描述性服务器名称:使工具命名空间清晰
  • 设置适当的超时:工具列表默认超时为 10 分钟
  • 安全凭据:使用环境变量,而非硬编码密钥
  • Test connections: Use cortex mcp start before relying on a server