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
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It does mention that compilation can fail and raises HTTPException, which is useful. However, it doesn't cover important behavioral aspects like whether compilation is synchronous/asynchronous, execution time limits, resource consumption, authentication requirements, or rate limits. The 'Raises' section adds some value but leaves significant gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (Args, Returns, Raises, Example) and front-loads the core purpose. Every sentence serves a purpose, though the parameter list could be more concise. The example is helpful but adds length. Overall, it's appropriately sized for a complex tool with many parameters.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (6 parameters, no annotations, no output schema), the description does a good job covering the essentials. It explains the purpose, parameters, return structure, and error conditions. The main gaps are behavioral details (execution characteristics, limits) and usage guidance relative to sibling tools. The return value documentation partially compensates for the missing output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description compensates well by listing all 7 parameters (including 'ctx' not in schema) with brief explanations. It provides meaningful context for each parameter beyond just naming them, especially for 'filters' and 'libraries'. However, it doesn't explain parameter interactions or provide format details for 'language' and 'compiler' values.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verb ('compile') and resource ('source code'), and distinguishes it from sibling tools like 'get_opcode_documentation' or 'list_compilers_for_language' which are informational rather than execution tools. The first sentence directly answers 'what does this tool do?'

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. While it's clear this is for compilation, there's no mention of prerequisites, when to use sibling tools like 'list_compilers_for_language' first, or what scenarios warrant using this tool over other compilation methods. The example shows usage but doesn't provide contextual guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other 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