Skills Script Extension
In addition to writing instructions in SKILL.md, you can add executable code to a skill via the scripts directory.
This section teaches you how to use scripts to extend a skill's functionality.
Why Use Scripts
Using scripts allows you to:
- Encapsulate complex logic and avoid writing large amounts of code in SKILL.md
- Provide tested, reliable implementations
- Let agents reuse the same tools and functions
- Handle more complex input/output operations
Tip: when you notice the agent repeatedly implementing the same logic across multiple executions, this is often a good time to create a script.
Script Directory Structure
Scripts should be placed in the scripts/ subdirectory of the skill directory:
Directory structure
my-skill
/
├── SKILL.md
└── scripts
/
├── script1.py
├── script2.sh
└── helper.js
Script Writing Guidelines
1. Self-Containment
Scripts should be as self-contained as possible, or clearly document their dependencies.
Self-Contained Script Example
#!/usr/bin/env python3
"""
PDF Text Extraction Script
Dependency: pip install pdfplumber
Run: python scripts/extract_pdf.py input.pdf
"""
import
sys
import
pdfplumber
def
extract_text_from_pdf
(
pdf_path
)
:
"""Extract text from a PDF file"""
with
pdfplumber.
open
(
pdf_path
)
as
pdf:
text
=
""
for
page
in
pdf.
pages
:
text +
=
page.
extract_text
(
)
or
""
return
text
if
name
==
"main"
:
if
len
(
sys
.
argv
)
<
2
:
(
"Usage: python extract_pdf.py
)
sys
.
exit
(
1
)
pdf_path
=
sys
.
argv
[
1
]
text
=
extract_text_from_pdf
(
pdf_path
)
(
text
)
2. Clear Error Handling
Scripts should provide useful error messages to help agents understand what went wrong.
Error-handling example
import
sys
def
main
(
)
:
if
len
(
sys
.
argv
)
<
2
:
(
"Error: missing required parameter"
,
file
=
sys
.
stderr
)
(
"Usage: python script.py
,
file
=
sys
.
stderr
)
sys
.
exit
(
1
)
input_file
=
sys
.
argv
[
1
]
try
:
Execute main logic
process_file
(
input_file
)
except
FileNotFoundError:
(
f
"Error: file not found {input_file}"
,
file
=
sys
.
stderr
)
sys
.
exit
(
1
)
except
PermissionError:
(
f
"Error: no permission to read file {input_file}"
,
file
=
sys
.
stderr
)
sys
.
exit
(
1
)
except
Exception
as
e:
(
f
"Error: unknown error occurred while processing file: {e}"
,
file
=
sys
.
stderr
)
sys
.
exit
(
1
)
if
name
==
"main"
:
main
(
)
3. Handle Edge Cases
Scripts should handle various edge cases gracefully rather than crashing.
Edge Case Handling Example
def
validate_input
(
text
)
:
"""Validate whether input is valid"""
if
not
text:
return
False
,
"Input cannot be empty"
if
len
(
text
)
10000
:
return
False
,
"Input length exceeds limit (maximum 10000 characters)"
return
True
,
""
Use validation
is_valid
,
error_msg
=
validate_input
(
user_input
)
if
not
is_valid:
(
f
"Validation failed: {error_msg}"
)
sys
.
exit
(
1
)
Referencing Scripts in SKILL.md
When a skill needs to execute a script, explain how to call it in SKILL.md.
Reference script:
## PDF 文本提取
Use a script to extract text from PDF:
```bash
python scripts/extract_pdf.py input.pdf
The script will extract all text from input.pdf and output it to standard output.
If you need to save the result to a file:
python scripts/extract_pdf.py input.pdf > output.txt
> 注意:引用脚本时使用相对于技能根目录的路径。
---
## Supported scripting languages
The supported scripting languages depend on the proxy implementation you use. Common options include:
| 语言 | 说明 |
| --- | --- |
| Python | 最常用的选择,功能强大且易于编写 |
| Bash | 适合系统操作和命令行工具 |
| JavaScript | 适合 Web 相关的任务 |
> 提示:在选择脚本语言时,考虑目标用户的运行环境。如果不确定,Python 是最安全的选择。
---
## Complete Example: PDF Processing Skills
Let's look at a complete example showing how to combine SKILL.md and scripts:
## Skill Structure
pdf-tool
/
├── SKILL.md
└── scripts
/
├── extract.py
├── fill_form.py
└── merge.py
SKILL.md 内容:
name: pdf-tool description: Process PDF files, including extracting text, filling forms, and merging files. Use cases: processing PDFs, extracting text, filling forms, merging PDFs.
Extract PDF Text
Extract text content from a PDF file:
python scripts/extract.py input.pdf
The output is the extracted plain text content.
Fill PDF Forms
Fill a PDF form using JSON data:
python scripts/fill_form.py input.pdf data.json output.pdf
data.json format:
{
"field_name": "字段值",
"another_field": "另一个值"
}
Merge PDFs
Merge multiple PDF files into one:
python scripts/merge.py output.pdf input1.pdf input2.pdf input3.pdf
Dependency installation
Requires pdfplumber and PyPDF2 to be installed:
pip install pdfplumber PyPDF2
---
## Two ways of use
There are two ways to use code in a Skill:
| 方式 | 适用场景 | 是否需要 scripts/ 目录 |
| --- | --- | --- |
| 一次性命令 | 只需调用现有工具,无需自定义逻辑 | 不需要 |
| 自包含脚本 | 需要复用的复杂逻辑 | 需要 |
---
## One-time command
当现有的包管理器工具已经能满足需求时,直接在 SKILL.md 的指令中引用即可,无需创建 scripts/ 目录。
Below are the common running methods for various language ecosystems:
### uvx(Python)
uvx 是 uv 自带的工具运行命令,会在隔离环境中运行 Python 包,且缓存积极,重复运行几乎瞬间完成。
## 实例
# Run ruff check code for specified version
uvx ruff
@
0.8.0 check .
# Run black formatter for specified version
uvx black
@
24.10.0 .
### pipx(Python)
pipx 是 uvx 的成熟替代方案,可通过系统包管理器安装(如 `brew install pipx`)。
## 实例
# Run a specific version of black
pipx run
'black==24.10.0'
.
# Run a specific version of ruff
pipx run
'ruff@0.8.0'
check .
### npx(Node.js)
npx 随 npm 自带,按需下载并运行 npm 包。
## 实例
# Run ESLint check
npx eslint
@
9
--fix
.
# Create project using Vite
npx create-vite
@
6 my-app
### go run(Go)
Go 自带的工具运行命令,直接编译并运行远程包。
## 实例
# Run goimports to format imports
go run golang.org
/
x
/
tools
/
cmd
/
goimports
@
v0.28.0 .
# Run golangci-lint check
go run github.com
/
golangci
/
golangci-lint
/
cmd
/
golangci-lint
@
v1.62.0 run
> 编写一次性命令的建议:固定版本号(如 npx eslint@9.0.0)以确保行为一致;在 SKILL.md 中声明前置条件(如"需要 Node.js 18+");当命令变得复杂时,应将其提取到 scripts/ 目录。
---
## Referencing scripts in SKILL.md
使用从 Skill 目录根开始的 相对路径 来引用打包的文件。
Agent 会自动解析这些路径,无需使用绝对路径。
First, list the available scripts in SKILL.md:
## 实例
## Available scripts
-
**
`scripts/validate.sh`
** — Validate configuration file
-
**
`scripts/process.py`
** — Process input data
-
**
`scripts/report.py`
-- Generate analysis report
Then reference them in the operation steps:
## 实例
## 操作流程
1.
Run validation script:
```bash
bash scripts/validate.sh "$INPUT_FILE"
```
2.
Process data:
```bash
python3 scripts/process.py --input results.json
```
> 脚本执行路径是相对于 Skill 目录根的,因为 Agent 会从 Skill 目录中运行命令。这在 references/*.md 等辅助文件中同样适用。
---
## Self-contained script
当你需要可复用的逻辑时,可以将脚本打包在 `scripts/` 目录中,并在脚本内声明依赖。
Agent 只需一条命令即可运行,无需额外的安装步骤。
### Python 自包含脚本(PEP 723)
PEP 723 定义了在 Python 脚本内声明依赖的标准格式。
Wrap TOML format dependency declarations using the `# ///` marker:
## 实例:Python 自包含脚本
# /// script
# dependencies = [
# "beautifulsoup4",
# ]
# ///
from
bs4
import
BeautifulSoup
# Example HTML content
html
=
'Welcome
RUNOOB 测试
'
# Use BeautifulSoup to parse HTML
soup
=
BeautifulSoup
(
html
,
"html.parser"
)
# Extract paragraph text with class="info"
info_text
=
soup.
select_one
(
"p.info"
)
.
get_text
(
)
print
(
info_text
)
Running method:
## 实例
# Run with uv (recommended)
uv run scripts
/
extract.py
# Run with pipx
pipx run scripts
/
extract.py
RUNOOB Test
### Deno Self-Contained Script
Deno achieves self-containment through `npm:` and `jsr:` import specifiers:
## Example: Deno self-contained script
#
!/
usr
/
bin
/
env
-
S deno run
import
*
as cheerio from
"npm:cheerio@1.0.0"
;
const
html
=
`
<
html
><
body
><
h1
>
Welcome
<
p
class
=
"info"
>
RUNOOB 测试
`
;
const
$
=
cheerio.
load
(
html
)
;
console.
log
(
$
(
"p.info"
)
.
text
(
)
)
;
## 实例
deno run scripts
/
extract.ts
### Bun Self-Contained Script
Bun automatically installs missing packages when the node_modules directory is missing:
## Example: Bun self-contained script
#
!/
usr
/
bin
/
env bun
import
*
as cheerio from
"cheerio@1.0.0"
;
const
html
=
`
<
html
><
body
><
h1
>
Welcome
<
p
class
=
"info"
>
RUNOOB 测试
`
;
const
$
=
cheerio.
load
(
html
)
;
console.
log
(
$
(
"p.info"
)
.
text
(
)
)
;
## 实例
bun run scripts
/
extract.ts
### Self-contained Ruby script
Ruby uses `bundler/inline` to declare gem dependencies in a script:
## Example: Self-contained Ruby script
require
'bundler/inline'
gemfile
do
source
'https://rubygems.org'
gem
'nokogiri'
end
html =
'Welcome
RUNOOB 测试
'
doc =
Nokogiri::HTML
(
html
)
puts
doc.
at_css
(
'p.info'
)
.
text
## 实例
ruby scripts
/
extract.rb
---
## Key points for designing scripts for an Agent
Agent 通过读取 stdout 和 stderr 来决定下一步操作,脚本的设计要考虑 Agent 的使用特点。
### Avoid interactive prompts
这是硬性要求。Agent 在非交互式 Shell 中运行,无法响应 TTY 提示、密码对话框或确认菜单。
所有输入应通过命令行参数、环境变量或 stdin 传入。
## Example: Wrong way vs Correct way
# Error: hangs waiting for input
$ python scripts
/
deploy.py
Target environment: _
# Correct: Clear error messages and guidance
$ python scripts
/
deploy.py
Error:
--env
is required. Options: development, staging, production.
Usage: python scripts
/
deploy.py
--env
staging
--tag
v1.2.3
### 提供 --help 文档
`--help` 输出是 Agent 了解脚本接口的主要方式。
Includes brief description, available parameters, and usage examples:
## Example: Good --help output
Usage: scripts
/
process.py
[
OPTIONS
]
INPUT_FILE
处理输入数据并生成摘要报告。
Options:
--format
FORMAT 输出格式: json, csv, table
(
默认: json
)
--output
FILE 将输出写入文件而非 stdout
--verbose
在 stderr 中打印进度信息
Examples:
scripts
/
process.py data.csv
scripts
/
process.py
--format
csv
--output
report.csv data.csv
### Writing useful error messages
Agent 看到错误信息后会据此调整策略,信息越具体,Agent 越容易自我纠正。
## 实例
# Bad error message
Error: invalid input
# Good error message
Error:
--format
must be one of: json, csv, table.
Received:
"xml"
### 使用结构化输出
优先使用 JSON、CSV、TSV 等结构化格式输出,而非自由文本。
结构化格式可同时被 Agent 和标准工具(jq、cut、awk)消费,方便组合使用。
## 实例
# Not recommended: text alignment, difficult to parse programmatically
NAME STATUS CREATED
my-service running
2025
-01-
15
# Recommended: JSON format, clear field boundaries
{
"name"
:
"my-service"
,
"status"
:
"running"
,
"created"
:
"2025-01-15"
}
> 将结构化数据输出到 stdout,将进度消息和诊断信息输出到 stderr。这样 Agent 可以获取干净的、可解析的输出,同时需要时也能查看诊断信息。
---
## More script design suggestions
| 建议 | 说明 |
| --- | --- |
| 幂等性 | Agent 可能重试命令。"不存在则创建"比"创建并在重复时报错"更安全 |
| 输入约束 | 用清晰的错误拒绝模糊输入,而非猜测用户意图 |
| Dry-run 支持 | 对于破坏性或有状态操作,提供 `--dry-run` 标志让 Agent 预览操作 |
| 有意义的退出码 | 不同失败类型使用不同退出码(未找到、参数无效、认证失败等) |
| 可预测的输出大小 | 默认输出摘要,提供 `--offset` 等参数让 Agent 按需获取更多信息 |
| 安全默认值 | 破坏性操作应要求明确的确认标志(`--confirm`、`--force`) |
---
## Complete Skill script example
Below is the complete Skill directory structure containing scripts:
## 实例
csv-analyzer
/
├── SKILL.md
# Main instruction file
├── scripts
/
│ ├── overview.py
# Data overview script
│ ├── summary.py
# Summary script
│ └── validate.py
# Data validation script
├── references
/
│ └── api-errors.md
# API Error Reference
└── assets
/
└── report-template.md
# Report template
The corresponding SKILL.md content:
## 实例
---
name: csv-analyzer
description: >
分析 CSV 和表格数据文件。当用户有 CSV、TSV 或 Excel 文件
并想探索、转换或可视化数据时使用。
---
# CSV Data Analysis
## Available scripts
-
**
`scripts/overview.py`
** — Display data overview (number of rows, column names, types)
-
**
`scripts/summary.py`
-- Generate statistical summary
-
**
`scripts/validate.py`
** — Validate data quality
## 操作流程
1.
First run the overview script to understand the data structure:
```bash
uv run scripts/overview.py input.csv
```
2.
Generate statistical summary:
```bash
uv run scripts/summary.py input.csv --output summary.json
```
3.
Validate data quality:
```bash
uv run scripts/validate.py input.csv
```
## Notes
-
大文件使用
`--chunk-size`
参数分块处理
-
中文 CSV 尝试
`--encoding gbk`
参数
---
## Script Distribution and Dependencies
If the script requires external dependencies, you have several options:
### 1. Describe dependencies in SKILL.md
最简单的方式是在 SKILL.md 中记录所需的依赖。
### 2. Using a virtual environment
对于复杂的项目,可以创建一个虚拟环境。
### 3. Using Docker
如果需要完整的运行环境,可以使用 Docker 容器。
> 注意:确保脚本可以在目标环境中运行。在编写脚本之前,了解目标用户的运行环境。
---
## 总结
In this section, we learned how to use scripts to extend skill functionality:
- 脚本放在 scripts/ 目录下
- 脚本应该自包含、有清晰的错误处理
- 在 SKILL.md 中引用脚本时使用相对路径
- 确保脚本可以在目标环境中运行