Skip to main content

Configuring Copilot CLI Isolation via the GitHub Copilot SDK

In the previous post, we walked through local sandboxing in the Copilot CLI: enable it with /sandbox enable, tune filesystem and network rules through the TUI, and your agent's shell execution is isolated by Microsoft MXC. Simple, useful, done.

But if you're building with the Copilot SDK, embedding the agent runtime into your own .NET application, you can't type /sandbox enable into a session you're programmatically orchestrating. So the question becomes: how do you get the same isolation guarantees when you own the host?

The good news: sandbox support is coming to the SDK as a preview feature. The entry point is Session.Rpc.Options.UpdateAsync, and it lets you push a sandbox configuration into a running session from code.

Preview caveat: this API is behind the experimental surface of the SDK. It's real, it works, but the shape may change before it stabilises. Treat it as preview-quality and don't build production contracts on top of it just yet.

What you're actually configuring

Before looking at code, it's worth understanding what the SDK sandbox does and doesn't do — because it's the same underlying thing as the CLI sandbox.

The CLI's /sandbox command writes a configuration into settings.json and the MXC isolation layer picks it up. The SDK's Session.Rpc.Options.UpdateAsync pushes that same configuration into a session over the JSON-RPC channel that the SDK uses to communicate with the Copilot CLI process it manages. MXC still does the actual isolation. You're just providing the config programmatically rather than interactively.

What the sandbox isolates: shell command execution that the Copilot agent initiates on your behalf. Same scope as the CLI: filesystem access, network connectivity, system capabilities.

What it doesn't replace: OnPermissionRequest. That's still your gate for deciding whether to approve a tool call at all. The sandbox is about constraining what an approved tool call can reach. The two are complementary.

The basic pattern

The key pieces:

  1. Create a session as normal, with an OnPermissionRequest handler
  2. Call Session.Rpc.Options.UpdateAsync with a sandboxConfig parameter
  3. Pass the sandbox configuration as a JsonElement (loaded from file or constructed inline)
  4. Then run your session as normal — sandbox is active for all subsequent tool execution
using GitHub.Copilot;
using GitHub.Copilot.Rpc;
using System.Text.Json;

await using var client = new CopilotClient();

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    OnPermissionRequest = async (request, invocation) =>
    {
        return PermissionDecision.ApproveOnce();
    }
});

// Load sandbox config from a JSON file alongside your application
var sandboxConfig = JsonSerializer.Deserialize<SandboxConfig>(
    File.ReadAllText("sandbox-config.json"));

// Push the sandbox configuration into the session
await Session.Rpc.Options.UpdateAsync(sandboxConfig: sandboxConfig);

// Now run the agent — tool execution is sandboxed
await session.SendAndWaitAsync($"<enquiry>{Enquiry}</enquiry>");

The Session.Rpc.Options surface is the SDK's escape hatch into the lower-level JSON-RPC options layer, which is why it lands in the Rpc namespace rather than on the session directly. The UpdateAsync method accepts a named sandboxConfig parameter of type JsonElement, mirroring the structure the CLI would write to settings.json.

The sandbox configuration file

The sandbox-config.json you pass follows the same schema as the CLI's sandbox configuration. Here's a realistic starting point for a .NET project doing dependency analysis:

{
  "enabled": true,
  "addCurrentWorkingDirectory": true,
  "sandboxMcpServers": true,
  "sandboxLspServers": true,
  "userPolicy": {
    "filesystem": {
      "readwritePaths": [],
      "readonlyPaths": [
        "C:\\Users\\user\\.nuget\\packages",
        "C:\\Program Files\\dotnet"
      ],
      "deniedPaths": [],
      "clearPolicyOnExit": true
    },
    "network": {
      "allowOutbound": true,
      "allowLocalNetwork": false,
      "allowedHosts": [
        "api.nuget.org",
        "api.github.com"
      ],
      "blockedHosts": []
    }
  }
}

A few things worth noting about the structure:

addCurrentWorkingDirectory automatically grants read/write access to the session's working directory — you don't need to hardcode it in readwritePaths. sandboxMcpServers and sandboxLspServers extend the isolation boundary to MCP and LSP server processes as well, not just shell commands.

Within userPolicy, filesystem access is split across three explicit lists: readwritePaths, readonlyPaths, and deniedPaths. The network side has a coarser toggle (allowOutbound, allowLocalNetwork) plus per-host overrides via allowedHosts and blockedHosts. clearPolicyOnExit ensures the sandbox policy doesn't linger after the session ends.

Building the config inline

Externalising to a file is the pragmatic default: it lets you tweak isolation rules without recompiling. But there are scenarios where you want to construct the configuration dynamically — for example, scoping the filesystem allowlist to the current session's working directory:

var sandboxConfig = JsonSerializer.SerializeToElement<SandboxConfig>(new
{
    enabled = true,
    filesystem = new[]
    {
        new { path = workingDirectory, permission = "readWrite" },
        new { path = nugetPackagesPath, permission = "read" }
    },
    network = new[]
    {
        new { host = "api.nuget.org", access = "allow" }
    }
});

await Session.Rpc.Options.UpdateAsync(sandboxConfig: sandboxConfig);

JsonSerializer.SerializeToElement gives you a SandboxConfig object from an anonymous object without going via a string round-trip.

Updating the config mid-session

UpdateAsync can be called more than once. If your session has phases with different access requirements — say, a dependency resolution phase that needs NuGet access, followed by a code generation phase that shouldn't — you can tighten or loosen the configuration at each transition:

// Phase 1: dependency resolution — NuGet access open
await session.Rpc.Options.UpdateAsync(sandboxConfig: JsonElement.Parse("""
{
  "enabled": true,
  "addCurrentWorkingDirectory": true,
  "sandboxMcpServers": true,
  "sandboxLspServers": true,
  "userPolicy": {
    "filesystem": {
      "readwritePaths": [],
      "readonlyPaths": ["C:\\Users\\user\\.nuget\\packages"],
      "deniedPaths": [],
      "clearPolicyOnExit": true
    },
    "network": {
      "allowOutbound": true,
      "allowLocalNetwork": false,
      "allowedHosts": ["api.nuget.org"],
      "blockedHosts": []
    }
  }
}
"""));

await session.SendAndWaitAsync("Analyse the project's dependency tree");

// Phase 2: code generation — lock down network entirely
await session.Rpc.Options.UpdateAsync(sandboxConfig: JsonElement.Parse("""
{
  "enabled": true,
  "addCurrentWorkingDirectory": true,
  "sandboxMcpServers": true,
  "sandboxLspServers": true,
  "userPolicy": {
    "filesystem": {
      "readwritePaths": ["D:\\projects\\myapp\\src"],
      "readonlyPaths": [],
      "deniedPaths": [],
      "clearPolicyOnExit": true
    },
    "network": {
      "allowOutbound": false,
      "allowLocalNetwork": false,
      "allowedHosts": [],
      "blockedHosts": []
    }
  }
}
"""));

await session.SendAndWaitAsync("Refactor the data access layer");

This is where the SDK model becomes genuinely more powerful than the CLI's interactive /sandbox configuration: you can drive isolation policy from your application logic, not just set it once at session start.

OnPermissionRequest is still your first line

The sandbox constrains what approved tool calls can reach. OnPermissionRequest controls whether a tool call gets approved at all. They're doing different jobs, and you want both.

A sensible pattern is to log at the permission handler, allow what makes sense for the task, and rely on the sandbox to enforce the boundary underneath:

OnPermissionRequest = async (request, invocation) =>
{
    logger.LogInformation(
        "Permission request: {Kind} - {Description}",
        request.Kind,
        invocation.Description);

    // Only allow bash execution — file operations are fine,
    // but direct shell access gets logged and approved with full sandbox context
    if (request.Kind == "shell")
    {
        logger.LogWarning("Shell execution requested: {Command}", invocation.Description);
    }

    return PermissionDecision.ApproveOnce();
}

With the sandbox active, approving a shell command means it runs under MXC constraints — it can only reach what your sandbox config allows. The permission log still gives you an audit trail of what the agent attempted.

Popular posts from this blog

Podman– Command execution failed with exit code 125

After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

Cache stampede: when our cache turned against us

While investigating some performance issues, we ran into an ASP.NET Core API that cached a fairly expensive aggregation query for 60 seconds. Under normal load, that was fine: one request rebuilds the cache, everyone else reads from it. Under peak load, dozens of requests would arrive in that same expiry window, all see a cache miss, and all fire the same expensive query in parallel. The database didn't like that. That was the moment when our caching layer stopped helping and started hurting. A burst of requests comes in at the same time, all miss the cache, and all go hammer the database or the downstream API at once. That's a cache stampede . The cache was supposed to protect our backend, and for a few hundred milliseconds it did the opposite. Why this happens IMemoryCache.GetOrCreate (and its async sibling) looks like it protects you, but it doesn't add any locking on its own. Look at the naive version: public async Task<Report> GetReportAsync(string key) ...

A complex system designed from scratch never works

A few years ago, I worked as an architect on a big mainframe rewrite. I still count it as one of my failures. Not because the technology was wrong, but because I couldn't convince the management team to simplify the approach. Years later, the organization is still struggling to get the new system up and running. I left the project at the time, because I couldn't put my name behind an approach that would take very long and cost a lot of money without a working system to show for it along the way. Gall’s Law That memory keeps coming back to me, because it's a textbook case of Gall's Law playing out in real life. Gall's Law , from John Gall's Systemantics , states it plainly: A complex system that works is invariably found to have evolved from a simple system that worked. A complex system designed from scratch never works, and it cannot be patched to make it work. You have to start over with a simple system that works. What does that mean in practice,...