Listen to this Post

Introduction:
Traditional AI coding assistants like GitHub Copilot rely on local filesystem access and shell commands. But what if you could run an autonomous coding agent entirely inside a cloud-hosted environment like Microsoft Copilot Studio—with no native filesystem or shell? This article breaks down a novel architecture that uses the Model Context Protocol (MCP) plus Azure Dev Tunnels to bridge a cloud planner to a local MCP server, enabling file reads, edits, grep, glob, and even shell execution from a cloud agent. You’ll learn how to replicate this setup, secure it with runtime safety postures, and understand the critical security trade-offs.
Learning Objectives:
- Build an AI coding agent inside Copilot Studio that can read, write, edit, and execute shell commands on your local machine via MCP and Dev Tunnels.
- Configure runtime safety postures (strict/moderate/open) and audit logging to prevent malicious file operations or command injection.
- Harden the tunnel and MCP server against common attacks, including path traversal, credential leakage, and unauthorized shell access.
You Should Know:
- Bridge the Cloud-to-Local Gap with Azure Dev Tunnels
The core innovation is exposing a local MCP server to the cloud agent over HTTPS. Copilot Studio agents have no local shell or filesystem, so you must create a secure tunnel. Azure Dev Tunnels is Microsoft’s native solution (no ngrok required).
Step‑by‑step guide:
- Install Dev Tunnels CLI (Windows/Linux/macOS):
`winget install Microsoft.DevTunnel` (Windows) or `curl -L https://aka.ms/TunnelsCliDownload/linux-x64 -o devtunnel` (Linux). - Authenticate (Azure account required):
`devtunnel user login`
- Create a tunnel pointing to your MCP server’s local port (e.g., 3000):
`devtunnel create –port 3000 –access public`
- Start the tunnel with a host header:
`devtunnel host –port 3000`
- The tunnel provides a public HTTPS URL (e.g., `https://your-tunnel-id.eastus.devtunnels.ms`). Configure this as the Copilot Studio agent’s action endpoint.
Security note: Public tunnels expose local services. Use `–access private` and authenticate via custom headers or OAuth when possible. Never expose raw shell endpoints.
- Build a Stateless MCP Server with Seven Core Tools
The MCP server acts as the bridge: it receives JSON-RPC requests over Streamable HTTP, executes local operations, and returns results. This TypeScript server implements seven tools modeled on Code.
Step‑by‑step guide to implement the server:
- Initialize a Node.js project:
`npm init -y && npm install express body-parser`
- Create `server.js` with endpoints for each tool. Example snippet for
read_file:app.post('/mcp', (req, res) => { const { tool, params } = req.body; switch(tool) { case 'read_file': const safePath = path.join(workspaceRoot, params.path); if (!safePath.startsWith(workspaceRoot)) throw new Error('Path traversal blocked'); const content = fs.readFileSync(safePath, 'utf8'); res.json({ result: content }); break; case 'run_shell': if (safetyPosture === 'strict') return res.status(403).json({ error: 'Shell disabled' }); const { stdout } = execSync(params.command, { cwd: workspaceRoot }); logAudit('shell', params.command); res.json({ result: stdout.toString() }); break; // ... implement edit_file, write_file, list_dir, glob, grep } }); - Implement runtime safety postures:
- Strict: No shell access, read-only file operations, allowlist of allowed commands via `run_shell` blocked.
- Moderate: Shell allowed but commands logged; file writes allowed only under workspace root.
- Open: Full shell and file access (development only).
- Run the server: `node server.js` (listens on port 3000). Then start the Dev Tunnel.
Windows/Linux commands to audit shell usage:
On Linux: `auditctl -w /path/to/workspace -p wa -k mcp_audit`
On Windows PowerShell: `Get-EventLog -LogName Security -InstanceId 4688 | Where-Object {$_.Message -like “run_shell”}`
3. Configure Copilot Studio for Code-Friendly Behavior
Copilot Studio applies content moderation by default. To avoid stripping code blocks or shell output, you must lower moderation settings and write precise tool descriptions.
Step‑by‑step guide:
- In Copilot Studio, navigate to your agent’s Safety & Compliance settings.
- Set Content moderation to Low (default Medium or High will remove code and shell responses).
- Under Actions, define each MCP tool with a clear, keyword‑rich description. Example for
grep:
“Searches for a regular expression pattern inside all files under the workspace root. Returns matching lines with filenames. Use this instead of read_file when you need to find where a symbol or string appears.” - Increase planner verbosity in agent settings to debug tool selection. Test with: “Read package.json and install a new dependency” – verify the planner calls `read_file` then `run_shell` (‘npm install’).
4. Jailbreak Path Operations and Prevent Traversal
Because the cloud agent controls the tool parameters, you must assume malicious or malformed inputs. Implement path jailing at the MCP server level.
Step‑by‑step hardening:
- Define a workspace root (e.g.,
/home/user/project). Resolve all paths relative to this root usingpath.resolve(workspaceRoot, userPath). - Check for path traversal:
function isPathSafe(requestedPath) { const resolved = path.resolve(workspaceRoot, requestedPath); return resolved.startsWith(workspaceRoot); } - For `write_file` and
edit_file, additionally validate file extensions (e.g., block.bashrc,.ssh/id_rsa). - On Windows, normalize drive letters and disable `..` via
path.normalize. Use `fs.realpath` to resolve symlinks before checking. - Linux command to monitor attempted escapes: `grep “path traversal” /var/log/mcp-audit.log`
- Audit Logging for Shell Commands and File Writes
Every `run_shell` and file modification must be logged to support forensic analysis and compliance. Implement structured logging and forward logs to a SIEM.
Step‑by‑step implementation:
- Add Winston logger to the MCP server:
const winston = require('winston'); const auditLogger = winston.createLogger({ transports: [new winston.transports.File({ filename: 'mcp-audit.log' })] }); function logAudit(action, details, user = 'copilot-agent') { auditLogger.info({ timestamp: new Date().toISOString(), user, action, details }); } - Log each shell command with full command line and exit code.
- For file writes, log the path, size, and a hash of the new content (e.g.,
crypto.createHash('sha256').update(content).digest('hex')). - Forward logs to Azure Sentinel or Splunk using a sidecar collector (e.g., Filebeat).
- Windows Event Log integration: Use `Write-EventLog` in PowerShell wrappers for
run_shell. - Linux syslog: Configure rsyslog to forward `mcp-audit.log` to a remote server.
- Secure the Dev Tunnel Against Credential and API Leakage
The tunnel exposes your MCP server to the public internet. Without authentication, anyone who guesses the tunnel URL can call your tools. Copilot Studio can inject headers, but you must validate them.
Step‑by‑step hardening:
- Generate a static API key (32‑byte random string). Store it in environment variable
MCP_API_KEY. - Modify the MCP server to check the `Authorization: Bearer
` header before processing any request. - In Copilot Studio action definition, add a custom HTTP header with the API key (stored as a secret in Azure Key Vault and referenced in the agent’s environment variables).
- Rotate the key weekly using a script:
Windows PowerShell $newKey = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count 32 | % {[bash]$_}) az keyvault secret set --vault-name MyVault --name MCPApiKey --value $newKey - Restrict tunnel access further by using `–access private` and enabling Entra ID authentication on the tunnel.
- Monitor tunnel usage: `devtunnel list` and
devtunnel show <tunnel-id> --logs.
- Test the Full Loop with a Bootstrapped Todo App
Once the MCP server, Dev Tunnel, and Copilot Studio agent are configured, deploy an end‑to‑end test to validate the agent’s ability to build a real application.
Step‑by‑step test:
- Prompt your Copilot Studio agent: “Create a full‑stack todo app with a React frontend and an Express backend. Use a JSON file as storage. Initialize the project structure, write all files, and run npm install.”
- Observe the planner’s tool calls (in Copilot Studio analytics). It should call
list_dir→write_file→run_shell. - Inject a failure case: “Delete /etc/passwd” – verify the strict posture blocks it and logs the attempt.
- Measure response time – the tunnel adds latency. For large file writes, implement chunking and streaming.
- Benchmark how many concurrent requests the MCP server can handle (Node.js event loop – use `–max-old-space-size=512` for memory limits).
What Undercode Say:
- Key Takeaway 1: Cloud agents can safely interact with local resources by using protocol bridges (MCP) and authenticated tunnels—but security posture (strict/moderate/open) must be enforced at the server, not just in documentation.
- Key Takeaway 2: The weakest link is often not the tool layer but the planner’s verbosity and content moderation; lowering moderation for code work introduces risks of shell output leakage if not paired with strict output sanitization.
Analysis: This architecture democratizes local execution for any cloud agent, not just Copilot Studio. However, it also creates a powerful remote code execution (RCE) vector if the tunnel is misconfigured or the API key leaks. The audit logging is necessary but not sufficient; you must also implement command allowlisting (e.g., only npm, git, `ls` and deny curl, wget, rm -rf). Further, the MCP server’s stateless design means each request carries the full risk – there is no session to revoke after a breach. Consider adding a per‑call OTP or short‑lived tokens.
Prediction:
Within 12 months, every major low‑code agent platform (Power Automate, Zapier, n8n) will adopt an MCP‑like protocol to offload filesystem and shell actions to local runners. This will drive a new market for “agent‑safe” sandboxing tools (e.g., Firecracker microVMs for each command). However, enterprise adoption will stall until platforms provide built‑in, zero‑trust tunnel authentication—expect Azure Dev Tunnels to integrate Entra ID pass‑through before Q4 2026. The first major breach of an agent tunnel (leaking cloud secrets via a compromised run_shell) is inevitable; prepare by isolating workspace roots to disposable containers.
▶️ Related Video (76% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Taikiyoshida Copilotstudio – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


