> ## Documentation Index
> Fetch the complete documentation index at: https://ngrok.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use MCP Gateway with Code Mode

> Let an agent write TypeScript that calls MCP Gateway tools, with types generated from tools/list and parallel stateless HTTPS calls.

In Code Mode, an agent writes one script that calls many tools, instead of asking for one tool call per model turn.
The script runs in the agent's own sandbox, and each tool call inside it is an HTTPS request to [MCP Gateway](https://ngrok.com/docs/ai-gateway/mcp-gateway.md).
The gateway supplies the typed tool catalog and the call path.
It doesn't run the script.

A Code Mode harness does three things with the gateway:

1. Calls `tools/list` on `https://mcp.ngrok.ai` to get every tool the access key may call, with its `inputSchema` and `outputSchema`.
2. Generates TypeScript declarations from those schemas, so the model writes typed calls and the harness can typecheck the script before it runs.
3. Gives the script one function, `callTool(name, args)`, that sends one stateless `tools/call` request per call.

Upstream credentials stay in the gateway, so the sandbox holds only the access key.

## What you'll need

* An [access key](https://ngrok.com/docs/ai-gateway/concepts/access-keys.md) whose [access key configuration](https://ngrok.com/docs/ai-gateway/guides/access-key-configurations.md) allows the MCP servers and tools the script should reach.
  See [Control tool access](https://ngrok.com/docs/ai-gateway/mcp-gateway.md#control-tool-access).
* At least one MCP server registered in [MCP Gateway](https://ngrok.com/docs/ai-gateway/mcp-gateway.md#set-up-an-mcp-gateway).
* Node.js 22 or later.

## Send stateless calls

MCP protocol version `2026-07-28` needs no `initialize` request and no session.
Each request is one `POST https://mcp.ngrok.ai/` that carries everything the gateway needs:

| Part | Value |
| - | - |
| `Authorization` header | `Bearer <your access key>` |
| `Content-Type` header | `application/json` |
| `Accept` header | `application/json, text/event-stream;q=0.5` |
| `Mcp-Protocol-Version` header | `2026-07-28` |
| `Mcp-Method` header | The JSON-RPC method, such as `tools/list` or `tools/call` |
| `Mcp-Name` header | For `tools/call` only, the tool name from `params.name` |
| `params._meta` | `"io.modelcontextprotocol/protocolVersion": "2026-07-28"` and `"io.modelcontextprotocol/clientCapabilities": {}` |

The headers must match the body.
A mismatch returns HTTP 400 with JSON-RPC error `-32020`, such as `Mcp-Name must match params.name`.

The `Accept` header above returns JSON for every method.
When `application/json` and `text/event-stream` have equal weight, the gateway streams `tools/call` results as server-sent events, which a script then has to parse.

```bash theme={"theme":{"light":"css-variables","dark":"css-variables"}}
curl https://mcp.ngrok.ai/ \
  -H "Authorization: Bearer $MCP_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream;q=0.5" \
  -H "Mcp-Protocol-Version: 2026-07-28" \
  -H "Mcp-Method: tools/list" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {
      "_meta": {
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientCapabilities": {}
      }
    }
  }'
```

The result holds every tool the key may call, each named `<label>__<tool>`, with the upstream descriptor unchanged.
That includes `inputSchema`, `outputSchema` when the upstream declares one, and annotations.
`tools/list` is free and returns the full catalog in one response, with no pagination.

## Example harness

This TypeScript file lists the tools, writes their declarations to `mcp-tools.d.ts`, and runs a script with parallel calls.
It uses [`json-schema-to-typescript`](https://www.npmjs.com/package/json-schema-to-typescript) for the type generation.

```bash theme={"theme":{"light":"css-variables","dark":"css-variables"}}
npm install json-schema-to-typescript tsx
export MCP_GATEWAY_API_KEY="<your access key>"
```

Save the file as `codemode.ts`.
The script at the end calls `docs__search` from the [setup example](https://ngrok.com/docs/ai-gateway/mcp-gateway.md#set-up-an-mcp-gateway); change it to a tool your key can call.

```ts codemode.ts theme={"theme":{"light":"css-variables","dark":"css-variables"}}
import { writeFile } from "node:fs/promises";
import { compile, type JSONSchema } from "json-schema-to-typescript";

const GATEWAY_URL = "https://mcp.ngrok.ai/";
const PROTOCOL_VERSION = "2026-07-28";
const API_KEY = process.env.MCP_GATEWAY_API_KEY!;

interface Tool {
  name: string; // "<label>__<tool>", such as "docs__search"
  description?: string;
  inputSchema: JSONSchema;
  outputSchema?: JSONSchema;
}

interface CallToolResult {
  content: unknown[];
  structuredContent?: unknown;
  isError?: boolean;
}

// Each request is one stateless POST: no initialize, no session ID.
// The protocol version and client capabilities travel in params._meta,
// and the Mcp-* headers repeat the method and tool name from the body.
async function rpc<T>(method: string, params: Record<string, unknown> = {}): Promise<T> {
  const headers: Record<string, string> = {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
    // Prefer JSON. Ties return tools/call results as an SSE stream.
    Accept: "application/json, text/event-stream;q=0.5",
    "Mcp-Protocol-Version": PROTOCOL_VERSION,
    "Mcp-Method": method,
  };
  if (typeof params.name === "string") headers["Mcp-Name"] = params.name;

  const res = await fetch(GATEWAY_URL, {
    method: "POST",
    headers,
    body: JSON.stringify({
      jsonrpc: "2.0",
      id: crypto.randomUUID(),
      method,
      params: {
        ...params,
        _meta: {
          "io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
          "io.modelcontextprotocol/clientCapabilities": {},
        },
      },
    }),
  });
  const body = await res.json();
  if (body.error) {
    throw new Error(`${method} failed (HTTP ${res.status}): ${body.error.code} ${body.error.message}`);
  }
  return body.result as T;
}

export async function listTools(): Promise<Tool[]> {
  const { tools } = await rpc<{ tools: Tool[] }>("tools/list");
  return tools;
}

// Turns every tool into a typed function signature the model can read and
// the harness can typecheck generated scripts against. Each tool compiles
// into its own namespace, because schemas reuse titles such as "Service".
export async function generateTypes(tools: Tool[]): Promise<string> {
  const declarations = await Promise.all(
    tools.map(async (tool) => {
      const id = tool.name.replace(/\W/g, "_");
      const signature: JSONSchema = {
        type: "object",
        properties: { input: tool.inputSchema, output: tool.outputSchema ?? {} },
        required: ["input", "output"],
        additionalProperties: false,
      };
      const types = await compile(signature, "Signature", { bannerComment: "" });
      const doc = tool.description ? `/** ${tool.description.replace(/\*\//g, "* /")} */\n` : "";
      return `export declare namespace ${id} {\n${types}}\n${doc}` +
        `export declare function ${id}(args: ${id}.Signature["input"]): Promise<${id}.Signature["output"]>;\n`;
    }),
  );
  return declarations.join("\n");
}

// The one function a sandboxed script gets. It returns structuredContent
// when the tool declares an outputSchema, otherwise the content blocks.
export async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
  const result = await rpc<CallToolResult>("tools/call", { name, arguments: args });
  if (result.isError) {
    throw new Error(`${name} returned an error: ${JSON.stringify(result.content)}`);
  }
  return result.structuredContent ?? result.content;
}

const tools = await listTools();
await writeFile("mcp-tools.d.ts", await generateTypes(tools));
console.log(`Wrote types for ${tools.length} tools to mcp-tools.d.ts`);

// A script the model writes: independent calls run as parallel HTTP requests.
const [servers, ...results] = await Promise.all([
  callTool("ngrok-gateway__list_servers", {}),
  ...["traffic policy", "rate limiting", "OAuth"].map((query) =>
    callTool("docs__search", { query }),
  ),
]);
console.log(JSON.stringify({ servers, results }, null, 2));
```

Run it:

```bash theme={"theme":{"light":"css-variables","dark":"css-variables"}}
npx tsx codemode.ts
```

The first line of output reads `Wrote types for <n> tools to mcp-tools.d.ts`.
Each tool becomes a declaration like this one, which the harness shows to the model and typechecks scripts against:

```ts theme={"theme":{"light":"css-variables","dark":"css-variables"}}
export declare namespace docs__search {
  export interface Signature {
    input: {
      query: string;
      [k: string]: unknown;
    };
    output: unknown;
  }
}
/** Search the docs. */
export declare function docs__search(args: docs__search.Signature["input"]): Promise<docs__search.Signature["output"]>;
```

A script that passes `{ q: "oauth" }` fails the typecheck with `Property 'query' is missing`, before any call reaches the gateway.
A tool without an `outputSchema` returns `unknown`, so the script has to inspect its content blocks.

## Run calls in parallel

Each `callTool` is an independent HTTPS request, so `Promise.all` sends them at the same time.
The script's wall time is close to its slowest call, not the sum of all of them.

Don't use JSON-RPC batches for Code Mode.
The gateway accepts batches only on protocol version `2025-03-26`, runs the items one after another, and limits a batch to 16 items.

## Handle errors and cost

* A tool that fails returns a result with `isError: true`, which the example turns into a thrown error.
  `Promise.all` rejects on the first one; use `Promise.allSettled` when the script should keep the other results.
* A denied tool returns JSON-RPC error `-32003`, and an account with no credits returns HTTP 402.
  See [Control tool access](https://ngrok.com/docs/ai-gateway/mcp-gateway.md#control-tool-access) and [Pricing](https://ngrok.com/docs/ai-gateway/mcp-gateway.md#pricing).
* Every completed `tools/call` is one billable operation, including an `isError` result.
  A script that loops over a tool bills each iteration.
* Each call can run up to the server's call timeout.
  See [Limits](https://ngrok.com/docs/ai-gateway/mcp-gateway.md#limits).
* Each call appears as its own request in **Activity** under **MCP calls**.

Give the sandbox a key whose configuration allows only the servers and tools the script needs, and set an expiry on the key when the script is short-lived.

## Use Claude Code's Code Mode

[Claude Code's Code Mode](https://code.claude.com/docs/en/code-mode) is experimental and off by default.
With it on, Claude writes JavaScript that calls MCP tools by name, so the tools of an MCP Gateway you added with `claude mcp add` work in that code like any other MCP server's tools.
Claude Code does the type generation and the calls itself; you don't need the harness on this page.

```bash theme={"theme":{"light":"css-variables","dark":"css-variables"}}
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude
```

> [!WARNING]
>
> Claude Code's Code Mode doesn't start when Claude Code sends model requests through an LLM gateway, which includes the [AI Gateway at `gateway.ngrok.ai`](https://ngrok.com/docs/ai-gateway/agents/claude-code), or when it authenticates with `ANTHROPIC_AUTH_TOKEN` or an API key helper.
> To use Code Mode, connect Claude Code to Anthropic directly.
> MCP Gateway is a separate MCP server, so it works in Code Mode either way.

## Related

* [MCP Gateway](https://ngrok.com/docs/ai-gateway/mcp-gateway.md)
* [Access key configurations](https://ngrok.com/docs/ai-gateway/guides/access-key-configurations.md)
* [Use Claude Code with the AI Gateway](https://ngrok.com/docs/ai-gateway/agents/claude-code.md)
* [Credits](https://ngrok.com/docs/ai-gateway/concepts/credits.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.