Skip to main content
Glama
azharlabs
by azharlabs

execute_cell

Execute a specific cell in a Jupyter notebook to run code and generate output using the notebook's kernel.

Instructions

Execute a specific cell in the notebook using a Jupyter kernel

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
notebook_pathYesAbsolute path to the Jupyter notebook file
cell_idYesCell ID or zero-based index of the cell to execute

Implementation Reference

  • The core handler function that executes the specified cell in the Jupyter notebook. It locates the cell by ID or index, uses a kernel session to execute the code, captures outputs, updates the notebook file with execution results, and returns formatted output or error.
    async executeCell(notebookPath, cellId) {
      try {
        const notebook = await this.readNotebook(notebookPath);
        
        // Find cell by ID or index
        let cellIndex = -1;
        let cell = null;
        
        if (typeof cellId === 'string') {
          // Search by cell ID
          cellIndex = notebook.cells.findIndex(c => c.id === cellId);
          if (cellIndex === -1) {
            throw new Error(`Cell with ID '${cellId}' not found`);
          }
        } else {
          // Treat as index
          cellIndex = cellId;
          this.validateCellIndex(notebook.cells, cellIndex);
        }
        
        cell = notebook.cells[cellIndex];
        
        if (cell.cell_type !== 'code') {
          throw new Error(`Cell ${cellId} is not a code cell (type: ${cell.cell_type})`);
        }
    
        // Get kernel session
        const session = await this.getKernelSession(notebookPath);
        const kernel = session.kernel;
    
        if (!kernel) {
          throw new Error('No kernel available for execution');
        }
    
        // Get cell source
        const source = Array.isArray(cell.source) ? cell.source.join('') : cell.source;
        
        if (!source.trim()) {
          return {
            content: [
              {
                type: "text",
                text: "Cell is empty, nothing to execute"
              }
            ]
          };
        }
    
        // Execute the code
        const future = kernel.requestExecute({ code: source });
        const outputs = [];
        let executionCount = null;
    
        // Collect outputs
        future.onIOPub = (msg) => {
          if (msg.header.msg_type === 'execute_result' || 
              msg.header.msg_type === 'display_data' ||
              msg.header.msg_type === 'stream' ||
              msg.header.msg_type === 'error') {
            outputs.push(msg.content);
          }
          
          if (msg.header.msg_type === 'execute_input') {
            executionCount = msg.content.execution_count;
          }
        };
    
        // Wait for execution to complete
        const reply = await future.done;
        
        // Update cell in notebook
        cell.execution_count = executionCount;
        cell.outputs = outputs.map(output => {
          // Convert Jupyter message format to notebook format
          if (output.output_type) {
            return output;
          } else {
            // Handle different message types
            const notebookOutput = {
              output_type: reply.content.status === 'error' ? 'error' : 'execute_result'
            };
            
            if (output.data) {
              notebookOutput.data = output.data;
              notebookOutput.metadata = output.metadata || {};
              notebookOutput.execution_count = executionCount;
            } else if (output.text) {
              notebookOutput.output_type = 'stream';
              notebookOutput.name = 'stdout';
              notebookOutput.text = output.text;
            }
            
            return notebookOutput;
          }
        });
    
        // Save updated notebook
        await this.writeNotebook(notebookPath, notebook);
    
        // Format output for display
        let outputText = `Executed cell ${cellId}\n`;
        
        if (reply.content.status === 'error') {
          outputText += `Error: ${reply.content.ename}: ${reply.content.evalue}`;
        } else {
          outputText += `Execution completed successfully`;
          
          if (outputs.length > 0) {
            outputText += '\n\nOutputs:';
            outputs.forEach((output, i) => {
              if (output.text) {
                outputText += `\n${Array.isArray(output.text) ? output.text.join('') : output.text}`;
              } else if (output.data && output.data['text/plain']) {
                const text = Array.isArray(output.data['text/plain']) 
                  ? output.data['text/plain'].join('')
                  : output.data['text/plain'];
                outputText += `\n${text}`;
              }
            });
          }
        }
    
        return {
          content: [
            {
              type: "text",
              text: outputText
            }
          ]
        };
        
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error executing cell: ${error.message}`
            }
          ],
          isError: true
        };
      }
    }
  • Input schema definition for the 'execute_cell' tool, specifying parameters notebook_path (string) and cell_id (string or integer).
    inputSchema: {
      type: "object",
      properties: {
        notebook_path: {
          type: "string",
          description: "Absolute path to the Jupyter notebook file"
        },
        cell_id: {
          type: ["string", "integer"],
          description: "Cell ID or zero-based index of the cell to execute"
        }
      },
      required: ["notebook_path", "cell_id"]
    }
  • src/index.js:378-379 (registration)
    Registration of the tool handler in the CallToolRequest switch statement, delegating execution to JupyterHandler's executeCell method.
    case "execute_cell":
      return await this.jupyterHandler.executeCell(args.notebook_path, args.cell_id);
  • src/index.js:238-255 (registration)
    Tool registration in the ListTools response, including name, description, and input schema.
    {
      name: "execute_cell",
      description: "Execute a specific cell in the notebook using a Jupyter kernel",
      inputSchema: {
        type: "object",
        properties: {
          notebook_path: {
            type: "string",
            description: "Absolute path to the Jupyter notebook file"
          },
          cell_id: {
            type: ["string", "integer"],
            description: "Cell ID or zero-based index of the cell to execute"
          }
        },
        required: ["notebook_path", "cell_id"]
      }
    },
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool executes a cell but doesn't describe what happens during execution (e.g., kernel state changes, output generation, error handling, or side effects like file modifications). For a mutation tool with zero annotation coverage, this leaves significant gaps in understanding its behavior and impact.

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 a single, clear sentence that efficiently conveys the core purpose without unnecessary details. It is front-loaded with the main action and resource, making it easy to parse. Every word earns its place, with no redundancy or fluff.

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

Completeness2/5

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

Given the complexity of executing a notebook cell (a mutation operation with potential side effects), no annotations, and no output schema, the description is incomplete. It lacks information on behavioral traits (e.g., what execution entails), error conditions, or return values. For a tool that interacts with a Jupyter kernel, more context is needed to use it effectively.

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%, with both parameters (notebook_path and cell_id) well-documented in the schema. The description adds no additional parameter semantics beyond what the schema provides, such as examples of cell_id formats or path requirements. The baseline score of 3 reflects adequate coverage by the schema alone.

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

Purpose4/5

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

The description clearly states the action ('execute') and resource ('a specific cell in the notebook'), and mentions the mechanism ('using a Jupyter kernel'). It distinguishes from siblings like edit_cell or get_cell_source by focusing on execution rather than modification or retrieval. However, it doesn't explicitly differentiate from potential execution-related siblings that might exist in other contexts.

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. It doesn't mention prerequisites (e.g., kernel availability), when not to use it (e.g., for read-only operations), or how it relates to siblings like bulk_edit_cells or trigger_vscode_reload. Usage is implied by the action but not explicitly contextualized.

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/azharlabs/mcp-jupyter-server'

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