Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 6 min read

MCP vs REST API for Agent Tool Boundaries: When Protocol Choice Determines Security Posture

The Model Context Protocol (MCP) and REST APIs solve different problems, but when you expose tools to AI agents, the protocol choice determines your security boundary. MCP uses persistent connections with upfront capabil

The Model Context Protocol (MCP) and REST APIs solve different problems, but when you expose tools to AI agents, the protocol choice determines your security boundary. MCP uses persistent connections with upfront capability negotiation. REST uses stateless requests with per-call authentication. These architectural differences create distinct threat models, especially when agents execute multi-step workflows or discover tools dynamically.

Authentication Boundary Differences

REST APIs distribute trust decisions across every invocation. Each HTTP request carries a token, API key, or session cookie. The server validates credentials, checks scopes, and enforces rate limits before executing the operation. If a token expires mid-workflow, the agent receives a 401 and must reauthenticate. This stateless design means compromise of a single request does not grant access to future operations.

MCP establishes a persistent connection after initial authentication. The client and server negotiate capabilities once, then exchange JSON-RPC messages over stdio, SSE, or WebSocket. The session remains open until explicitly closed or the transport fails. If an attacker hijacks the connection after authentication, they inherit the full capability set for the session lifetime. You cannot revoke access without terminating the transport.

Security Property REST API MCP Session
Auth granularity Per request Per session
Token expiry enforcement Immediate At next reconnect
Credential rotation Transparent to agent Requires new session
Attack window Single request Entire session
Revocation latency Milliseconds Seconds to minutes

Capability Discovery and Attack Surface

REST APIs expose endpoints through documentation, OpenAPI specs, or discovery documents. The agent must know which URLs exist and what parameters they accept. You control visibility by omitting endpoints from public schemas or requiring separate credentials for different resource sets. An agent with read-only credentials cannot discover admin endpoints unless you explicitly document them.

MCP servers advertise their full capability surface during the initialization handshake. The client calls tools/list, resources/list, and prompts/list to enumerate everything the server offers. The protocol assumes the client should see all available operations upfront. If you want to hide certain tools, you must implement custom authorization logic that filters the list response based on session context. The protocol itself has no built-in scoping mechanism.

This creates a reconnaissance advantage for attackers. A compromised MCP client immediately learns the full tool inventory. With REST, an attacker must probe endpoints, guess URL patterns, or exfiltrate API documentation separately.

State Management and Session Hijacking

REST's stateless design means each request is independent. If an agent workflow spans ten tool calls, the server processes ten separate HTTP transactions. Session state lives in the client or in a separate store (Redis, database) referenced by token. Hijacking a REST session requires stealing the token and replaying it before expiry. Rate limiting and anomaly detection can flag suspicious patterns across requests.

MCP sessions are stateful by design. The server may cache context, maintain conversation history, or track resource subscriptions. A resources/subscribe call keeps the connection open for streaming updates. If an attacker injects malicious JSON-RPC messages into an active MCP session, they can invoke tools without reauthenticating. The server has no per-message credential check unless you build one.

Hybrid Architecture Example

Many production systems use REST for the stable service layer and add an MCP adapter when AI hosts need tool discovery. The MCP server acts as a thin translation layer that wraps REST endpoints.

// MCP server wrapping a REST backend
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server(
  { name: "rest-wrapper", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

server.setRequestHandler("tools/list", async () => ({
  tools: [
    {
      name: "create_ticket",
      description: "Create support ticket via REST API",
      inputSchema: {
        type: "object",
        properties: {
          title: { type: "string" },
          priority: { type: "string", enum: ["low", "medium", "high"] }
        },
        required: ["title"]
      }
    }
  ]
}));

server.setRequestHandler("tools/call", async (request) => {
  if (request.params.name === "create_ticket") {
    // Forward to REST API with stored credentials
    const response = await fetch("https://api.example.com/tickets", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.API_TOKEN}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(request.params.arguments)
    });

    if (!response.ok) {
      throw new Error(`REST API error: ${response.status}`);
    }

    return { content: [{ type: "text", text: await response.text() }] };
  }
});

const transport = new StdioServerTransport();
await server.connect(transport);

This pattern keeps the REST API as the source of truth for authentication, rate limiting, and audit logging. The MCP server holds long-lived credentials and proxies requests. You gain MCP's tool discovery without rebuilding your security model.

The risk is credential scope. The MCP server needs a token with enough privilege to call all wrapped endpoints. If the MCP process is compromised, the attacker inherits those privileges for the full session. With direct REST integration, each agent request uses a scoped token tied to the end user or workflow identity.

Observability and Audit Trails

REST APIs produce one log entry per request. You can correlate entries by trace ID, but each operation is self-contained. Anomaly detection looks for patterns like rapid credential rotation, geographic inconsistencies, or unusual endpoint sequences.

MCP sessions produce a stream of JSON-RPC messages over a single transport. Logging the raw message stream gives you a complete audit trail, but you must parse the protocol to extract tool calls, resource reads, and prompt invocations. If the transport is stdio, logs go to the host process stderr. If it is SSE or WebSocket, you need middleware to capture the message flow.

Session-based protocols also complicate rate limiting. With REST, you count requests per token per time window. With MCP, you must count tool invocations within a session and decide whether to terminate the connection or reject individual calls when limits are exceeded.

Failure Modes

REST failures are localized. A 500 error on one endpoint does not affect other operations. The agent retries the failed request or moves to a fallback. Network partitions cause immediate request timeouts.

MCP failures can cascade. If the transport dies mid-session, the agent loses access to all tools until it reconnects and renegotiates capabilities. If the server crashes during a tools/call, the client may not know whether the operation completed. The protocol has no built-in idempotency mechanism. You must design tools to be safely retryable or track execution state externally.

Long-running MCP sessions also accumulate resource leaks. A server that caches context per session will grow memory usage linearly with active connections. REST servers can be stateless and scale horizontally without coordination.

When MCP's Stateful Model Wins

MCP makes sense when the agent needs to maintain context across multiple interactions. A code assistant that reads a project structure, subscribes to file changes, and invokes build tools benefits from a persistent session. Reconnecting and rediscovering capabilities on every operation would add latency and complexity.

MCP also simplifies client implementation when you control both ends. The SDK handles transport, message framing, and capability negotiation. You do not need to manage HTTP clients, parse status codes, or implement retry logic.

When REST's Stateless Model Wins

REST is the better choice when you need fine-grained access control, short-lived credentials, or integration with existing API gateways. If your agent workflow spans hours or days, stateless requests let you rotate tokens, enforce dynamic policies, and audit each operation independently.

REST also fits multi-tenant systems where different agents have different permission sets. You issue scoped tokens per agent identity and let the API gateway enforce boundaries. With MCP, you must implement custom authorization in the server or run separate MCP processes per tenant.

Technical Verdict

Use REST when you need per-request authentication, token expiry enforcement, or integration with existing API infrastructure. Use MCP when the agent benefits from persistent context, tool discovery, or streaming resource updates. In production, the hybrid pattern (MCP wrapping REST) often provides the best balance: you keep REST's security properties and add MCP's discovery layer when AI hosts need it.

Avoid MCP if your threat model cannot tolerate long-lived sessions or if you need to revoke access in real time. Avoid REST if the agent must maintain stateful context and the overhead of reconnecting per operation is unacceptable.

Source Links

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.