Todos os insights

Este artigo está disponível em inglês por enquanto.

O original aparece aqui até a tradução ficar pronta.

Escrito emEnglishTürkçe

IA & Automação

Model Context Protocol (MCP) in production: architecture, security and token budgets

Production guide to Model Context Protocol (MCP): stdio vs Streamable HTTP transports, OAuth 2.1 security, progressive tool discovery and CLI vs MCP trade-offs.

Neste artigo

The Model Context Protocol (MCP) standardizes how AI hosts connect to external tools, data resources, and prompt templates over JSON-RPC. In production, naive MCP deployments inject dozens of verbose tool schemas into every turn, inflating token costs and exposing agents to prompt injection. Reliable architectures pair scoped OAuth 2.1 gateways and progressive tool discovery with explicit CLI fallback rules.

Production takeaways

  • Use stdio for single-user local workspaces and Streamable HTTP with OAuth 2.1 for remote or multi-user MCP servers.
  • Loading every server's tools/list schema upfront wastes thousands of tokens per prompt; use progressive tool discovery and bounded payloads instead.
  • Stop tool poisoning and rug pulls by pinning SHA-256 schema hashes, locking server digests, gating mutating tools, and scanning tool outputs.
  • Prefer standard CLIs with compact skill files when agents run in an isolated shell; reserve MCP for governed cross-client connectors.
  • Design task-oriented MCP tools with explicit field masks and pagination rather than wrapping REST endpoints one-for-one.

What changes when Model Context Protocol moves into production?

Connecting a desktop chat app to a local directory via MCP takes minutes, hiding what breaks across team workflows. In a local prototype, one developer holds every secret, runs trusted code locally, and rarely counts response bytes.

Production reverses those assumptions. An MCP host — an IDE, multi-agent workspace, or backend orchestrator — runs 1:1 client sessions against multiple MCP servers exposing model-invoked Tools, host-controlled Resources, and user-selected Prompts. Once servers cross team boundaries or touch live systems, five operational requirements dominate:

  • Transport resilience across network drops, autoscaling containers, and idle timeouts.
  • Token discipline so schemas and raw outputs do not exhaust the context window.
  • Identity boundaries mapping each human user or service role to least-privilege OAuth scopes.
  • Supply-chain and prompt-injection defenses against poisoned descriptions or untrusted records.
  • Audit logs tracking which agent invoked which tool, with what parameters, and under whose approval.

How do stdio and Streamable HTTP transports differ?

MCP decouples the JSON-RPC contract from the transport layer, giving teams two production options: local stdio and remote Streamable HTTP. Picking the wrong transport forces fragile workarounds in secret management, deployment, and logging.

Local stdio transport

With stdio, the MCP host spawns the server as a child process and exchanges newline-delimited JSON-RPC over stdin and stdout, reserving stderr for logs. Without a network socket, stdio skips TLS and inherits local folder permissions and environment credentials. It fits single-developer tools, local git utilities, and build diagnostics.

Remote Streamable HTTP transport

Streamable HTTP superseded the older dual-endpoint HTTP+SSE pattern with one unified endpoint, usually /mcp. Clients send requests via HTTP POST, receive JSON or chunked Server-Sent Events (SSE) streams, and optionally open an HTTP GET SSE stream for server notifications. Stateful deployments pass an Mcp-Session-Id header and support HTTP DELETE for teardown, while stateless deployments behind load balancers rebuild per-request context cleanly.

Two Streamable HTTP rules are non-negotiable. First, even localhost servers must validate the Origin header to block DNS rebinding attacks from browser tabs. Second, network-exposed servers require TLS termination and per-request authentication.

  • Use stdio when the server inspects local files inside a single-user session or sandboxed worktree.
  • Use Streamable HTTP when teams share central connectors, need centralized audits, or run shell-less agents.
  • Run Streamable HTTP statelessly when autoscaled containers lack sticky routing.

Why do naive MCP setups bloat token budgets?

Teams usually discover MCP scaling limits on their model bill or in sluggish first-token latency. During initialization, the MCP client calls tools/list on every server and injects all tool names, descriptions, and JSON Schemas into the prompt before the user writes anything.

Context cost follows a simple equation: total overhead equals mounted schema tokens multiplied by active turns, plus tool payloads retained in conversation history. Connecting three or four broad SaaS servers — each exposing 30 to 50 granular actions — easily adds 10,000 to 20,000 schema tokens on turn zero. Provider prompt caching cuts repeat-prefix pricing (check current provider schedules), yet any schema change busts the cache and oversized tool outputs still bill at full input rates.

Billing is only half the cost. Attention dilution hurts tool accuracy when dozens of overlapping schemas compete in context. Models confuse similar flags or make redundant lookups, while naive REST wrappers dump megabytes of unused JSON fields into history.

How does progressive tool discovery fix MCP context overhead?

Progressive tool discovery — implemented via tool search or deferred loading — eliminates upfront schema bloat without removing integrations. Instead of mounting 80 JSON schemas immediately, the host or gateway registers a small core toolset plus one lightweight search_tools meta-tool.

When a task needs an external service, the agent queries the discovery layer with a short intent phrase. Hybrid keyword and semantic matching ranks the tool catalog and dynamically loads only the top three to five schemas for that sub-task, holding baseline overhead near a few hundred tokens.

Pair discovery with disciplined server-side tool design rather than 1:1 REST mirroring:

  1. Consolidate granular CRUD routes into workflow tools like search_issues or inspect_deployment with clean mode enums.
  2. Require explicit limit, cursor, and fields arguments so servers trim unused properties before returning JSON-RPC responses.
  3. Keep descriptions to one or two sentences stating preconditions, side effects, and hard bounds.
  4. Expose large logs or specs as URI-templated MCP Resources so hosts fetch slices on demand instead of stuffing tool replies.

How do you secure MCP servers against tool poisoning and rug pulls?

Traditional APIs assume untrusted callers and static docs. MCP inverts part of that threat model: AI hosts often read tool metadata as developer-grade instructions, while external records returned by tools can smuggle prompt injections straight into reasoning.

OAuth 2.1 and audience-bound tokens

For remote Streamable HTTP servers, the MCP authorization spec mandates OAuth 2.1 with PKCE (S256) instead of shared static API keys. Unauthenticated requests to /mcp return HTTP 401 with a WWW-Authenticate header pointing to Protected Resource Metadata (RFC 9728). The client obtains a scoped short-lived token bound to that server's exact URI via Resource Indicators (RFC 8707), preventing confused-deputy token replay across downstream APIs.

Tool poisoning and indirect prompt injection

Tool poisoning hides imperative directives inside tool descriptions, parameter notes, or errors — for instance, instructing the model to read local SSH keys into a telemetry field. Indirect prompt injection arrives through external content returned by tools, such as support tickets, web pages, or pull request comments.

Rug pulls and mutable server definitions

A rug pull happens when an MCP server passes initial vetting, then silently mutates tool behavior or descriptions across restarts or via notifications/tools/list_changed. Without hash verification, users never notice an approved read helper becoming an exfiltration channel.

Production security requires defense in depth across host, gateway, and runtime:

  • Hash and pin schemas: store a SHA-256 digest of each approved tool name, description, and schema, blocking execution until a human re-approves changes.
  • Lock supply-chain dependencies: pin npm packages, Python wheels, and container images to immutable versions or digests.
  • Gate mutating actions: tag read-only tools clearly, exclude destructive scopes by default, and enforce human confirmation before external writes or deletes.
  • Route through an MCP policy gateway: enforce server allowlists, inspect tools/list and tools/call payloads, and restrict outbound network egress.
  • Sandbox local servers: run third-party stdio servers in minimal containers with access limited strictly to declared directories.

CLI + skills vs MCP: which interface should agents use?

MCP is not automatically better than a documented command-line tool. Frontier models already know standard CLIs like git, gh, kubectl, docker, and psql from pretraining. Inside an isolated shell, CLIs frequently beat MCP on token cost and composability.

Instead of loading schemas upfront, a terminal agent reads a short Markdown skill file on disk only when relevant, runs --help lazily, and pipes large output through jq or head so noisy fields never enter the context window.

Outside developer shells, however, CLIs fall short. Use a crisp decision rubric:

  • Choose CLI + skill docs when agents already run inside an isolated shell or git worktree, rely on Unix pipes, or wrap fast-changing internal scripts.
  • Choose MCP when the host lacks a shell (desktop apps, web assistants, multi-tenant SaaS), multiple clients share one connector, or per-user OAuth 2.1 consent and central audit trails are required.
  • Run both in hybrid stacks: let coding agents inspect code and run tests via local CLIs while routing CRM, ticketing, and production data through an authenticated MCP gateway.

How do you configure a production TypeScript MCP server?

A production TypeScript server on @modelcontextprotocol/sdk checks Origin and Bearer auth before JSON-RPC dispatch, validates arguments with zod, marks read-only annotations, and caps row counts to protect caller context budgets.

mcp-server-config.tsTypeScript
// mcp-server-config.ts
import express from "express";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";

const ALLOWED_ORIGINS = new Set(["https://app.neptay.com", "http://localhost:3000"]);

function buildServer(scopes: Set<string>) {
  const server = new McpServer({ name: "ops-gateway", version: "1.2.0" });
  server.registerTool(
    "list_deployments",
    {
      description: "Read recent deployment summaries for one service (max 20 rows).",
      inputSchema: {
        service: z.string().min(1).max(64),
        limit: z.number().int().min(1).max(20).default(10),
      },
      annotations: { readOnlyHint: true, idempotentHint: true },
    },
    async ({ service, limit }) => {
      if (!scopes.has("deployments:read")) {
        return { isError: true, content: [{ type: "text", text: "Missing deployments:read scope." }] };
      }
      const rows = [{ service, limit, status: "healthy" }];
      return { content: [{ type: "text", text: JSON.stringify(rows) }] };
    }
  );
  return server;
}

const app = express();
app.use(express.json({ limit: "256kb" }));

app.post("/mcp", async (req, res) => {
  const origin = req.headers.origin;
  if (origin && !ALLOWED_ORIGINS.has(origin)) return res.status(403).end();
  const token = req.headers.authorization?.replace(/^Bearer\s+/i, "");
  if (!token) {
    res.setHeader("WWW-Authenticate", 'Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"');
    return res.status(401).end();
  }
  const scopes = new Set(["deployments:read"]); // Verify JWT signature, aud (RFC 8707), and scopes
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  const server = buildServer(scopes);
  res.on("close", () => { transport.close(); server.close(); });
  await server.connect(transport);
  await transport.handleRequest(req, res, req.body);
});

Frequently asked questions

What is the difference between stdio and Streamable HTTP in MCP?

Stdio runs an MCP server as a local child process exchanging JSON-RPC over stdin and stdout, ideal for single-user desktop tools and local repositories. Streamable HTTP uses one unified /mcp HTTP endpoint with optional SSE streaming, supporting remote hosting, OAuth 2.1 authentication, centralized audit logging, and stateless horizontal scaling.

When should engineering teams choose a CLI tool over an MCP server?

Choose a CLI with concise Markdown skill files when agents already operate inside an isolated terminal or git worktree and can filter output with Unix pipes. Choose MCP when clients lack shell access, require per-user OAuth 2.1 consent, or need one standardized connector governed across multiple AI applications.

How do you reduce MCP token overhead when connecting many servers?

Replace eager loading of tools/list schemas with progressive tool discovery: register a compact search_tools meta-tool and load only the three to five most relevant schemas per turn. Consolidate granular server tools, enforce limit and fields parameters, and serve large documents through MCP Resources rather than inline tool replies.

How do you prevent tool poisoning and prompt injection in MCP?

Treat tool schemas and returned outputs as untrusted inputs. Pin SHA-256 hashes of approved tool descriptions to block rug pulls, lock servers to immutable package or container digests, gate mutating tools behind human confirmation, enforce least-privilege OAuth scopes, and inspect traffic through an MCP gateway with egress controls.

How does MCP fit into multi-agent developer environments like Anlato Space?

In multi-agent developer environments, parallel coding agents work across isolated git worktrees while needing governed access to issue trackers, specs, or staging diagnostics. Local repository work stays fast via direct CLIs, while scoped MCP gateways supply read-bounded external context without exposing production secrets inside agent sandboxes.

How Neptay builds agent tooling and Anlato Space

At Neptay Media & Technology Services, we build production AI automation, custom MCP integrations, and policy-gated agent workflows for client operations. Under our Anlato technology line, Anlato Space — our flagship agent development environment, planned for macOS — focuses on running multiple coding agents side by side with clear workspace isolation, review gates, and predictable tool boundaries. Planning production MCP architecture or multi-agent tooling? Contact us at hello@neptay.com.

Na NeptayAnlato Space

Neptay Media & Technology Services

Planejando algo parecido?

Os métodos destes artigos são os mesmos que usamos em projetos de clientes — software, automação com IA, conteúdo, redes sociais e produção de lives. Conte o que você tem em mente; respondemos em até 24 horas.