Skip to main content
Glama
TwT23333
by TwT23333

view_code

Extract and display specific code sections by selecting file paths, line numbers, or span IDs for targeted analysis and context retrieval.

Instructions

View specific code sections with context

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
end_lineNoEnding line number (1-indexed)
file_pathYesPath to the file to view
span_idsNoList of span IDs to view (class names, function names, etc.)
start_lineNoStarting line number (1-indexed)

Implementation Reference

  • Main handler for the view_code MCP tool. Processes input arguments, calls the core view_code implementation from AdvancedSearchTools, formats the response with code sections.
    async def execute(self, arguments: Dict[str, Any]) -> ToolResult: """Execute the view_code tool.""" try: file_path = arguments.get("file_path") start_line = arguments.get("start_line") end_line = arguments.get("end_line") span_ids = arguments.get("span_ids") if not file_path: return self.format_error("file_path is required") search_tools = AdvancedSearchTools(self.workspace.config, self.workspace.workspace_path) result = await search_tools.view_code(file_path, start_line, end_line, span_ids) if "error" in result: return self.format_error(result["error"]) # Format the response message = f"Code view for {result['file_path']} (Total lines: {result['total_lines']}):\n\n" for section in result['content_sections']: if 'span_id' in section: message += f"=== {section['span_type'].title()}: {section['span_id']} ===\n" message += f"Lines {section['start_line']}-{section['end_line']}:\n" else: message += f"=== Lines {section['start_line']}-{section['end_line']} ===\n" message += section['content'] message += "\n\n" return ToolResult( success=True, message=message, properties=result ) except Exception as e: logger.error(f"Error in view_code: {e}") return self.format_error(str(e))
  • Input schema defining parameters for the view_code tool: file_path (required), start_line, end_line, span_ids.
    def input_schema(self) -> Dict[str, Any]: return { "type": "object", "properties": { "file_path": { "type": "string", "description": "Path to the file to view" }, "start_line": { "type": "integer", "description": "Starting line number (1-indexed)" }, "end_line": { "type": "integer", "description": "Ending line number (1-indexed)" }, "span_ids": { "type": "array", "items": {"type": "string"}, "description": "List of span IDs to view (class names, function names, etc.)" } }, "required": ["file_path"] }
  • Registration of ViewCodeTool instance in the ToolRegistry's default tools list.
    FindClassTool(self.workspace), FindFunctionTool(self.workspace), ViewCodeTool(self.workspace), SemanticSearchTool(self.workspace), RunTestsTool(self.workspace),
  • Core helper function implementing the view_code logic: reads file, handles line ranges or span_ids (classes/functions), uses tree-sitter or regex to find code blocks, extracts and sections content.
    async def view_code(self, file_path: str, start_line: Optional[int] = None, end_line: Optional[int] = None, span_ids: Optional[List[str]] = None) -> Dict[str, Any]: """View specific code sections with intelligent context. Args: file_path: Path to the file to view start_line: Starting line number (1-indexed) end_line: Ending line number (1-indexed) span_ids: List of span IDs to view (class names, function names, etc.) Returns: Dictionary with code content and metadata """ try: # Validate and normalize file path full_path = self.workspace_root / file_path if not self.config.is_file_allowed(full_path): return {"error": "File access not allowed"} if not full_path.exists(): return {"error": f"File not found: {file_path}"} if not full_path.is_file(): return {"error": f"Path is not a file: {file_path}"} # Read file content try: with open(full_path, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() except Exception as e: return {"error": f"Cannot read file: {str(e)}"} lines = content.split('\n') total_lines = len(lines) result = { "file_path": file_path, "total_lines": total_lines, "content_sections": [] } # Handle span_ids (enhanced implementation) if span_ids: for span_id in span_ids: found_matches = [] # Handle different span_id formats if '.' in span_id: # Handle ClassName.method_name format parts = span_id.split('.') if len(parts) == 2: class_name, method_name = parts found_matches.extend(self._find_class_method(content, lines, class_name, method_name)) else: # Handle simple class or function names found_matches.extend(self._find_simple_span(content, lines, span_id)) # Process matches for match_line, span_type, end_line in found_matches: try: # Validate line numbers if match_line > len(lines) or match_line < 1: continue # Extract the content start_idx = match_line - 1 # Convert to 0-based index end_idx = min(end_line, total_lines) section_content = '\n'.join(lines[start_idx:end_idx]) result["content_sections"].append({ "span_id": span_id, "span_type": span_type, "start_line": match_line, "end_line": end_idx, "content": section_content }) except Exception as e: logger.warning(f"Error processing span_id {span_id}: {e}") continue # If no matches found for span_ids, add error info if not result["content_sections"]: result["content_sections"].append({ "error": f"No matches found for span_ids: {', '.join(span_ids)}", "start_line": 1, "end_line": 1, "content": f"# No code blocks found matching: {', '.join(span_ids)}\n# Available in this file, please use line numbers or search for specific patterns." }) # Handle line range elif start_line is not None: start_idx = max(1, start_line) - 1 end_idx = min(total_lines, end_line or start_line) if end_line else start_idx + 1 if start_idx >= total_lines: return {"error": f"Start line {start_line} exceeds file length {total_lines}"} section_content = '\n'.join(lines[start_idx:end_idx]) result["content_sections"].append({ "start_line": start_idx + 1, "end_line": end_idx, "content": section_content }) # Return entire file if no specific range requested else: if total_lines > 1000: # Limit large files result["content_sections"].append({ "start_line": 1, "end_line": 100, "content": '\n'.join(lines[:100]) + f"\n... (file has {total_lines} total lines, showing first 100)" }) else: result["content_sections"].append({ "start_line": 1, "end_line": total_lines, "content": content }) return result except Exception as e: logger.error(f"Error in view_code: {e}") return {"error": f"Failed to view code: {str(e)}"}

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/TwT23333/mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server