Skip to main content
Glama

run_code

Run a short script once, server-side, against a project's own bindings — get the result + console logs back in one call. It replaces a throwaway debug endpoint or dozens of tool calls when inspecting data, trying a query variant, or running a one-off transformation.

code is an ES module whose default async function receives sw (the same database / files / search / ai bindings a deployed function gets) and returns a JSON-serializable value:

{
  "project_id": "my-saas",
  "code": "export default async function (sw) { const { data } = await sw.db.server.from('notes', { limit: 1 }); return data; }"
}

Declare application tables in db/schema.ts. Read them with sw.db.from for caller-scoped access or sw.db.server.from after authorizing the caller for server access. Write them with the corresponding structured methods, such as sw.db.server.insert. Raw query and batch use the separate raw SQL database on current projects. The script entry point above is for run_code. For a JSON route in api/, use export default sw.endpoint({ auth, handler }) and set auth explicitly. TypeScript infers the handler inputs and sw context. Use auth: 'none' only for a deliberately public route.

Runs with the project's OWN authority, not your developer key: no env secrets unless you pass include_env: true, no admin, no cross-project access, and outbound fetch is limited to public hosts. Returns { result, logs, duration_ms, error? }. result is capped at 256KB (truncated with a notice past that). logs keeps at most 100 entries. Each log message is cut at 64KB with a [truncated: …] marker at its end. All logs together stop at 4MB, followed by one final [logs truncated: …] entry. logs_truncated: true is set when entries were dropped by either limit (not when a single message is cut). error.message and error.stack are each cut at 64KB. A returned session over 64KB is not stored and the call answers SESSION_TOO_LARGE. timeout_ms defaults to 10000, max 30000.

Threading state across calls (opt-in): pass a stable session_id to carry explicit JSON state between runs. The saved JSON is exposed to your script as a read-only sw.session; a returned { session: {...} } object saves state for the next call (it is stored under that session_id, separately from result). Absent session_id = stateless, byte-identical to a normal run. This is explicit data you thread by id — NOT live-variable/closure persistence.

Tool call template

Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.

{
  "id": 1,
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "arguments": {
      "project_id": "<project_id>",
      "code": "<code>"
    },
    "name": "run_code"
  }
}

Input Schema

NameRequiredDescriptionDefault
argsNoPer-run string inputs (at most 16KiB UTF-8 JSON), passed as the frozen second argument to export default async (sw, args). Separate from env and saved sessions; omitted means an empty object. Secrets belong in project env.
codeYesES module source: export default async function (sw, args) { ...; return value }. args is a read-only object of per-run strings (empty when omitted); existing (sw) scripts also work. The JSON-serializable return value comes back as result.
project_idYesProject ID (UUID), subdomain, slug, or 'default'. Resolved server-side.
session_idNoOpt-in session key (<=128 chars, [A-Za-z0-9_-]). Loads saved JSON as a read-only sw.session before the run; a returned { session } persists for the next call (stored state capped at 64KB). Absent = stateless.
timeout_msNoAbort the script after N ms. Default 10000. Clamped to [1, 30000].
include_envNoExpose the project env vars as sw.env. Default false — off unless the script needs a secret.

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A4.5/5.0
Behavior5/5

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

Goes far beyond the annotations: the script runs with the project's own authority, not the developer key; no env secrets unless include_env is true; no admin or cross-project access; outbound fetch limited to public hosts. It also documents truncation limits (256KB result, 100 log entries, 64KB per message, 4MB total), the SESSION_TOO_LARGE failure, and the 10s default / 30s max timeout.

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

Conciseness3/5

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

The core is front-loaded and dense, but the middle of the description drifts into advice about authoring endpoints in api/ (sw.endpoint, auth: 'none', TypeScript inference) that does not help an agent call run_code. Those sentences cost length without earning their place in this tool's definition.

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?

Despite no output schema, the return contract is fully given ({ result, logs, duration_ms, error? }) with size caps and truncation markers. For a six-parameter, nested-schema, high-privilege execution tool, nothing essential is missing.

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?

Schema coverage is 100%, so baseline is 3, but the description adds real meaning the schema does not: session_id threading is explicit JSON state, not closure persistence, and absent session_id yields a byte-identical stateless run. Timeout and include_env semantics are also restated in context of what the script can reach.

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?

States a specific verb and resource — run a short server-side script once against the project's own bindings — and immediately distinguishes the use case from a throwaway endpoint or many tool calls. It also separates itself from the raw-query/batch path, so an agent can tell what this tool is versus the SQL siblings.

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

Usage Guidelines4/5

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

Gives concrete use cases (inspecting data, trying a query variant, one-off transformation) and notes that raw query and batch go through the separate raw SQL database. It lacks an explicit 'prefer db_query when you just need one query' exclusion, so the routing decision against named siblings is implied rather than spelled out.

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

Try in Browser

Glama MCP Gateway

Add one secure layer between your agents and this server.

Resources