Skip to main content
Glama
georgejeffers

Gemini MCP Server

Code Execution

code_execution
Read-only

Execute Python code in a sandboxed environment based on natural language prompts. Generate and run code, then return both the code and execution results.

Instructions

Execute Python code in a sandboxed environment. Gemini generates and runs code, returning both the code and results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesDescribe what code to write and execute
modelNoGemini model to usegemini-2.5-flash
temperatureNoSampling temperature
maxOutputTokensNoMaximum output tokens

Implementation Reference

  • Main handler function that executes Python code by calling Gemini's code execution tool. Takes prompt, model, temperature, and maxOutputTokens as input, processes the response to extract text, executable code, and execution results, then returns formatted output.
    async ({ prompt, model, temperature, maxOutputTokens }) => {
      try {
        const response = await ai.models.generateContent({
          model,
          contents: prompt,
          config: {
            temperature,
            maxOutputTokens,
            tools: [{ codeExecution: {} }],
          },
        });
    
        const parts = response.candidates?.[0]?.content?.parts ?? [];
        const sections: string[] = [];
    
        for (const part of parts) {
          if (part.text) {
            sections.push(part.text);
          } else if (part.executableCode) {
            sections.push(`\`\`\`python\n${part.executableCode.code}\n\`\`\``);
          } else if (part.codeExecutionResult) {
            const outcome = part.codeExecutionResult.outcome ?? 'UNKNOWN';
            sections.push(`**Execution result** (${outcome}):\n\`\`\`\n${part.codeExecutionResult.output}\n\`\`\``);
          }
        }
    
        return {
          content: [{ type: 'text' as const, text: sections.join('\n\n') }],
        };
      } catch (error) {
        return formatToolError(error);
      }
    },
  • Registers the code_execution tool with the MCP server. Defines tool metadata (title, description, annotations), input schema using Zod validation, and connects the handler function.
    export function register(server: McpServer, ai: GoogleGenAI): void {
      server.registerTool(
        'code_execution',
        {
          title: 'Code Execution',
          description: 'Execute Python code in a sandboxed environment. Gemini generates and runs code, returning both the code and results.',
          inputSchema: {
            prompt: z.string().min(1).describe('Describe what code to write and execute'),
            model: TextModel.default('gemini-2.5-flash').describe('Gemini model to use'),
            temperature: z.number().min(0).max(2).optional().describe('Sampling temperature'),
            maxOutputTokens: z.number().min(1).optional().describe('Maximum output tokens'),
          },
          annotations: {
            readOnlyHint: true,
            destructiveHint: false,
            openWorldHint: true,
          },
        },
        async ({ prompt, model, temperature, maxOutputTokens }) => {
          try {
            const response = await ai.models.generateContent({
              model,
              contents: prompt,
              config: {
                temperature,
                maxOutputTokens,
                tools: [{ codeExecution: {} }],
              },
            });
    
            const parts = response.candidates?.[0]?.content?.parts ?? [];
            const sections: string[] = [];
    
            for (const part of parts) {
              if (part.text) {
                sections.push(part.text);
              } else if (part.executableCode) {
                sections.push(`\`\`\`python\n${part.executableCode.code}\n\`\`\``);
              } else if (part.codeExecutionResult) {
                const outcome = part.codeExecutionResult.outcome ?? 'UNKNOWN';
                sections.push(`**Execution result** (${outcome}):\n\`\`\`\n${part.codeExecutionResult.output}\n\`\`\``);
              }
            }
    
            return {
              content: [{ type: 'text' as const, text: sections.join('\n\n') }],
            };
          } catch (error) {
            return formatToolError(error);
          }
        },
      );
    }
  • Input schema definition using Zod. Validates prompt (required string), model (text model enum with default), temperature (optional number 0-2), and maxOutputTokens (optional number).
    inputSchema: {
      prompt: z.string().min(1).describe('Describe what code to write and execute'),
      model: TextModel.default('gemini-2.5-flash').describe('Gemini model to use'),
      temperature: z.number().min(0).max(2).optional().describe('Sampling temperature'),
      maxOutputTokens: z.number().min(1).optional().describe('Maximum output tokens'),
    },
  • TextModel enum schema defining allowed Gemini models for text/code execution: gemini-2.5-flash, gemini-2.5-pro, and various preview versions. Used as model parameter in code_execution tool.
    export const TextModel = z.enum([
      'gemini-2.5-flash',
      'gemini-2.5-pro',
      'gemini-3-flash-preview',
      'gemini-3-pro-preview',
      'gemini-3.1-pro-preview',
    ]);
    export type TextModel = z.infer<typeof TextModel>;
  • formatToolError helper function that formats error objects into a standardized MCP response structure with isError flag, used by the code_execution handler for error handling.
    export function formatToolError(error: unknown) {
      const text = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: 'text' as const, text }],
        isError: true,
      };
    }
Behavior4/5

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

Annotations already declare readOnlyHint=true, destructiveHint=false, and openWorldHint=true, covering safety and scope. The description adds valuable context about the sandboxed environment and that Gemini both generates and runs the code, which clarifies the execution flow beyond what annotations provide.

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

Conciseness5/5

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

The description is two sentences that efficiently convey the core functionality and agent role without unnecessary details. It's front-loaded with the main purpose and wastes no words, making it easy to parse quickly.

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?

For a tool with good annotations (covering safety and scope) and full schema coverage, the description adds useful context about the sandbox and Gemini's role. However, without an output schema, it could benefit from mentioning return values (e.g., code and results format), though it's not strictly required.

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

Parameters3/5

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

Schema description coverage is 100%, so parameters are fully documented in the schema. The description doesn't add any parameter-specific details beyond what the schema provides, such as explaining the prompt format or model differences. Baseline 3 is appropriate given the high schema coverage.

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 specific action ('Execute Python code'), target resource ('in a sandboxed environment'), and agent role ('Gemini generates and runs code'). It distinguishes from sibling tools like chat or generate_text by focusing on code execution rather than conversation or text generation.

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

Usage Guidelines3/5

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

The description implies usage for Python code execution tasks but doesn't explicitly state when to use this tool versus alternatives like generate_text for non-code tasks or edit_image for image editing. No exclusions or specific contexts are provided beyond the general purpose.

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/georgejeffers/gemini-mcp-server'

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