Skip to main content
Glama
torshepherd

Compiler Explorer MCP

by torshepherd

compile_code

Compile source code with specified compilers and options to generate assembly output, test compiler behavior, and analyze compilation results across different programming languages.

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
sourceYes
languageYes
compilerYes
optionsNo
filtersNo
librariesNo

Implementation Reference

  • The main MCP tool handler function for 'compile_code'. It resolves the compiler ID based on the language, logs progress using the provided Context, and delegates the actual compilation to the CompilerExplorerClient instance.
    @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 BaseModel defining the schema for CompilationFilters, which configures filtering options for compiler output in 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 BaseModel defining the schema for Library dependencies used in the 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
  • CompilerExplorerClient.compile_code method: performs the actual API request to Compiler Explorer for compiling the code with given options, filters, and libraries.
    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
        )
  • infer_compiler_id utility: matches the provided compiler name against available compilers to find the exact compiler 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

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