Skip to main content
Glama

compile_code

Compile source code with specific compilers and options to generate assembly, analyze output, and manage dependencies using the Compiler Explorer MCP server.

Instructions

Compile source code using specified compiler and options.

Args: source: Source code to compile language: Programming language of the source code compiler: Compiler name or ID to use ctx: MCP context for logging and error reporting options: Compiler flags and options filters: Configuration for filtering compiler output libraries: List of library dependencies Returns: Dictionary containing compilation results with keys: - code: Exit code of the compilation - stdout: Standard output from the compiler - stderr: Standard error from the compiler - asm: Generated assembly (if applicable) Raises: HTTPException: If compilation fails, compiler not found, or API request fails Example: >>> result = await compile_code( ... source="int main() { return 0; }", ... language="cpp", ... compiler="gcc", ... ctx=ctx ... )

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
compilerYes
filtersNo
languageYes
librariesNo
optionsNo
sourceYes

Implementation Reference

  • MCP tool handler for 'compile_code'. This is the main entry point decorated with @mcp.tool(), handling input validation implicitly via type hints and pydantic models, inferring compiler ID, logging, and delegating to CompilerExplorerClient
    @mcp.tool() async def compile_code( source: str, language: str, compiler: str, ctx: Context, options: str = "", filters: CompilationFilters = CompilationFilters(), libraries: list[Library] = [], ) -> dict: """Compile source code using specified compiler and options. Args: source: Source code to compile language: Programming language of the source code compiler: Compiler name or ID to use ctx: MCP context for logging and error reporting options: Compiler flags and options filters: Configuration for filtering compiler output libraries: List of library dependencies Returns: Dictionary containing compilation results with keys: - code: Exit code of the compilation - stdout: Standard output from the compiler - stderr: Standard error from the compiler - asm: Generated assembly (if applicable) Raises: HTTPException: If compilation fails, compiler not found, or API request fails Example: >>> result = await compile_code( ... source="int main() { return 0; }", ... language="cpp", ... compiler="gcc", ... ctx=ctx ... ) """ try: compilers = await ce_client.list_compilers(language) compiler_id = infer_compiler_id(compiler, compilers) if not compiler_id: await ctx.error( message=f"Compiler '{compiler}' not found", level="error", ) raise HTTPException( status_code=404, detail=f"Compiler '{compiler}' not found" ) await ctx.log( message=f"Inferred compiler {compiler_id} from {compiler}. Compiling...", level="info", ) return await ce_client.compile_code( source=source, compiler=compiler_id, options=options, filters=filters, libraries=libraries, ) except CompilerExplorerError as e: raise HTTPException(status_code=e.status_code, detail=str(e))
  • Pydantic schema for compilation filters passed to the compile_code tool
    class CompilationFilters(BaseModel): """Configuration for filtering compiler output. Attributes: binary: Include binary output in the response (default: False) binary_object: Include binary object output (default: False) comment_only: Include only comments from the output (default: True) demangle: Demangle C++ symbols in the output (default: True) directives: Include compiler directives in the output (default: True) execute: Include execution results (default: False) intel: Use Intel syntax for assembly output (default: True) labels: Include labels in the output (default: True) library_code: Include library code in the output (default: False) trim: Trim whitespace from the output (default: False) """ binary: bool = False binary_object: bool = False comment_only: bool = True demangle: bool = True directives: bool = True execute: bool = False intel: bool = True labels: bool = True library_code: bool = False trim: bool = False
  • Pydantic schema for library dependencies used in compile_code tool
    class Library(BaseModel): """Represents a library dependency for compilation. Attributes: id: Unique identifier for the library (e.g., 'boost', 'fmt') version: Version string of the library (e.g., '1.76.0') """ id: str version: str
  • Core helper method in CompilerExplorerClient that performs the actual API call to Compiler Explorer for compilation
    async def compile_code( self, source: str, compiler: str, options: str = "", filters: CompilationFilters = CompilationFilters(), libraries: list[Library] = [], ) -> dict: """Compile code using specified compiler. Args: source: Source code to compile compiler: Compiler ID to use (e.g., 'gcc-12.2') options: Optional compiler flags and options filters: Optional configuration for filtering compiler output libraries: Optional list of library dependencies Returns: Dictionary containing compilation results with keys: - code: Exit code of the compilation - stdout: Standard output from the compiler - stderr: Standard error from the compiler - asm: Generated assembly (if applicable) Raises: CompilerExplorerError: If compilation fails or API request fails """ data = { "source": source, "options": { "userArguments": options or "", "filters": filters.dict() if filters else CompilationFilters().dict(), "libraries": [lib.dict() for lib in libraries] if libraries else [], }, } return await self._make_request( "POST", f"{self.base_url}/compiler/{compiler}/compile", json=data )
  • Helper function used by compile_code tool to infer the full compiler ID from a short name or direct ID
    def infer_compiler_id( compiler_name_or_id: str, compilers: list[dict[str, str]] ) -> str | None: """Infer the compiler ID from a name or ID string. Args: compiler_name_or_id: Either a compiler ID or name to match compilers: List of available compilers from the API Returns: Matching compiler ID if found, None otherwise Example: >>> compilers = [{"id": "gcc-12.2", "name": "GCC 12.2"}] >>> infer_compiler_id("gcc", compilers) "gcc-12.2" """ if compiler_name_or_id in [c["id"] for c in compilers]: compiler_id = compiler_name_or_id else: # Get the compiler ID from the name compiler_id = next( ( c["id"] for c in compilers if c["name"].lower().strip() == compiler_name_or_id.lower().strip() ), None, ) return compiler_id

Other Tools

Related Tools

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/torshepherd/compiler-explorer-mcp'

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