apply_code_action
Execute a specific code action identified by index to implement suggested fixes or improvements in Python files at precise locations.
Instructions
Apply a code action by index (from get_code_actions).
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| file_path | Yes | ||
| line | Yes | ||
| column | Yes | ||
| action_index | Yes |
Implementation Reference
- src/mcp_ty/server.py:669-724 (handler)The 'apply_code_action' tool is defined as an MCP tool and handles applying code actions to files using an LSP client.
@mcp.tool() async def apply_code_action( file_path: str, line: int, column: int, action_index: int ) -> str: """Apply a code action by index (from get_code_actions).""" client = _get_client() path = Path(file_path).resolve() if not path.exists(): return _error(f"File not found: {file_path}") try: await client.open_document(path) import asyncio await asyncio.sleep(0.3) diagnostics = client.get_diagnostics(path) relevant_diags = [ d for d in diagnostics if d.range.start.line <= line - 1 <= d.range.end.line ] actions = await client.get_code_actions( path, line - 1, column - 1, line - 1, column, relevant_diags ) if not actions: return _not_found(f"No actions at {path.name}:{line}:{column}") if action_index < 1 or action_index > len(actions): return _error(f"Invalid index. Choose 1-{len(actions)}") action = actions[action_index - 1] if not action.edit: return _error(f"Action '{action.title}' has no edits") all_edits = action.edit.get_all_edits() applied_files = [] for uri, edits in all_edits.items(): file_to_edit = _uri_to_path(uri) if file_to_edit.exists(): new_content = _apply_edits_to_file(file_to_edit, edits) file_to_edit.write_text(new_content, encoding="utf-8") applied_files.append(file_to_edit.name) return _ok({ "applied": True, "action": action.title, "modified_files": applied_files }) except Exception as e: return _error(str(e))