Skip to content
Latest (currently 2026.10.2) has the newest features, bug fixes, and CVE patches of Solo Enterprise for agentgateway.

For the complete documentation index, see llms.txt. Markdown versions of all docs pages are available by appending .md to any docs URL.

Code and search mode

Page as Markdown

Combine progressive disclosure and sandboxed execution with get_tool and run_code.

In code and search mode, an MCP backend exposes two meta tools instead of the upstream tool list:

  • get_tool looks up an upstream tool by name and returns its typed JavaScript API definition.
  • run_code executes JavaScript that calls the upstream tools in an embedded sandbox.

This mode pairs progressive disclosure with sandboxed execution, and so combines the benefits of Search mode and Code mode. Like Search mode, the full tool catalog never enters the model’s context, and the model discovers tools at runtime with get_tool. Like Code mode, the model composes multiple tool calls in a single script and only the final return value reaches the model.

The difference from Code mode is that the run_code description does not embed the typed API for every upstream tool. Instead, the model calls get_tool to fetch the definition for a specific tool, then writes a script that calls it. This keeps the model’s context small even when the backend fronts so many tools that embedding every definition in run_code would itself be too large.

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. If you already deployed this server for another tool mode, skip this step.

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
EOF

Step 2: Create the EnterpriseAgentgatewayBackend

Create an MCP backend with toolMode: CodeSearch. 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-search-backend
  namespace: default
spec:
  entMcp:
    toolMode: CodeSearch
    codeMode:
      timeout: 7s
      cpuTimeout: 2s
    targets:
      - name: fetcher
        static:
          host: mcp-website-fetcher.default.svc.cluster.local
          port: 80
          protocol: SSE
EOF

Step 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-search
  namespace: default
spec:
  parentRefs:
    - name: agentgateway-proxy
      namespace: agentgateway-system
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /mcp/code-search
      filters:
        - type: URLRewrite
          urlRewrite:
            path:
              type: ReplacePrefixMatch
              replacePrefixMatch: /mcp
      backendRefs:
        - name: mcp-code-search-backend
          group: enterpriseagentgateway.solo.io
          kind: EnterpriseAgentgatewayBackend
EOF

Step 4: Verify the connection

  1. Get the external address of the gateway and save the MCP endpoint in the MCP_URL environment 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-search"
    echo $MCP_URL
    1. Open a port-forward in a separate terminal.

      kubectl port-forward -n agentgateway-system svc/agentgateway-proxy 8080:80
    2. Then set the endpoint variable.

      export MCP_URL="http://localhost:8080/mcp/code-search"
  2. Initialize an MCP session and send the notifications/initialized acknowledgement. The session ID is returned in the mcp-session-id response 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"}'
  3. List the tools.

    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: Code and search mode exposes exactly two tools, get_tool and run_code. The upstream fetch tool is not in the list, and run_code does not embed a typed API for it. Instead, the run_code description instructs the model to use get_tool to discover a tool signature before calling it.

    data: {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"get_tool","description":"Get information about available tools. ... Available tools: [fetch]", ...},{"name":"run_code","description":"Execute code to achieve a goal.\n\nWrite JavaScript. ... Use get_tool to discover a tool's description and signature before writing code that calls it. ...", ...}]}}
  4. Look up the fetch tool with get_tool. Unlike Search mode, the result is the tool’s typed JavaScript API definition, which is the same signature that run_code accepts. The definition includes input field descriptions and any declared output schema. Tools that the caller is not authorized to use are filtered out.

    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":"get_tool","arguments":{"name":"fetch"}}}'

    Example output: The response contains the TypeScript function definition for the tool. This tool does not declare an output schema, so the return type is Promise<unknown>.

    data: {"jsonrpc":"2.0","id":3,"result":{"structuredContent":{"results":[{"typescript":"// 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"}]},"isError":false}}

    If the lookup does not match a tool, the response returns an empty results array, a no_match status, and the list of available tool names to guide the next lookup.

    data: {"jsonrpc":"2.0","id":3,"result":{"structuredContent":{"results":[],"status":"no_match","available_tools":["fetch"]},"isError":false}}
  5. Call run_code with a script that calls the fetch function you discovered 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":4,"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 success envelope on the happy path. Compilation, runtime, and timeout errors are returned as {"error": {"message": "...", "diagnostic": "..."}} instead.

    data: {"jsonrpc":"2.0","id":4,"result":{"structuredContent":{"success":{"first120":"<!doctype html><html lang=\"en\"><head><title>Example Domain</title>...","length":559}},"isError":false}}

Cleanup

You can remove the resources that you created in this guide.
kubectl delete httproute mcp-code-search -n default
kubectl delete enterpriseagentgatewaybackend mcp-code-search-backend -n default
kubectl delete deployment mcp-website-fetcher -n default
kubectl delete service mcp-website-fetcher -n default

Next steps

Check out how to use code mode to expose your existing OAS-compatible APIs as an MCP.