Synthèse automatique
Extrait une plage de lignes sélectionnée dans un fichier source vers une fonction nommée, en privilégiant l'action de refactorisation extract-function du serveur de langage, avec repli manuel.
Points forts
- S'appuie sur les actions de refactorisation natives du LSP pour produire des modifications adaptées au langage.
- Vérifie les symboles du document avant l'édition afin de détecter les collisions de noms.
- Prévoit des contrôles après extraction sur les variables capturées, le masquage de portée et la compilation/les diagnostics.
- Prend en charge les réponses d'action sous forme de commande ou d'édition.
Limites
- Nécessite le serveur MCP agent-lsp et un serveur de langage exposant les actions de code ; sinon, le repli manuel s'impose.
- Le contenu fourni de SKILL.md est tronqué dans la section de repli manuel, donc l'enchaînement exact des étapes de repli et de validation n'est pas entièrement spécifié.
- La compétence ne fait que restructurer du code existant ; elle ne génère pas de nouvelle implémentation.
À utiliser lorsqu'un bloc de code existant doit devenir une fonction nommée et que le serveur de langage peut fournir une action de refactorisation.
À éviter pour créer du code à partir de zéro ou dans un environnement dépourvu du serveur MCP LSP requis.
Analyse de sécurité
SûrThe skill only uses LSP MCP tools: opening documents, listing symbols, querying code actions, applying workspace edits, reading diagnostics, and formatting. There is no shell execution, no network access, no credential handling, and no destructive filesystem operations. Edits are scoped to the named file and gated on a user confirmation step, and the primary path defers to the language server's own code action. The only notable inconsistency is a reference to a start_lsp tool not present in the declared tool list, which is harmless.
- •Prerequisites instruct calling `mcp__lsp__start_lsp`, which is not included in the declared allowed-tools list — an inconsistency, though not a risk in itself
- •The skill applies edits to user files via `mcp__lsp__apply_edit`, but only to the specified document with user confirmation on the proposed signature
Exemples
Extract lines 42-58 of /Users/me/project/src/parser.ts into a function named parseHeader, using the LSP extract-function code action and checking diagnostics afterward.In /Users/me/project/src/service.ts, extract lines 110-135 into a new function called buildRequest. Check for an existing symbol with that name first and stop if there is a collision.Extract the selected block on lines 25-40 of /Users/me/project/src/utils.py into normalize_path. If the language server offers no extract-function action, use the manual fallback and validate the result.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_namealready 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_namealready 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_commandif the action has acommandfield:mcp__lsp__execute_command({ "command": "<action.command.command>", "arguments": <action.command.arguments> }) - OR apply directly via
mcp__lsp__apply_editif the action has aneditfield: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:
-
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" }] } } }) -
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).
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.
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/extract-code-block-to-named-function-ms8gxmvc/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/extract-code-block-to-named-function-ms8gxmvc' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/extract-code-block-to-named-function-ms8gxmvc/download' --output '.skill-downloads/extract-code-block-to-named-function-ms8gxmvc/SKILL.md.part' && mv '.skill-downloads/extract-code-block-to-named-function-ms8gxmvc/SKILL.md.part' '.skill-downloads/extract-code-block-to-named-function-ms8gxmvc/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Environnement déclaré par l’auteur : Requires the agent-lsp MCP server (github.com/blackwell-systems/agent-lsp)
Outils déclarés par l’auteur (à vérifier dans votre agent) : 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
Extrait original : 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.
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/extract-code-block-to-named-function-ms8gxmvc/SKILL.md' && test -s '.skill-downloads/extract-code-block-to-named-function-ms8gxmvc/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/lsp-extract-function' && cp -R '.skill-downloads/extract-code-block-to-named-function-ms8gxmvc' '.claude/skills/lsp-extract-function'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/extract-code-block-to-named-function-ms8gxmvc'openskills read 'extract-code-block-to-named-function-ms8gxmvc'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/extract-code-block-to-named-function-ms8gxmvc/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Bonnes pratiques React Hook Form
Developpement
Maîtrisez React Hook Form : évitez les anti-patterns, gérez les abonnements, et traitez correctement reset, dirty state et entrées contrôlées.
Migration Emotion vers Mantine
Developpement
Migrer les styled-components Emotion vers des composants Mantine avec style props et modules CSS. Pour convertir .styled.tsx ou supprimer les imports @emotion.
Détecteur de dérive de périmètre
Developpement
Analyse les diffs git par rapport à une intention pour détecter la dérive de périmètre, fichiers non liés et PR trop larges, puis suggère de garder, diviser ou justifier.