Skip to main content
Glama

Execute Code

ctx_execute

Execute code in a sandboxed subprocess to filter, aggregate, or transform data, returning only concise summaries instead of raw output.

Instructions

Run code in a sandboxed subprocess. Languages: javascript, shell, python, perl.

Think-in-Code — the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.

Concrete shape — analyze 47 source files without reading any of them: ctx_execute(language: "javascript", code: const fs = require('fs'); const files = fs.readdirSync('src').filter(f => f.endsWith('.ts')); files.forEach(f => { const lines = fs.readFileSync('src/'+f,'utf8').split('\\n').length; console.log(f + ': ' + lines + ' lines'); }); ) // 47 files analyzed, 15,314 LoC summarized — output ~3.6 KB instead of 47 Read() calls = ~700 KB.

WHEN:

  • You intend to derive an answer FROM data (filter, count, aggregate, parse, compare, transform) — do the derivation in code and print only the answer

  • Output shape or size cannot be predicted before execution (recursive finds, repo-wide greps, list endpoints, query results, log scans)

  • You would otherwise read raw output and then mentally compute — that compute belongs here, in code, where its inputs stay out of your conversation

  • You need to keep a long-running process alive (dev server, watcher, daemon) — pass background: true to detach on timeout instead of killing the process

  • The output may legitimately be large but you only want recall-by-topic later — pass an intent string; outputs over ~5KB are auto-indexed into the knowledge base and only the section titles + previews come back, retrievable via ctx_search

WHEN NOT:

  • Single observational command whose entire short output you intend to consume verbatim (whoami, pwd, git status on a clean tree) — Bash is simpler

  • File mutations (Edit/Write) or navigation (cd/ls) — Bash is the right surface

  • You already know the output is one short fixed line and you want to read it as-is

RETURNS: Only what your code prints. Wrap risky calls in try/catch — uncaught errors go to stderr and may leak more than intended. When intent is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.

EXAMPLE: ctx_execute(language: "shell", code: "npm test 2>&1 | grep -E '(FAIL|✗|×|Error:|Tests +.*(failed|passed))' | head -60") EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(${hooks.length} hook-related issues)")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
languageYesRuntime language
codeYesSource code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context.
timeoutNoMax execution time in ms. When omitted, no server-side timer fires — the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT).
backgroundNoKeep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts — the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background.
intentNoWhat you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews — not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'. TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.
Behavior5/5

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

Despite no annotations, the description fully discloses behavioral traits: sandboxing, only printed output returned, background mode, intent auto-indexing, timeout behavior, error handling, and the memory-conscious philosophy. No contradictions.

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 and front-loaded core statement. However, it is somewhat verbose with extended philosophy explanation; a slightly more concise version could be equally informative without the lengthy example.

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

Completeness5/5

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

Given the tool's complexity with 5 parameters and no output schema, the description completely covers all aspects: parameters, returns, error handling, examples, and even references sibling tools like ctx_search for retrieval after intent use.

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

Parameters5/5

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

All 5 parameters are documented in the schema (100% coverage), but the description adds substantial value by explaining the rationale behind timeout, background pitfalls, intent usage with search tips, and output print methods. This goes well beyond the schema.

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 it runs code in a sandboxed subprocess with explicit supported languages, and the WHEN NOT section distinguishes it from simpler tools like Bash. The verb and resource are specific and the examples solidify its purpose.

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

Usage Guidelines5/5

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

The WHEN and WHEN NOT sections provide explicit guidance on when to use this tool, including alternatives like Bash for simple commands and mentioning background usage. This is excellent decision support.

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/mksglu/context-mode'

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