Back to Insights
AI & Machine Learning•Trust Boundaries for WebMCP: Auditing Browser Tool Surfaces, Detecting Agent Abuse, and Building Observability into Agent-Native Apps•deep dive•December 1, 2026•16 min read

Trust Boundaries for WebMCP: Auditing Browser Tool Surfaces, Detecting Agent Abuse, and Building Observability into Agent-Native Apps

Deep-dive on WebMCP trust boundaries: auditing browser tool surfaces, detecting agent abuse, and building OpenTelemetry observability into agent-native apps.

T
Tamiz UddinFull-Stack Engineer

WebMCP collapses one of the most dangerous boundaries in modern software: the line between an LLM's probabilistic reasoning and your browser's privileged APIs. When an agent can call tabs.query, storage.set, or fetch as easily as a human clicks a button, the model's output stops being text and starts being a security principal. This is the confused-deputy problem at scale. In this deep-dive, we map the WebMCP trust boundary, build an audit layer for the tool surface you've exposed, design a detection engine for agent abuse, and wire OpenTelemetry-based observability into agent-native apps so every tool call is traceable, attributable, and reviewable.

1. The WebMCP Trust Model

WebMCP (the browser-flavored deployment of the Model Context Protocol) exposes browser capabilities as MCP tools: reading the active tab, snapshotting the DOM, querying history, writing to storage, issuing network requests, and controlling the page. The protocol itself is clean — JSON-RPC over WebSocket or HTTP with a server that advertises tools/list and handles tools/call. The problem is what those tools can reach.

Let's draw the trust boundary explicitly:

ini
┌─────────────┐      ┌─────────────┐      ┌──────────────┐      ┌─────────────┐
│   LLM Agent │ ───► │  MCP Client │ ───► │  WebMCP      │ ───► │  Browser    │
│  (untrusted │      │  (session   │      │  Server      │      │  APIs       │
│   output)   │      │   scope)    │      │  (tool reg)  │      │  (privileged)│
└─────────────┘      └─────────────┘      └──────────────┘      └─────────────┘
        │                   │                    │                     │
   model output       tool selection        permission            system
   = untrusted        = constrained         = scoped             = trusted

Three boundaries matter:

  1. The transport boundary — who can connect to the MCP server. If any page or extension can open a WebSocket to your server, the tool surface is open to every script on the origin.
  2. The tool-selection boundary — which tools the agent is allowed to invoke. This is your capability list, and it must be explicit, not "everything the server registers."
  3. The tool-execution boundary — what a single tool call is allowed to touch. This is your permission scope: tab IDs, storage keys, URL allowlists, DOM selectors.

The critical realization: the model's reasoning is not a security principal. When you pass page content to the model and then let it call tools, you are treating untrusted bytes as a decision-maker. A prompt injection in a third-party iframe becomes a fetch to an attacker's server within one round trip.

2. Threat Model: How Agents Abuse Browser Tools

Let's enumerate the realistic abuse vectors for a WebMCP surface:

Attack vectorMechanismTypical surfaceMitigation
Prompt injectionMalicious DOM text steers the agent into calling a tooldom.snapshot, tabs.readSanitize/truncate model input; require human approval for side-effect tools
Confused deputyAgent has broad perms; model is tricked into using themstorage.set, fetch, tabs.navigateLeast privilege; per-tool allowlists; scope to session
Tool poisoningTool registry modified to return attacker-controlled schemastools/listSign/verify tool definitions; immutable registry
Cross-tool chainingRead from one context, write to anotherstorage.get → fetchData-flow analysis; block cross-context writes
Permission escalationScoped tools with traversal in paramsstorage.get with arbitrary keys, fetch with arbitrary URLsValidate params against allowlist regexes; reject non-canonical input
Data exfiltrationTool sends data to attacker endpointfetch, websocket.sendEgress allowlist; rate limiting; alert on new destinations

The common thread: agents amplify the blast radius of any single mistake. A human might click one wrong link. An agent with 40 tools and a 10k-token context can chain five side effects in a second. Your defenses must be at the tool-execution boundary, not at the model.

3. Auditing the Exposed Tool Surface

Before you can detect abuse, you need to know exactly what you've exposed. An audit is a static inventory of every tool, its input schema, its side-effect class, and its permission scope. You should run it at server startup and on every tool registration, and ship the result as a versioned artifact.

Here's a TypeScript audit function that walks an MCP tool registry and produces a report:

ts
// audit.ts
import type { Server } from "@modelcontextprotocol/sdk/server/index.js";

type SideEffectClass = "read" | "write" | "network" | "control";

interface ToolAudit {
  name: string;
  description: string;
  sideEffect: SideEffectClass;
  scope: string[];
  inputSchema: Record<string, unknown>;
  riskScore: number; // 0-100
  flags: string[];
}

function classifySideEffect(name: string, schema: any): SideEffectClass {
  if (/fetch|request|send|post|put|websocket/i.test(name)) return "network";
  if (/write|set|create|update|delete|remove|navigate|click|submit/i.test(name)) return "write";
  if (/control|exec|run|invoke|eval/i.test(name)) return "control";
  return "read";
}

function extractScope(schema: any): string[] {
  const scope: string[] = [];
  const props = schema?.properties ?? {};
  for (const [key, val] of Object.entries(props)) {
    if (val?.enum) scope.push(`${key}:enum(${val.enum.join("|")})`);
    else if (val?.pattern) scope.push(`${key}:pattern(${val.pattern})`);
    else if (val?.type === "string") scope.push(`${key}:string`);
  }
  return scope;
}

export function auditToolSurface(server: Server): ToolAudit[] {
  // In practice you'd read from the server's registered tool map.
  const registry = (server as any)._toolRegistry ?? [];
  return registry.map((tool: any) => {
    const schema = tool.inputSchema ?? {};
    const sideEffect = classifySideEffect(tool.name, schema);
    const scope = extractScope(schema);
    let riskScore = 10;
    const flags: string[] = [];

    if (sideEffect === "write") { riskScore += 30; flags.push("SIDE_EFFECT_WRITE"); }
    if (sideEffect === "network") { riskScore += 40; flags.push("SIDE_EFFECT_NETWORK"); }
    if (sideEffect === "control") { riskScore += 50; flags.push("SIDE_EFFECT_CONTROL"); }
    if (scope.some(s => s.endsWith(":string") && !s.includes("enum"))) {
      riskScore += 15; flags.push("UNBOUNDED_STRING_PARAM");
    }
    if (/url|uri|href|endpoint/i.test(tool.name + JSON.stringify(schema))) {
      riskScore += 20; flags.push("EXTERNAL_ENDPOINT");
    }
    if (riskScore > 70) flags.push("REQUIRES_HUMAN_APPROVAL");

    return { name: tool.name, description: tool.description ?? "", sideEffect, scope, inputSchema: schema, riskScore, flags };
  });
}

This gives you a machine-readable inventory. The flags are the interesting part — REQUIRES_HUMAN_APPROVAL should map to your policy engine, and UNBOUNDED_STRING_PARAM is a red flag for tools that take a URL or storage key without a pattern.

A quick CLI wrapper:

ts
// audit-cli.ts
import { auditToolSurface } from "./audit.js";
import { createServer } from "./server.js"; // your WebMCP server

const server = createServer();
const report = auditToolSurface(server);
console.table(report.map(({ name, sideEffect, riskScore, flags }) => ({
  name, sideEffect, riskScore, flags: flags.join(", "),
})));
const highRisk = report.filter(r => r.riskScore >= 70);
if (highRisk.length) {
  console.error(`\n⚠ ${highRisk.length} high-risk tool(s) require human approval.`);
  process.exitCode = 1;
}

Auditing is not a one-time event. Treat the report as a contract: any diff that raises risk score or adds a new write/network tool should fail CI.

4. Detecting Agent Abuse in Real Time

Static auditing tells you what's exposed. Runtime detection tells you what's happening. Agent abuse is rarely a single malicious call — it's a pattern. Three detection layers work together:

Layer 1: Signature-based. Match tool calls against known abuse patterns. Example: a storage.get immediately followed by a fetch to a domain that wasn't in the session's prior egress set.

Layer 2: Heuristic. Score each call on deviation from expected behavior. An agent that suddenly calls tabs.navigate 40 times in a minute, or a tool that was never called before in a session, is anomalous.

Layer 3: Behavioral baseline. Per-agent, per-session baselines of tool-call frequency, param entropy, and scope expansion. Deviations beyond a threshold trigger alerts.

Here's a detection engine that composes these:

ts
// detector.ts
type ToolCall = {
  tool: string;
  params: Record<string, unknown>;
  sessionId: string;
  agentId: string;
  timestamp: number;
};

class AbuseDetector {
  private callHistory = new Map<string, ToolCall[]>();
  private egressDomains = new Map<string, Set<string>>();
  private readonly MAX_CALLS_PER_MINUTE = 30;
  private readonly MAX_NEW_DOMAINS_PER_SESSION = 5;

  record(call: ToolCall): DetectionVerdict[] {
    const verdicts: DetectionVerdict[] = [];
    const history = this.callHistory.get(call.sessionId) ?? [];
    history.push(call);
    this.callHistory.set(call.sessionId, history);

    // Layer 1: signature — read-then-exfiltrate
    const prev = history.slice(-3, -1).find(c => c.tool.includes("storage") && c.tool.includes("get"));
    if (prev && /fetch|send|post/.test(call.tool)) {
      const domain = this.extractDomain(call.params);
      const known = this.egressDomains.get(call.sessionId) ?? new Set();
      if (domain && !known.has(domain)) {
        verdicts.push({ severity: "high", rule: "READ_THEN_EXFILTRATE", detail: `storage.get → ${call.tool} to ${domain}` });
        known.add(domain);
        this.egressDomains.set(call.sessionId, known);
      }
    }

    // Layer 2: heuristic — call rate
    const callsLastMinute = history.filter(c => call.timestamp - c.timestamp < 60_000).length;
    if (callsLastMinute > this.MAX_CALLS_PER_MINUTE) {
      verdicts.push({ severity: "medium", rule: "CALL_RATE_EXCEEDED", detail: `${callsLastMinute} calls in 60s` });
    }

    // Layer 3: behavioral — new egress domain
    const domain = this.extractDomain(call.params);
    if (domain && /fetch|send|post/.test(call.tool)) {
      const known = this.egressDomains.get(call.sessionId) ?? new Set();
      if (!known.has(domain)) {
        known.add(domain);
        this.egressDomains.set(call.sessionId, known);
        if (known.size > this.MAX_NEW_DOMAINS_PER_SESSION) {
          verdicts.push({ severity: "high", rule: "EGRESS_DOMAIN_EXPANSION", detail: `${known.size} unique domains` });
        }
      }
    }

    return verdicts;
  }

  private extractDomain(params: Record<string, unknown>): string | null {
    const raw = params.url ?? params.uri ?? params.endpoint;
    if (typeof raw !== "string") return null;
    try { return new URL(raw).hostname; } catch { return null; }
  }
}

interface DetectionVerdict {
  severity: "low" | "medium" | "high";
  rule: string;
  detail: string;
}

The key design choice: the detector is stateless per verdict but stateful per session. You keep session-scoped state (history, egress domains) and clear it when the session ends. This prevents one session's activity from poisoning another's baseline.

False positives are the enemy. A legit agent doing a multi-step research task might call fetch to 6 domains. Tune thresholds per agent type, and always pair detection with human-in-the-loop for high-severity verdicts — block the call, surface the alert, let a human approve or deny.

5. Observability for Agent-Native Apps

Detection without observability is blind. You need to know which agent, which session, which model, which tool, and what happened — for every call. That's OpenTelemetry's job.

For agent-native apps, the telemetry model is:

  • A root span per agent session — carries agent ID, model ID, user ID, session ID.
  • A child span per tool call — carries tool name, input hash, output size, risk score, verdict.
  • Structured logs per call — full input/output (truncated), timing, and detection verdicts.
  • Metrics — tool call counters, latency histograms, error rates, egress domain counts.

Here's a middleware that wraps every MCP tool handler with OTel spans, logs, and metrics:

ts
// telemetry.ts
import { trace, SpanStatusCode, context } from "@opentelemetry/api";
import { meter } from "@opentelemetry/api-metrics";
import { logger } from "./logger.js";

const tracer = trace.getTracer("webmcp-agent");
const toolCalls = meter.createCounter("webmcp.tool.calls", { description: "Total tool calls" });
const toolLatency = meter.createHistogram("webmcp.tool.latency", { description: "Tool call latency (ms)" });
const toolErrors = meter.createCounter("webmcp.tool.errors", { description: "Tool call errors" });

export function withTelemetry<T extends (...args: any[]) => Promise<any>>(
  toolName: string,
  handler: T
): T {
  return (async (...args: Parameters<T>) => {
    const span = tracer.startSpan(`webmcp.tool.${toolName}`, {
      attributes: {
        "webmcp.tool.name": toolName,
        "webmcp.agent.id": context.active().getValue(Symbol.for("webmcp.agent.id")),
        "webmcp.session.id": context.active().getValue(Symbol.for("webmcp.session.id")),
      },
    });

    const start = performance.now();
    try {
      const result = await handler(...args);
      span.setAttribute("webmcp.output.size", JSON.stringify(result).length);
      span.setStatus({ code: SpanStatusCode.OK });
      logger.info({ tool: toolName, args: truncate(args), result: truncate(result) }, "tool_call_success");
      return result;
    } catch (err) {
      span.setStatus({ code: SpanStatusCode.ERROR, message: (err as Error).message });
      span.recordException(err as Error);
      toolErrors.add(1, { "webmcp.tool.name": toolName });
      logger.error({ tool: toolName, err }, "tool_call_error");
      throw err;
    } finally {
      const elapsed = performance.now() - start;
      toolLatency.record(elapsed, { "webmcp.tool.name": toolName });
      toolCalls.add(1, { "webmcp.tool.name": toolName });
      span.end();
    }
  }) as T;
}

function truncate(v: unknown, max = 200): unknown {
  const s = JSON.stringify(v);
  return s.length > max ? s.slice(0, max) + "…" : v;
}

A few conventions worth standardizing:

  • webmcp.agent.id — which agent instance made the call. Critical for attribution.
  • webmcp.session.id — the MCP session. Lets you correlate all calls in one agent run.
  • webmcp.risk.score — the detector's verdict severity, attached as a span attribute so you can query "all high-risk calls" in your trace backend.
  • webmcp.input.hash — a SHA-256 of the serialized params. Lets you detect "same params, different outcome" and dedupe.

Propagate trace context across the MCP boundary. When the agent client sends a tools/call, inject the traceparent header. The server extracts it and starts the child span under the session root. This gives you end-to-end traces from model prompt → tool call → browser API.

6. Putting It Together: A Reference Architecture

Now compose all three layers into a single Agent Security Gateway that sits between the MCP client and the tool server. It audits on registration, detects on invocation, and emits telemetry on every call.

ts
// gateway.ts
import { auditToolSurface } from "./audit.js";
import { AbuseDetector } from "./detector.js";
import { withTelemetry } from "./telemetry.js";

export function createAgentGateway(server: any, policy: Policy) {
  const audit = auditToolSurface(server);
  const detector = new AbuseDetector();

  // 1. Enforce audit contract
  for (const tool of audit) {
    if (tool.riskScore >= 70 && !policy.allowHighRisk) {
      throw new Error(`Tool "${tool.name}" is high-risk (${tool.riskScore}) and not in allowlist.`);
    }
  }

  // 2. Wrap every handler with detection + telemetry
  for (const tool of audit) {
    const original = server._toolHandlers?.[tool.name];
    if (!original) continue;
    server._toolHandlers[tool.name] = withTelemetry(tool.name, async (params: any, ctx: any) => {
      const call = {
        tool: tool.name,
        params,
        sessionId: ctx.sessionId,
        agentId: ctx.agentId,
        timestamp: Date.now(),
      };

      const verdicts = detector.record(call);
      const highRisk = verdicts.filter(v => v.severity === "high");

      if (highRisk.length) {
        await policy.onHighRisk(highRisk, call); // e.g. block + alert + require human approval
        if (policy.mode === "block") {
          throw new Error(`Blocked: ${highRisk.map(v => v.rule).join(", ")}`);
        }
      }

      return original(params, ctx);
    });
  }

  return server;
}

The gateway is the single choke point. It guarantees:

  1. No tool runs un-audited — startup fails if a high-risk tool isn't explicitly allowlisted.
  2. No tool runs un-instrumented — every call has a span, a log, and metrics.
  3. No abuse goes unnoticed — every call passes through the detector before execution.

Deployment options:

  • In-process middleware — simplest, zero network overhead, but shares the server's fate.
  • Sidecar proxy — the MCP client talks to a local proxy that forwards to the real server. Clean separation, but adds a hop.
  • Gateway service — centralized for many agents. Best for fleet-level policy, but becomes a bottleneck and a single point of failure.

For production, start with in-process middleware, then graduate to a sidecar if you need independent scaling or policy isolation.

Production best practices:

  • Least privilege at the tool level. Don't give the agent storage.set on all keys — scope it to a session-prefixed key space.
  • Explicit allowlist for egress. Only allow fetch to domains you've vetted. Block everything else.
  • Human approval for high-risk tools. Any tool with riskScore >= 70 requires an explicit human confirmation before execution.
  • Rate limit per session. Cap tool calls per minute; an agent in a tight loop is either broken or being abused.
  • Immutable audit logs. Write every call (input hash, verdict, agent, timestamp) to an append-only store. You'll need it for forensics.

For a deeper look at agent security patterns and production hardening, check out Tamiz's Insights and the tamiz.pro engineering hub.

7. Frequently Asked Questions

Q: Should I just block all write-capable tools from agents?

A: Not necessarily — that removes most of the value of a browser agent. Instead, scope them. A storage.set tool that only writes to keys under session:<id>: is far safer than one that accepts any key. Same for fetch: an allowlist of domains turns a dangerous tool into a useful one. The audit report tells you which tools are too broad to scope safely — those are the ones to block.

Q: How do I handle prompt injection when the model reads page DOM?

A: Treat DOM content as untrusted input, not as instructions. Sanitize and truncate it before it reaches the model, strip any <script>-like content, and never let the model's output directly trigger a tool without passing through the detector. The real defense is at the tool-execution boundary: even if the model is fully compromised, a scoped fetch to an allowlisted domain and a session-scoped storage.set limit the damage.

Q: What's the minimum observability I need for production?

A: Three things: (1) a root span per agent session with agent and session IDs, (2) a child span per tool call with tool name, input hash, and risk verdict, and (3) structured logs that capture the full call context. Metrics are nice for dashboards, but traces and logs are what let you answer "what did this agent do and why" after an incident.