Back to blog posts

16 min

How AI agents use MCP servers to connect to tools in 2026

Learn what an MCP server is, how agents call tools over JSON-RPC and how to deploy and secure servers in production.

Nicolas LecomteNico is a founder of Blaxel, who usually writes about AI, agentics, and the future of AI runtimes.

An MCP server gives an AI agent a standard way to discover and call outside tools. The Model Context Protocol (MCP) runs on JSON-RPC 2.0, so any compatible client can reach any compatible server. Agents ask a server what it offers, then call the tool they need at runtime.

The protocol looks different in November 2026. The 2026-07-28 specification retired the initialize handshake along with the Mcp-Session-Id header. Each request now carries its own context in a _meta field, so servers handle every call statelessly. Authorization stays optional, and servers on HTTP should follow an OAuth 2.1 flow.

For teams shipping agents, guides written around sessions and setup handshakes no longer match how servers behave. This guide walks through tools/list and tools/call and compares MCP with plain APIs and function calling. It then shows how teams deploy and centralize their servers.

Key takeaways

  • An MCP server exposes tools, resources, and prompts that any compliant AI host can discover and call.
  • The 2026-07-28 spec drops the initialize handshake and session header, so remote servers scale statelessly.
  • Authorization is optional in the spec, so your team owns authentication, token validation, and permission scoping.
  • Servers that run untrusted or AI-generated code need microVM isolation, not shared-kernel containers.

What is an MCP server?

An MCP server is a program that exposes tools, data sources, and prompt templates to AI applications. The server speaks the Model Context Protocol, an open standard for connecting agents to external systems. MCP acts as a USB-C port for AI applications. One connector shape works with many devices, and one MCP server works with many AI hosts.

The protocol uses JSON-RPC 2.0 for communication. Local servers talk over stdio (standard input and output). Remote servers use Streamable HTTP, which replaced the older HTTP with Server-Sent Events (SSE) transport.

The architecture has three participants:

  • The MCP host is the AI application that coordinates one or more MCP clients. Claude Desktop, a coding IDE, or your custom agent can play that role.
  • The MCP client maintains a connection to one MCP server and obtains context from it for the host.
  • The MCP server provides that context. Each host creates one dedicated client per server, so every connection stays one-to-one.

Servers offer capabilities through three building blocks, called tools, resources, and prompts:

Building blockWhat it isWho controls itExample
ToolsFunctions the AI model can executeThe model decides when to call themget_forecast, read_file, a database query
ResourcesContext and data for the user or model, addressed by URIThe host application decides what to loadA file, a document, a live query result
PromptsTemplated messages and workflowsThe user picks themA "plan-vacation" or code-review template

MCP server vs API vs function calling

MCP servers, plain APIs, and provider function calling solve overlapping problems at different layers. The right mix depends on who calls the tool and how many hosts need it.

MCP serverPlain REST/OpenAPI APIFunction calling
Built forAI agents in any MCP-compliant hostHuman developers writing deterministic clientsOne model provider's API
Tool discoveryAgent sends tools/list at runtimeDeveloper reads docs and writes codeTool definitions sent with each request
PortabilitySame server works across hostsAny HTTP client, custom glue per agentTied to the provider's request format
StateStateless per request in the 2026-07-28 specDepends on the APIRequest-scoped
Best fitTools shared across agents and providersDeterministic or one-off integrationsA small fixed toolset on one provider

The three options often complement each other. Claude Academy calls MCP servers and tool use complementary but different concepts. The model still uses tool calling to invoke tools, and MCP standardizes where those tools come from.

For deterministic integrations, static context, or strict security, plain API calls often win. Start with MCP when several agents or providers need the same tool. Stay with direct API calls when your agent calls one endpoint the same way every time.

How MCP changes your agent architecture

Without MCP, tool logic lives inside the agent. The agent's codebase embeds database queries, API calls, and file operations as provider-specific function definitions. The agent, its tools, and its execution environment share the same process. Adding or removing a tool means modifying and redeploying the agent. Each agent keeps its own copy of every integration.

MCP moves tool logic out of the agent. Tools live in independent MCP servers, and the agent's codebase shrinks to reasoning logic and a protocol client. The shift has three effects.

First, tools become shared infrastructure. A single GitHub MCP server handles repository operations for every agent in your stack. Your coding agent, pull request review agent, and deployment agent all connect to the same server instance. When you update the GitHub integration, every agent gets the change without redeployment.

Second, each server can run in its own isolation boundary. In the embedded model, a vulnerability in your filesystem code exposes the entire agent process. With MCP, you can give each server its own filesystem mounts, network rules, and permissions.

Compromising an isolated Git server doesn't give an attacker access to database credentials on a separate query server.

Third, agents discover tools dynamically instead of loading them at build time. An agent sends a tools/list request and receives the current inventory with schemas and descriptions. You can add, remove, or update MCP servers without touching agent code, so changing your toolset becomes a deployment task.

Benefits of adopting MCP servers

The value of MCP depends on your agent architecture and scale.

Here's where each benefit applies and where it doesn't:

  • Cross-host portability: Tools work across MCP-compliant hosts such as Claude, ChatGPT, Cursor, and VS Code. You write no extra integration code per host. Teams on one provider with no plans to switch can skip that overhead with custom function calling.
  • Dynamic tool discovery: Discovery pays off when specialized agents share a common tool pool. For a single agent with a fixed toolset, discovery adds a round trip with little benefit.
  • Per-server isolation boundaries: Separate boundaries matter most for coding agents and workflows where untrusted code runs alongside sensitive data.
  • Ecosystem access: The official MCP Registry catalogs publicly available servers. The official servers repository calls its servers reference implementations and educational examples, not production-ready code. Its GitHub, Slack, and PostgreSQL servers now sit in the archived servers repository. You'll typically fork or rebuild servers to add authentication, logging, and permission scoping.

Weigh each benefit against how many agents and providers share your tools.

How does an MCP server work?

Every MCP interaction follows the message model in the official protocol specification. The 2026-07-28 revision removes the initialize/initialized exchange and the Mcp-Session-Id header. Each request carries its protocol version, client identity, and client capabilities in _meta. A server/discover call returns server capabilities, but clients don't have to send them.

The tool execution lifecycle

A session-free exchange starts with a tools/list request. The server replies with its available tools, one page at a time. Each tool has a name, a description, and an inputSchema. The 2026-07-28 revision allows any JSON Schema 2020-12 keyword in inputSchema and the optional outputSchema.

List results also carry ttlMs and cacheScope, so clients know how long to cache the tool inventory.

The host presents these tools to the large language model (LLM). The LLM decides which tools to invoke from their descriptions and context. The client then sends tools/call requests with arguments that match the tool's inputSchema.

The server runs the tool and returns structured results. The core JSON-RPC shapes look like this:

JSON
{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"cursor": "optional-cursor-value"}}

{"jsonrpc": "2.0", "id": 2, "method": "tools/call",
"params": {"name": "get_weather", "arguments": {"location": "New York"}}}

{"jsonrpc": "2.0", "id": 2,
"result": {"resultType": "complete", "content": [{"type": "text", "text": "<weather report>"}], "isError": false}}

The sample requests omit the _meta object that every 2026-07-28 request carries, including io.modelcontextprotocol/protocolVersion. The result shows the required resultType field, set to "complete" for ordinary results.

The transport determines how those messages travel. The 2026-07-28 transports spec defines two standard options:

TransportWhere it runsHow messages moveCredentialsStatus
stdioLocal machineClient launches the server as a subprocess. Newline-delimited JSON-RPC over stdin and stdout.Read from the environmentStandard
Streamable HTTPRemote endpointHTTP POST to one MCP endpoint. Replies come as JSON or a request-scoped SSE stream.OAuth 2.1 flow (optional)Standard, stateless in 2026-07-28
HTTP with SSERemote endpointSeparate SSE and POST endpoints from the 2024-11-05 revisionVariesDeprecated, migrate to Streamable HTTP

Over Streamable HTTP, clients also send an Mcp-Method header, plus Mcp-Name on calls like tools/call.

What changed in the 2026-07-28 MCP specification

The 2026-07-28 release is the largest revision of the protocol since launch, and it includes breaking changes. Each revision string marks the last date of backward-incompatible changes.

RevisionKey changes
2025-03-26OAuth 2.1 authorization, Streamable HTTP in place of HTTP+SSE, and tool annotations such as read-only and destructive
2025-06-18Structured tool output, elicitation, classification of servers as OAuth Resource Servers, RFC 8707 resource indicators, a required MCP-Protocol-Version header, and removal of JSON-RPC batching
2026-07-28Stateless core, removal of the initialize handshake and session header, Tasks as an extension, Multi Round-Trip Requests, and a deprecation policy

The 2026-07-28 revision deprecates Roots, Sampling, and Logging. Pass directories through tool parameters or resource URIs instead of Roots. Call your LLM provider's API instead of Sampling. Log to stderr or OpenTelemetry.

Deprecated features stay in the spec for at least 12 months. An expedited-removal exception shortens that window to at least 90 days.

Multi Round-Trip Requests replace server-initiated requests. The server returns an InputRequiredResult, and the client retries with inputResponses. A 2026-07-28-only server should answer GET or DELETE with 405 Method Not Allowed.

Such a server also ignores Mcp-Session-Id. Test your server with both legacy and 2026-07-28 clients before you stop supporting the old protocol.

How to build, test, and connect an MCP server

Building and connecting a custom Model Context Protocol server follows a workflow across development, transport selection, testing, and client integration.

To get an MCP server up and running, follow these key steps:

  1. Install an SDK: Running pip install mcp now installs the 2.x Python SDK, which renames FastMCP to MCPServer. The TypeScript v2 line splits into @modelcontextprotocol/server and @modelcontextprotocol/client. The v1 @modelcontextprotocol/sdk package still gets fixes on the v1.x branch.
  2. Register tools: Give each tool a clear name, a description the model can reason about, and an input schema. The build guide walks through a weather server exposing get_alerts and get_forecast.
  3. Pick a transport: Use stdio for local servers. Never write non-MCP output to stdout, because stray prints break the connection. Send logs to stderr. Use Streamable HTTP for servers other people reach over the network, and put them behind a gateway.
  4. Test with the Inspector: The MCP Inspector is the reference tool for testing and debugging servers. The build guide runs npx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era modern --method tools/list. The Inspector defaults to the legacy era, so run it once with modern and once with legacy. Confirm the tool list, then verify one tools/call result.
  5. Connect a client: Each host registers servers differently:
ClientWhere you register serversRemote servers
Claude Desktopclaude_desktop_config.json under mcpServers. macOS: ~/Library/Application Support/Claude/. Windows: %APPDATA%\Claude\Customize > Connectors, not the config file
Claude Codeclaude mcp add, then /mcp to check what loadedclaude mcp add --transport http <name> <url>
Cursor.cursor/mcp.json per project or ~/.cursor/mcp.json globally. Files merge, and the project file winsurl field with optional headers
VS Code.vscode/mcp.json with a top-level servers keyurl entry
ChatGPTPlugins UI, "Add custom MCP server"Public HTTPS URL including /mcp, or Secure MCP Tunnel

VS Code expects a servers key, while Claude Desktop expects mcpServers. Copy the format from each client's own docs instead of reusing one file everywhere.

Production deployment topology

Deploying an MCP server follows one of two paths. A local server runs as a stdio subprocess that the client launches. A remote server runs as a Streamable HTTP service behind a gateway. A production coding agent typically connects to several MCP servers.

Such an agent uses a filesystem server for file operations and a Git server for version control. It also connects to a code execution server for running tests and a database server for schema lookups. Each server should run as a separate service in its own isolated environment.

When the LLM selects a tool, the client routes the tools/call request to the target server by tool name. Servers share one secrets store, with credentials scoped per server. They also share one observability stack for tracing and alerting.

Under 2026-07-28, remote servers no longer need sticky routing or shared session stores. A plain round-robin load balancer can spread requests across them.

You can centralize servers in three ways:

  • Govern what runs: The local server security guide recommends an allowlist with published acceptance criteria. Maintain a continuous inventory of client configurations. Add audit logs, block a server's egress and rotate its credentials.
  • Route through a gateway: Send remote traffic through a gateway. The gateway enforces policy for authentication, rate limits, and logging. Network operations teams can expose device inventory or configuration APIs as read-only tools behind the gateway. Gate any tool that changes device configuration behind human approval.
  • Consume managed servers: Use managed remote servers, the "MCP server as a service" model. Google reports more than 50 Google-managed MCP servers generally available or in preview as of April 29, 2026. AWS made its AWS MCP Server generally available. GitHub runs a remote GitHub MCP server with OAuth 2.1 and Proof Key for Code Exchange (PKCE). Managed MCP deployment services like these remove hosting work for common integrations. You then build servers only for internal systems.

Handle three failure modes in the client. Drop an unreachable server's tools and tell the LLM. Return a structured error when a server times out mid-execution so that the LLM can retry or choose another approach. Check the isError flag to catch tool failures. Retry logic and timeout thresholds keep one degraded server from blocking the entire agent.

Challenges of deploying MCP servers in production

The protocol handles communication, and production deployments add five categories of challenges:

  • Security is your responsibility: The MCP specification defines authorization as optional. HTTP transports should follow its OAuth 2.1 flow, but nothing forces a server to. You implement authentication, token management, and permission scoping yourself.
  • MCP-specific attack vectors: An academic analysis examined 1,899 open-source MCP servers. The analysis found 7.2% with general vulnerabilities and 5.5% with MCP-specific tool poisoning (hidden instructions in tool descriptions). Treat every community server as untrusted until you've reviewed it.
  • Isolation requirements for code execution: Servers that execute untrusted or AI-generated code need strong isolation. Containers share the host kernel, creating potential escape vectors. MicroVMs give each workload its own kernel behind hardware-enforced boundaries.
  • Infrastructure overhead: You need gateway orchestration, multitenancy isolation, observability, and version management. Someone on your team still runs and patches every server.
  • Missing operational benchmarks: MCP maintainers report close to half a billion monthly downloads across Tier 1 SDKs. Download counts confirm traction but say nothing about latency or cost per operation. Plan internal performance testing.

Budget for these five areas before a server reaches production.

Best practices for deploying MCP servers with autonomous coding agents

Most production controls sit outside the protocol, so your team builds them.

Implement token exchange for agent authentication

Use OAuth 2.1 with PKCE for remote MCP servers over HTTP transports. Issue short-lived, scoped tokens per client or per task to limit exposure windows. A database query server should receive tokens scoped only to SELECT operations on specific tables. Those tokens should expire within minutes.

Validate the audience on every token. A server that skips this check can accept tokens issued for other services, as the MCP security guidance warns. Attackers can then reuse legitimate tokens. The same guidance rules out token passthrough. A server that forwards unmodified tokens downstream creates a confused deputy.

The downstream API then trusts the token as if it came from the server. Request a separate token for the downstream service rather than reusing the client's.

Since the 2025-06-18 revision, clients send the RFC 8707 resource parameter. The 2026-07-28 revision deprecates Dynamic Client Registration in favor of Client ID Metadata Documents. Over stdio, servers skip OAuth and read credentials from the environment, per the 2026-07-28 authorization spec.

Run each MCP server in an isolated environment

Compromising one MCP server can cascade to others if they share resources. Deploy each server in its own isolated environment. Use separate filesystem mounts and network segmentation. For coding agents that execute untrusted or AI-generated code, microVM-based isolation provides stronger boundaries than containers.

Local servers need isolation too. A local MCP server runs as an ordinary child process. The protocol provides no sandbox. The process can read SSH keys, cloud credentials, and browser profiles. It can also open outbound connections. Run local servers under least-privilege accounts, strip unneeded environment variables, and restrict network egress.

Containers remain a reasonable choice for your own trusted services. For tool code that agents generate, Baseten Sandboxes, the infrastructure foundation for autonomous agents, run each sandbox as a microVM.

Every sandbox exposes a built-in MCP server, so agents operate its files and processes through tool calls. Baseten Sandboxes resume from standby in under 25ms, so an idle sandbox adds little delay to the next tool call.

Scope permissions to the minimum required operations

Each MCP server needs an allowlist of permitted operations. A filesystem server for a code review agent should have read access to the workspace directory only. The server gets no write access and no access outside the project root.

Split development and production scopes. Development servers can hold broader permissions while you test. Production servers should default to read-only, with every write operation gated behind human approval. Hosts already support this pattern.

Claude Code requests permission by default for actions that modify the system, including MCP tools. OpenAI's Responses API lets developers require explicit approval for MCP tool calls. Avoid "Always Allow" policies on servers that can write data.

Adopt code execution patterns over upfront tool loading

Loading every tool definition into the context window wastes tokens before the agent reads a request. Anthropic measured about 55,000 tokens for five servers exposing 58 tools. The overhead repeats with every prompt, so large toolsets raise cost.

Anthropic's code execution architecture lets agents write code that calls MCP tools programmatically. The agent discovers tools by listing a ./servers/ directory and reading only the tool files it needs.

The agent also filters and aggregates locally. In Anthropic's example, token usage fell from 150,000 to 2,000, "a time and cost saving of 98.7%."

This reduction comes from the code execution pattern itself. Code execution patterns require stronger sandboxing because the agent now runs code it wrote.

Centralize secrets with automated rotation

Store all API keys, database credentials, and tokens in a centralized secret management system. Use short-lived dynamic secrets scoped to each MCP server. Automate rotation on a fixed schedule, and revoke credentials immediately when you decommission a server.

Cursor resolves ${env:NAME} variables in its config, so keys stay out of files you commit. For stdio servers, environment hygiene is part of secret management.

Deploy structured logging with distributed tracing

Structured logs should capture correlation IDs, tool invocations, latency, and security context. Use OpenTelemetry to trace each request from the chat interface to the server's API call. The 2026-07-28 spec documents traceparent, tracestate, and baggage keys in _meta, so trace context travels with each request.

Forward logs and traces to platforms like Splunk, Datadog, or Elastic for alerting and security monitoring.

Monitor for MCP-specific threat patterns

Watch for tool poisoning, prompt injection, rug pulls, and confused deputy attacks. Tool poisoning hides instructions in tool descriptions that the model reads, but users rarely see. Indirect prompt injection arrives through content the agent processes, such as a poisoned document that triggers a tool call.

A rug pull changes a server's behavior after you approve it. The postmark-mcp npm package impersonated Postmark and built trust over 15 versions. Version 1.0.16 then secretly BCC'd emails to an external server.

The Open Worldwide Application Security Project (OWASP) MCP cheat sheet recommends watching for tool description changes and verifying package integrity. Pinning server versions makes description changes easier to spot.

Feed alerts and behavioral baselines into your security information and event management (SIEM) system. The SIEM can then flag descriptions that drift from the approved baseline.

Design tools as small, composable operations

Expose discrete operations. For example, a filesystem server can provide separate read_file, list_directory, and get_file_info tools. This design lets agents compose complex workflows by chaining small tools. Separate tools also let you control permissions per operation.

Thoughtworks warns against naive API-to-MCP conversion that maps every endpoint to a tool. Thoughtworks recommends a dedicated server instead, built for agent workflows on top of existing APIs.

Tool-selection accuracy drops as the tool count climbs. Design each tool around a task the agent performs. Keep the list short enough for the model to choose well.

Next steps for MCP servers in your agent stack

MCP now standardizes discovery, invocation, transport, and authorization flows. Your team still owns isolation, token scoping, secrets, logging, and threat monitoring.

For servers that run untrusted or AI-generated code, compare running your own microVMs with agent infrastructure platforms like Baseten Sandboxes.

FAQs about MCP server

How is an MCP server different from a REST API?

A REST API exposes endpoints that developers integrate manually. An MCP server exposes tools through a standardized protocol that AI agents discover at runtime. Agents send a tools/list request and receive descriptions with JSON Schema parameter definitions. The LLM reads these descriptions and decides which tools to call. Many MCP servers wrap existing APIs, so the two work together.

Do all major AI platforms support MCP?

Yes, the largest AI vendors support MCP. Anthropic launched MCP with a specification and SDKs. The launch also included local server support in Claude Desktop and an open-source server repository. OpenAI supports remote MCP servers in its Responses API and custom MCP servers in ChatGPT. Google offers managed MCP servers, Microsoft made MCP generally available in Copilot Studio, and AWS ships its own MCP server.

What security risks should I plan for with MCP servers?

Your team owns OAuth token exchange, audience validation, per-server permission scoping, and isolation. MCP introduces attack vectors such as tool poisoning, rug pulls, and confused deputy attacks through token passthrough. Prompt injection can also arrive through external content the agent reads. Servers that run untrusted or AI-generated code need microVM-based sandbox isolation or equivalent hardware-enforced boundaries.

Can I build a custom MCP server, or do I need to use existing ones?

You can build custom MCP servers in any language that supports JSON-RPC 2.0. The 2026-07-28 SDK page lists TypeScript, Python, Go, C#, Rust, and Ruby as Tier 1 SDKs. Java is Tier 2, and Swift, PHP, and Kotlin are Tier 3. A common production setup combines custom servers for internal tools with pre-built or managed servers for standard integrations.

How does MCP compare to OpenAI function calling?

MCP is a JSON-RPC 2.0 protocol layer that works across AI providers over stdio or Streamable HTTP. OpenAI function calling is an API-level feature tied to OpenAI's request format. Function calling defines tools in each API request. Choose MCP for tools shared across providers or agents. Choose function calling for OpenAI-only deployments with a small, fixed toolset.

Related articles