MCP HubMCP Hub
스킬 목록으로 돌아가기

lsp-extract-function

blackwell-systems
업데이트됨 5 days ago
53
2
53
GitHub에서 보기
개발ai

정보

이 스킬은 선택된 코드 블록을 새로운 명명된 함수로 추출하며, 주로 언어 서버의 내장 리팩터링 기능을 사용하고 수동 대체 방법을 보조로 활용합니다. 변수 캡처와 스코프를 검증하여 추출 후 정확성을 보장합니다. IDE 내에서 반복적인 코드를 재사용 가능한 함수로 리팩터링해야 할 때 사용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add blackwell-systems/agent-lsp -a claude-code
플러그인 명령대체
/plugin add https://github.com/blackwell-systems/agent-lsp
Git 클론대체
git clone https://github.com/blackwell-systems/agent-lsp.git ~/.claude/skills/lsp-extract-function

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

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 typeLikely causeFix
Undefined variableCaptured var not passed as parameterAdd parameter
Type mismatchReturn type inferred incorrectlyAdjust return type in signature
Name shadows outerNew function name matches outer scopeChoose different name
Unused variableReturn value not captured at call siteAdd 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).


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.

GitHub 저장소

blackwell-systems/agent-lsp
경로: skills/lsp-extract-function
0
agentskillsai-agentsai-toolingclaudeclaude-codecode-intelligence

연관 스킬

qmd

개발

qmd는 BM25, 벡터 임베딩, 재순위화를 결합한 하이브리드 검색을 통해 로컬 파일을 색인화하고 검색할 수 있는 로컬 검색 및 색인화 CLI 도구입니다. 명령줄 사용과 Claude 통합을 위한 MCP(Model Context Protocol) 모드를 모두 지원합니다. 이 도구는 임베딩에 Ollama를 사용하고 색인을 로컬에 저장하여 터미널에서 직접 문서나 코드베이스를 검색하는 데 이상적입니다.

스킬 보기

subagent-driven-development

개발

이 스킬은 각 독립적인 작업마다 새로운 하위 에이전트를 배치하고 작업 사이에 코드 리뷰를 진행하여 구현 계획을 실행합니다. 이 리뷰 프로세스를 통해 품질 게이트를 유지하면서 빠른 반복 작업을 가능하게 합니다. 동일한 세션 내에서 대부분 독립적인 작업을 진행할 때 내장된 품질 검증과 함께 지속적인 진행을 보장하기 위해 사용하세요.

스킬 보기

mcporter

개발

mcporter 스킬은 개발자가 Claude에서 직접 Model Context Protocol(MCP) 서버를 관리하고 호출할 수 있도록 합니다. 이 스킬은 사용 가능한 서버를 나열하고, 인수를 사용해 해당 서버의 도구를 호출하며, 인증 및 데몬 생명주기를 처리하는 명령어를 제공합니다. 개발 워크플로우에서 MCP 서버 기능을 통합하고 테스트할 때 이 스킬을 사용하세요.

스킬 보기

adk-deployment-specialist

개발

이 스킬은 A2A 프로토콜을 사용하여 Vertex AI ADK 에이전트를 배포하고 오케스트레이션하며, AgentCard 검색, 작업 제출, 코드 실행 샌드박스 및 메모리 뱅크와 같은 지원 도구를 관리합니다. Python, Java 또는 Go 언어로 순차, 병렬 또는 루프 오케스트레이션 패턴을 갖춘 다중 에이전트 시스템 구축을 가능하게 합니다. Google Cloud에서 ADK 에이전트 배포 또는 에이전트 워크플로우 오케스트레이션을 요청받았을 때 사용하세요.

스킬 보기