For the complete documentation index, see llms.txt. Markdown versions of all docs pages are available by appending .md to any docs URL.
Code mode
Verified : Automated tests passed for: End-to-end run: Every step ran in a fresh test environment and the results were checked.Expose a single run_code tool so that the LLM composes multiple MCP calls in one script.
In Code mode, an MCP backend presents a single run_code tool to the client. The model submits JavaScript that calls the upstream MCP tools, and the gateway executes the script in an embedded sandbox. Only the final return value reaches the model, which keeps the model’s context small even when the workflow spans many tool calls.
Code mode trades the tool catalog for a scripting interface rather than disclosing tools on demand. For progressive disclosure, where the model looks up one tool definition at a time, see Search mode or Code and search mode.
For background and a comparison with the other tool modes, see MCP tool modes.
Before you begin
Install the Solo Enterprise for agentgateway control plane by following the quick start guide.Step 1: Deploy an MCP server
Deploy a sample MCP server that exposes a single fetch tool.
kubectl apply -f- <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
name: mcp-website-fetcher
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: mcp-website-fetcher
template:
metadata:
labels:
app: mcp-website-fetcher
spec:
containers:
- name: mcp-website-fetcher
image: ghcr.io/peterj/mcp-website-fetcher:main
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8000
name: http
---
apiVersion: v1
kind: Service
metadata:
name: mcp-website-fetcher
namespace: default
labels:
app: mcp-website-fetcher
spec:
selector:
app: mcp-website-fetcher
ports:
- name: http
port: 80
targetPort: 8000
EOFStep 2: Create the EnterpriseAgentgatewayBackend
Create an MCP backend with toolMode: Code. The optional codeMode settings cap how long a single run_code execution can run. timeout caps real elapsed time and defaults to 60s. cpuTimeout caps CPU time and defaults to 1s.
kubectl apply -f- <<EOF
apiVersion: enterpriseagentgateway.solo.io/v1alpha1
kind: EnterpriseAgentgatewayBackend
metadata:
name: mcp-code-backend
namespace: default
spec:
entMcp:
toolMode: Code
codeMode:
timeout: 7s
cpuTimeout: 2s
targets:
- name: fetcher
static:
host: mcp-website-fetcher.default.svc.cluster.local
port: 80
protocol: SSE
EOFStep 3: Route traffic to the backend
Attach the backend to your Gateway with an HTTPRoute. The path prefix is rewritten to /mcp so the upstream MCP server sees its expected path.
kubectl apply -f- <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: mcp-code
namespace: default
spec:
parentRefs:
- name: agentgateway-proxy
namespace: agentgateway-system
rules:
- matches:
- path:
type: PathPrefix
value: /mcp/code
filters:
- type: URLRewrite
urlRewrite:
path:
type: ReplacePrefixMatch
replacePrefixMatch: /mcp
backendRefs:
- name: mcp-code-backend
group: enterpriseagentgateway.solo.io
kind: EnterpriseAgentgatewayBackend
EOFStep 4: Verify the connection
Get the external address of the gateway and save the MCP endpoint in the
MCP_URLenvironment variable. The remaining commands in this step reuse this variable, so the curl examples work for both connection types.export INGRESS_GW_ADDRESS=$(kubectl get svc -n agentgateway-system agentgateway-proxy -o jsonpath="{.status.loadBalancer.ingress[0]['hostname','ip']}") echo $INGRESS_GW_ADDRESS export MCP_URL="http://${INGRESS_GW_ADDRESS}/mcp/code" echo $MCP_URLOpen a port-forward in a separate terminal.
kubectl port-forward -n agentgateway-system svc/agentgateway-proxy 8080:80Then set the endpoint variable.
export MCP_URL="http://localhost:8080/mcp/code"
Initialize an MCP session and send the
notifications/initializedacknowledgement. The session ID is returned in themcp-session-idresponse header.curl -sS -D /tmp/hdr -o /tmp/init -X POST "$MCP_URL" \ -H 'Content-Type: application/json' \ -H 'Accept: application/json, text/event-stream' \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' SID=$(awk -F': *' 'tolower($1)=="mcp-session-id"{gsub(/\r/,"",$2);print $2}' /tmp/hdr) curl -sS -X POST "$MCP_URL" \ -H "Mcp-Session-Id: $SID" \ -H 'Content-Type: application/json' \ -H 'Accept: application/json, text/event-stream' \ -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'List the tools. Code mode exposes exactly one:
run_code. The description contains a typed JavaScript API for each upstream tool the caller is authorized to use. The generated API includes input field descriptions and any declared output schema.curl -sS -X POST "$MCP_URL" \ -H "Mcp-Session-Id: $SID" \ -H 'Content-Type: application/json' \ -H 'Accept: application/json, text/event-stream' \ -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'Example output (truncated):
data: {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"run_code","description":"... Available API:\n```js\n// Fetches a website and returns its content\ntype Input = {\n // URL to fetch\n url: string,\n};\nasync function fetch(input: Input): Promise<unknown>;\n\n```\n", ...}]}}Tools that declare an output schema also include a
type Outputblock and returnPromise<Output>. Tools that do not declare an output schema returnPromise<unknown>.Call
run_codewith a script that fetches a URL and returns only the fields you need. The full HTML never enters the model’s context; only the projected value does.curl -sS -X POST "$MCP_URL" \ -H "Mcp-Session-Id: $SID" \ -H 'Content-Type: application/json' \ -H 'Accept: application/json, text/event-stream' \ -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"run_code","arguments":{"code":"const r = await fetch({url: \"https://example.com\"}); ({first120: String(r).slice(0,120), length: String(r).length})"}}}'Example output: The result is wrapped in a
successenvelope on the happy path. Compilation, runtime, and timeout errors are returned as{"error": {"message": "...", "diagnostic": "..."}}instead.data: {"jsonrpc":"2.0","id":3,"result":{"structuredContent":{"success":{"first120":"<!doctype html><html lang=\"en\"><head>...","length":528}},"isError":false}}
Cleanup
kubectl delete httproute mcp-code -n default
kubectl delete enterpriseagentgatewaybackend mcp-code-backend -n default
kubectl delete deployment mcp-website-fetcher -n default
kubectl delete service mcp-website-fetcher -n defaultNext steps
Check out how to use code mode to expose your existing OAS-compatible APIs as an MCP.