К основному содержанию
скилл CX Codex

lsp-extract-function — скилл для Claude Code: что делает и установка

Выносит выделенный блок кода в отдельную функцию через LSP-сервер или вручную. Помогает безопасно декомпозировать функции с проверкой типов и скоупа.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add blackwell-systems/agent-lsp --skill lsp-extract-function -a claude-code
Открыть на GitHub

Что делает lsp-extract-function

Скилл рефакторит уже написанный код в проекте. Он принимает абсолютный путь к файлу, диапазон строк и желаемое имя новой функции. Сначала инструмент через MCP открывает документ и запрашивает символы. Если функция с таким именем уже существует в файле, операция сразу прерывается для защиты от конфликтов.

Основной сценарий использует действие refactor.extract языкового сервера через вызов suggest_fixes. Если сервер не поддерживает такую команду, скилл переключается на ручной разбор. Он анализирует захваченные переменные, возвращаемые значения и точки выхода. Перед правкой агент обязательно согласует сигнатуру с вами. Сначала заменяется вызов, затем добавляется объявление функции, чтобы не сбить номера строк.

После редактирования инструмент запрашивает ошибки компилятора через get_diagnostics и форматирует файл. Для работы обязательно требуется MCP-сервер agent-lsp.

Какие задачи решает

  • вынести длинный блок кода в новую функцию с сохранением контекста
  • проверить конфликты имён символов перед рефакторингом
  • найти ошибки затенения переменных и несовпадения типов через LSP
  • разбить сложный метод при отсутствии встроенных рефакторингов в сервере

Примеры запросов агенту

  • Вынеси строки 40-75 из /workspace/src/auth.ts в функцию verifyToken
  • Выдели блок со строки 12 по 35 в /project/pkg/parser.go в отдельную функцию parseHeaders
  • Рефактори строки 100-142 в файле /app/main.py и назови новую функцию process_batch

Как установить lsp-extract-function

1Через Skills CLI (Vercel)

npx skills add blackwell-systems/agent-lsp --skill lsp-extract-function -a claude-code

2Вручную: положить файлы

~/.claude/skills/lsp-extract-function/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/lsp-extract-function/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о lsp-extract-function

Как установить lsp-extract-function в Claude Code?

Выполните команду npx skills add blackwell-systems/agent-lsp --skill lsp-extract-function -a claude-code.

Что делает скилл lsp-extract-function?

Он находит указанный диапазон строк в файле, проверяет видимость переменных и переносит код в отдельную функцию через LSP или ручной разбор.

Что произойдёт, если языковой сервер не поддерживает refactor.extract?

Скилл переключится в ручной режим: сам выделит параметры и возвращаемые значения, покажет сигнатуру и дождётся подтверждения перед редактированием.

Исходный текст

SKILL.md · MIT
---
name: lsp-extract-function
description: Extract a selected code block into a named function. Primary path uses the language server's extract-function code action; falls back to manual extraction when no code action is available. Validates captured variables, scope shadowing, and compilation after extraction.
argument-hint: "[file-path] [start-line] [end-line] [new-function-name]"
user-invocable: true
allowed-tools: mcp__lsp__list_symbols mcp__lsp__suggest_fixes mcp__lsp__execute_command mcp__lsp__apply_edit mcp__lsp__get_diagnostics mcp__lsp__open_document mcp__lsp__format_document mcp__lsp__get_server_capabilities
license: MIT
compatibility: Requires the agent-lsp MCP server (github.com/blackwell-systems/agent-lsp)
metadata:
  required-capabilities: codeActionProvider
  optional-capabilities: documentFormattingProvider documentSymbolProvider
---

> Requires the agent-lsp MCP server.

# lsp-extract-function: Extract Code Block into a Named Function

**This skill RESTRUCTURES existing code** — it takes code that already exists
and moves it into a new function. This is distinct from `/lsp-generate`, which
creates NEW code that does not yet exist (stubs, mocks, interface implementations).
Use this skill when the code is already written; use `/lsp-generate` when you
need to generate code from scratch.

**Invocation:** User provides `file_path` (absolute path), `start_line` and
`end_line` (1-indexed range), and `new_function_name` (desired name for the
extracted function).

---

## Prerequisites

If LSP is not yet initialized, call `mcp__lsp__start_lsp` with the workspace
root first. Auto-inference applies when file paths are provided, but an explicit
start is required when switching workspaces.

---

## Step 1 — Get context (document symbols)

Call `mcp__lsp__open_document` to open the file, then call
`mcp__lsp__list_symbols` to understand the containing function and scope:

```
mcp__lsp__open_document({ "file_path": "<file_path>" })
mcp__lsp__list_symbols({ "file_path": "<file_path>" })
```

This establishes:
- Which function contains the selection
- Whether `new_function_name` already exists in the file (name collision check)

**Mandatory name collision check:** If `new_function_name` already exists as a
symbol in the document symbols list, report the conflict and stop immediately:

> Cannot extract: function `new_function_name` already exists in this file.
> Choose a different name and retry.

---

## Step 2 — Check server capabilities

Call `mcp__lsp__get_server_capabilities` to understand what the language server
supports:

```
mcp__lsp__get_server_capabilities({})
```

Check for `codeActionProvider` in the response. Note whether `execute_command`
is listed in `executeCommandProvider.commands`. This determines whether the
primary path (Step 3) is available.

---

## Step 3 — Primary path: LSP code action

Call `mcp__lsp__suggest_fixes` with the selection range:

```
mcp__lsp__suggest_fixes({
  "file_path": "<file_path>",
  "start_line": N,
  "start_column": 1,
  "end_line": M,
  "end_column": 999
})
```

Filter the returned actions for extract-function actions: include any action
whose `kind` contains `"refactor.extract"` OR whose `title` contains both
"Extract" and "function" (case-insensitive).

**If an extract-function action is found:**
- Display the action title to the user
- If the action proposes a different name than `new_function_name`, ask for
  confirmation before proceeding
- Execute via `mcp__lsp__execute_command` if the action has a `command` field:
  ```
  mcp__lsp__execute_command({
    "command": "<action.command.command>",
    "arguments": <action.command.arguments>
  })
  ```
- OR apply directly via `mcp__lsp__apply_edit` if the action has an `edit` field:
  ```
  mcp__lsp__apply_edit({ "workspace_edit": <action.edit> })
  ```
- Skip to Step 5 after applying.

**If no extract-function action is found:** fall through to Step 4 (manual fallback).

---

## Step 4 — Manual fallback

When no code action is available, perform manual extraction:

### a) Analyze the selection

Read the selected lines (`start_line` through `end_line`) and identify:
- **Parameters:** Variables used inside the selection that are declared outside
  (captured from outer scope — must become function parameters)
- **Return values:** Variables declared inside the selection that are used outside
  (must be returned from the extracted function)
- **Early returns:** Return statements inside the selection (the extracted function
  must wrap these)

### b) Construct and confirm the proposed signature

Build the extracted function signature based on the captured variables analysis.
Display the proposed signature to the user before writing:

> Proposed extraction:
> ```
> func new_function_name(param1 Type1, param2 Type2) (ReturnType, error) {
>     // selected lines
> }
> ```
> Proceed with this signature? [y/n]

Wait for user confirmation before applying any edit.

### c) Apply the extraction (order matters)

Apply edits sequentially — do NOT batch edits from different line regions into a
single `apply_edit` call:

1. **First:** Replace the selected lines with a call to the new function:
   ```
   mcp__lsp__apply_edit({
     "workspace_edit": {
       "changes": {
         "<file_path>": [{
           "range": { "start": { "line": start_line-1, "character": 0 },
                      "end":   { "line": end_line,     "character": 0 } },
           "newText": "    result := new_function_name(args...)\n"
         }]
       }
     }
   })
   ```

2. **Second:** Insert the new function definition after the containing function's
   closing brace:
   ```
   mcp__lsp__apply_edit({
     "workspace_edit": {
       "changes": {
         "<file_path>": [{
           "range": { "start": { "line": insert_line, "character": 0 },
                      "end":   { "line": insert_line, "character": 0 } },
           "newText": "\nfunc new_function_name(params) ReturnType {\n    ...\n}\n"
         }]
       }
     }
   })
   ```

Apply call-site replacement first, then insert the new function. This order
preserves line numbers during editing: replacing call site does not shift the
insertion point for the new function definition.

---

## Step 5 — Validate

After extraction via either path:

### 1. Check diagnostics

```
mcp__lsp__get_diagnostics({ "file_path": "<file_path>" })
```

If errors are reported, display them with the table of common causes below.

### 2. Common post-extraction errors

| Error type | Likely cause | Fix |
|------------|--------------|-----|
| Undefined variable | Captured var not passed as parameter | Add parameter |
| Type mismatch | Return type inferred incorrectly | Adjust return type in signature |
| Name shadows outer | New function name matches outer scope | Choose different name |
| Unused variable | Return value not captured at call site | Add variable at call site |

### 3. Format the document

```
mcp__lsp__format_document({ "file_path": "<file_path>" })
```

This cleans up indentation introduced by the extraction.

---

## Output Format

After completing extraction, display:

```
## Extraction Summary
- File:           path/to/file.go
- Extracted:      lines N–M
- New function:   new_function_name
- Path used:      LSP code action / Manual fallback
- Post-extraction errors: 0
```

Follow with the Diagnostic Summary if any errors changed (format in
[references/patterns.md](references/patterns.md)).

---

## Language-Specific Notes

- **Go:** gopls may offer "Extract function" in code actions for selection ranges.
  Check code actions first; gopls support varies by version.
- **TypeScript/JavaScript:** typescript-language-server may offer "Extract to function in global scope"
  or "Extract to inner function" — filter for these titles in Step 3.
- **Python:** pylsp and pyright-langserver typically do NOT offer extract-function
  code actions. Manual fallback (Step 4) is required for Python files.

© blackwell-systems · MIT · blackwell-systems/agent-lsp

Похожие скиллы

Все скиллы по теме «Код-ревью и рефакторинг» →
improve-codebase-architecture Matt Pocock Скилл ищет архитектурные узкие места в кодовой базе и показывает варианты углубления модулей в HTML-отчёте. Подойдёт для ревью перед рефакторингом. 1 163 035установок tdd Matt Pocock Скилл управляет циклом красный-зелёный в TDD: проверяет, что тесты пишутся до кода, держит их на уровне публичных интерфейсов и не завязывает на внутреннюю структуру. 1 141 062установок triage Matt Pocock Скилл проводит issue и внешние PR через роли триажа, проверку и подготовку брифа для агента. Подойдёт мейнтейнеру, который разбирает очередь задач. 990 453установок codebase-design Matt Pocock Скилл помогает проектировать модули с небольшим интерфейсом и скрытой внутри сложностью. Подходит для рефакторинга, тестируемости и поиска чистого seam. 850 344установок code-review Matt Pocock Проверяет изменения от выбранной точки по стандартам репозитория и требованиям задачи. Нужен для ревью ветки, PR или незавершённой работы. 789 521установок implement Matt Pocock Выполняет задачу по спецификации или тикетам, ведёт работу через тесты и завершает её ревью с коммитом. Подходит для задач, где нужен дисциплинированный цикл разработки. 774 700установок

Из того же набора25

lsp-impact Показывает всех вызывающих, супертипы и подтипы, число ссылок на символ или файл до того, как вы что-то поменяете. Пригодится при рефакторинге и удалении кода. CX Codex +1 ★ 165звёзд репо lsp-generate Запускает генерацию кода через языковой сервер: создаёт заглушки интерфейсов, каркасы тестов и недостающие методы. Пригодится при написании нового кода по типам. CX Codex +1 ★ 165звёзд репо lsp-format-code Форматирует целый файл или выбранный диапазон через языковой сервер. Пригодится после генерации кода и перед коммитом, чтобы привести отступы и стиль к правилам проекта. CX Codex +1 ★ 165звёзд репо lsp-fix-all Прогоняет все диагностики в файле и применяет доступные quick-fix от языкового сервера. Пригодится, когда в файле накопились ошибки и предупреждения перед новой работой. CX Codex +1 ★ 165звёзд репо lsp-explore Собирает сведения о символе: определение, тип, реализации, вызывающие функции и ссылки. Пригодится, когда нужно разобраться в незнакомом коде. CX Codex +1 ★ 165звёзд репо lsp-edit-symbol Меняет функцию, тип или переменную по имени, когда точный файл и позиция неизвестны. Работает через MCP-сервер agent-lsp. CX Codex +1 ★ 165звёзд репо lsp-edit-export Пошаговый сценарий безопасного изменения публичных функций, типов и API. Сначала находит все вызовы через LSP, запрашивает подтверждение и проверяет сборку. CX Codex +1 ★ 165звёзд репо lsp-docs Скилл ищет сведения о символе через LSP, документацию локального toolchain и исходное определение. Выручает, когда hover пустой или зависимость не индексируется. CX Codex +1 ★ 165звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой