If you are building AI agents in 2026, the Model Context Protocol (MCP) is how your agent connects to the outside world. MCP provides a universal interface for tools, resources, and prompts, enabling your agent to call external APIs, databases, and services without custom integration code for each one.
But understanding MCP at a conceptual level is only half the work. To build a production-ready AI agent, you need to understand the complete request flow—from the model's decision to call a tool, through the MCP client and server, to the tool's execution and the result's return. You also need to handle authentication, authorization, validation, error handling, logging, and security boundaries.
This guide walks through the MCP request lifecycle step by step, showing how to build an AI agent that securely and reliably interacts with MCP servers.
MCP Architecture Overview
Before diving into the request flow, it helps to understand the architecture. MCP follows a client-server model:
- AI Agent — The autonomous system that decides to call tools. It runs the reasoning loop and coordinates the MCP client.
- MCP Client — A component within the host application that maintains a connection to an MCP server and sends JSON-RPC requests on behalf of the agent.
- MCP Server — A program that exposes tools, resources, and prompts to MCP clients. It validates requests, executes tools, and returns results.
- External Tools — The underlying systems (APIs, databases, file systems) that the MCP server calls to perform the actual work.
The host application creates one MCP client for each MCP server it connects to. Local servers typically use STDIO transport (single client), while remote servers use Streamable HTTP (many clients).
The MCP Request Flow: Step by Step
The complete request flow from user goal to tool result involves nine steps. Here's how they work.
Step 1: User Provides a Goal
The user gives the AI agent a high-level goal. For example: "I need to find the best flight from New York to London next Tuesday, but only if the price is under $600."
Step 2: Model Processes and Decides to Call a Tool
The language model within the agent processes the goal and determines that it needs to call a tool to get flight data. It constructs a tool call with the appropriate parameters (origin, destination, date, price constraint).
This is where the model's reasoning and planning capabilities are exercised. The model identifies the need for a tool, selects the appropriate tool from available options, and prepares the parameters.
Step 3: MCP Client Sends a JSON-RPC Request
The agent passes the tool call to the MCP client. The client constructs a JSON-RPC 2.0 request with the following structure:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "searchFlights",
"arguments": {
"origin": "New York",
"destination": "London",
"date": "2026-09-10",
"maxPrice": 600
}
},
"id": 1
}
The client sends this request over the configured transport (STDIO for local servers, Streamable HTTP for remote servers).
Step 4: MCP Server Authenticates the Request
Before processing the request, the server authenticates the client. For OAuth 2.1 flows:
- If the client has a valid access token, it includes it in the Authorization header
- If the client does not have a token, the server returns a 401 Unauthorized with a Protected Resource Metadata (PRM) document location
- The client fetches the PRM document to discover the authorization server and supported scopes
- The client initiates the authorization flow (user authentication with PKCE, token exchange)
- The client obtains an access token and retries the request
For STDIO-based local servers, authentication is typically handled through environment-based credentials or third-party libraries embedded in the server.
Step 5: Server Authorizes and Validates the Request
Once authenticated, the server checks if the client has permission to call the requested tool. MCP supports tool-level RBAC, enabling least-privilege enforcement.
The server then validates the tool inputs against the tool's JSON Schema. Each tool defines an inputSchema that specifies the expected parameters, their types, and whether they are required. If validation fails, the server returns a JSON-RPC error.
The server may also perform additional checks at this point:
- Rate limiting — Ensure the client isn't exceeding usage limits
- Quota checks — Verify the user has sufficient quota for the operation
- Context validation — Check that the request makes sense given the current session context
Step 6: Server Executes the Tool
With validation complete, the server executes the tool. This involves:
- Mapping the tool name to an implementation function
- Converting the JSON arguments to the implementation's expected format
- Calling the implementation (which may invoke external APIs, query databases, modify files, etc.)
- Capturing the result or error
This is the point where the server actually does the work—querying the flight API, searching the database, or modifying the file system.
Step 7: Server Validates Output and Returns Result
After the tool executes, the server validates the output against the tool's output schema (if defined). If validation fails, it returns an error.
Otherwise, the server constructs a JSON-RPC 2.0 response:
{
"jsonrpc": "2.0",
"result": {
"content": [
{
"type": "text",
"text": "Found 3 flights under $600: United 421 ($545), British Airways 72 ($580), Delta 48 ($595)"
}
],
"metadata": {
"origin": "New York",
"destination": "London",
"date": "2026-09-10",
"count": 3
}
},
"id": 1
}
The server sends this response back to the MCP client.
Step 8: Client Returns Result to Agent
The MCP client receives the JSON-RPC response, extracts the result, and passes it to the agent.
The agent now has the tool result. Depending on the agent's design, it may:
- Present the result directly to the user
- Incorporate the result into its next reasoning step
- Call additional tools based on the result
- Ask the user for clarification if the result is insufficient
Step 9: Model Generates Final Response
Finally, the language model incorporates the tool result into its final response to the user. The response may be a summary of the flight options, a recommendation, or a follow-up question.
If the agent needs to call additional tools to complete the goal, the cycle repeats.
Authentication and Authorization in Depth
Security is a critical concern in MCP implementations. The protocol supports OAuth 2.1 authorization for remote servers.
OAuth 2.1 with PKCE
MCP follows the conventions outlined for OAuth 2.1. Authorization is strongly recommended when your server:
- Accesses user-specific data
- Needs to audit actions
- Grants access requiring user consent
- Operates in enterprise environments
The flow uses PKCE (Proof Key for Code Exchange) to protect against authorization code interception attacks.
Protected Resource Metadata (PRM)
MCP servers that require OAuth 2.1 return a 401 Unauthorized with a Protected Resource Metadata (PRM) document location. The PRM document follows RFC 9728 and provides:
- resource — The resource server's identifier
- authorization_servers — URLs of the authorization servers
- scopes_supported — Scopes the server supports
The client fetches this document to discover the authorization server and supported scopes.
Tool-Level RBAC
MCP supports tool-level Role-Based Access Control. This allows:
- Granular permission enforcement — analysts can read databases but not write
- Least-privilege access — tools only get the permissions they need
- User-identity mapping — the MCP server uses the user's identity to determine what permissions they actually have
The server receives the access token, validates it against the upstream provider, and uses the user's identity to determine tool access.
Local Server Considerations
For MCP servers using the STDIO transport, the security model is different:
- Environment-based credentials can be used
- Credentials can be provided by third-party libraries embedded directly in the MCP server
- The server runs locally and has access to the user's local credentials
Security experts recommend user-scoped OAuth 2.1 authentication with PKCE over broad service-scoped credentials to reduce the risk of AI agents acting with excessive privileges.
Tool Discovery: The tools/list Request
Before calling a tool, the agent needs to know what tools are available. MCP supports tool discovery through the tools/list request.
The client sends a tools/list request:
{ "jsonrpc": "2.0", "method": "tools/list", "id": 1}
The server responds with a list of available tools, each with a name, description, and input schema:
{
"jsonrpc": "2.0",
"result": {
"tools": [
{
"name": "searchFlights",
"description": "Search for available flights between two cities on a given date",
"inputSchema": {
"type": "object",
"properties": {
"origin": {
"type": "string",
"description": "Departure city"
},
"destination": {
"type": "string",
"description": "Arrival city"
},
"date": {
"type": "string",
"format": "date",
"description": "Travel date"
},
"maxPrice": {
"type": "number",
"description": "Maximum price in USD"
}
},
"required": [
"origin",
"destination",
"date"
]
}
}
]
},
"id": 1
}
Tool discovery typically happens during initialization or when the agent's available tools need to be refreshed.
Validation: Input and Output
Validation is a critical part of the MCP request flow, ensuring that tools are called with correct parameters and return expected results.
Input Validation
When the server receives a tools/call request, it validates the arguments against the tool's inputSchema:
- Check that all required parameters are present
- Validate parameter types (string, number, boolean, object, array)
- Validate formats (date, email, URI)
- Validate constraints (minimum, maximum, enum)
If validation fails, the server returns a JSON-RPC error with code -32602 (Invalid params) and a descriptive message.
Output Validation
If the tool defines an output schema, the server validates the output before returning it:
- Check that the output matches the expected structure
- Validate value types and formats
- Ensure the output is complete
Output validation prevents malformed responses from reaching the model and helps maintain data integrity.
Error Handling
Error handling in MCP follows JSON-RPC 2.0 conventions. Errors are returned with an error code and message.
JSON-RPC Error Categories
JSON-RPC defines a set of standard error codes:
- -32700 — Parse error (invalid JSON)
- -32600 — Invalid Request (invalid JSON-RPC structure)
- -32601 — Method not found (tool not available)
- -32602 — Invalid params (validation failure)
- -32603 — Internal error (server error)
MCP-Specific Errors
MCP adds additional error codes:
- 401 — Unauthorized (authentication required)
- 403 — Forbidden (authorization failure)
- 404 — Tool not found
- 409 — Conflict (concurrent modification)
- 429 — Too Many Requests (rate limiting)
- 500 — Tool execution error
Error Response Example
{
"jsonrpc": "2.0",
"error": {
"code": -32602,
"message": "Invalid params: maxPrice must be a number",
"data": {
"parameter": "maxPrice",
"received": "six hundred",
"expected": "number"
}
},
"id": 1
}
Error Handling Strategies
When the client receives an error, it should handle it appropriately:
- Authentication errors (401) — Initiate OAuth flow and retry
- Authorization errors (403) — Report to user, do not retry
- Validation errors (-32602) — Correct parameters and retry
- Rate limiting (429) — Wait and retry with backoff
- Server errors (-32603, 500) — Retry with exponential backoff
- Tool not found (404) — Refresh tool list and retry or report
Clients should implement proper retry logic with exponential backoff for transient errors.
Logging and Observability
Logging is essential for production MCP implementations. Key areas to log include:
Request Logging
- Incoming request details (method, params, client ID, timestamp)
- Authentication results (success, failure, user ID)
- Authorization decisions (access granted or denied)
- Validation results (success or specific failures)
- Tool execution duration
- Response results or errors
- Outgoing calls to external services (for debugging and audit)
Security Logging
- Authentication attempts (successful and failed)
- Authorization decisions (who accessed what)
- Privilege escalation attempts
- Unexpected errors that might indicate attacks
- Access token issuance and revocation
Observability Patterns
Consider implementing:
- Distributed tracing — Track requests across the entire stack (agent → client → server → tool)
- Structured logging — Use JSON-formatted logs for easier parsing and analysis
- Metrics — Track tool call counts, latency, error rates, and token usage
- Audit trails — Maintain complete records of all tool calls for compliance and debugging
As one practitioner noted: "You can't secure what you can't see. Log everything that matters—authentication, authorization, validation, and execution. Then build dashboards that tell you when something is wrong before it becomes an incident."
Security Boundaries
Several security boundaries should be maintained in MCP implementations:
- Perimeter security — TLS/mTLS for all remote connections
- Authentication — OAuth 2.1 with PKCE for remote servers, environment-based for local
- Authorization — Tool-level RBAC with least privilege
- Input validation — JSON Schema validation for all tool inputs
- Output sanitization — Validate outputs before returning to the client
- Rate limiting — Protect against abuse and denial-of-service
- Audit logging — Complete records of all access and actions
Implementation Checklist
When building an MCP-powered AI agent, consider these implementation decisions:
| Category | Question | Options |
|---|---|---|
| Authentication | How will clients authenticate? | OAuth 2.1 with PKCE / Environment-based / API keys |
| Authorization | How will permissions be enforced? | Tool-level RBAC / Scopes / Role-based |
| Validation | How will inputs be validated? | JSON Schema / Custom validation / Both |
| Error Handling | How will errors be handled? | Retry with backoff / Fail fast / Circuit breakers |
| Logging | What will be logged? | Requests / Security events / Execution details / All |
| Transport | What transport will be used? | STDIO (local) / Streamable HTTP (remote) |
Frequently Asked Questions
How does an AI agent discover tools via MCP?
The agent calls tools/list on the MCP client. The client sends a JSON-RPC request to the server, which responds with a list of available tools, including their names, descriptions, and JSON Schemas.
How does MCP handle authentication?
MCP supports OAuth 2.1 with PKCE for remote servers. The server returns a 401 with a Protected Resource Metadata document, the client discovers the authorization server, and the user authenticates to get an access token. For local servers, environment-based credentials are common.
What is tool-level RBAC in MCP?
Tool-level RBAC allows granular permission enforcement. The MCP server uses the authenticated user's identity to determine which tools they can call, enabling least-privilege access—analysts can read databases but not write.
How does MCP validate tool inputs?
Each tool defines an inputSchema in JSON Schema format. When the server receives a tools/call request, it validates the arguments against this schema, checking required parameters, types, formats, and constraints.
What transport options does MCP support?
MCP supports STDIO for local servers (single client, typically) and Streamable HTTP for remote servers (many clients). The transport determines the communication channel between client and server.
How should I handle errors in MCP?
Error handling depends on the error type. Authentication errors should trigger the OAuth flow. Validation errors should be corrected and retried. Rate limiting requires backoff. Server errors should be retried with exponential backoff. Authorization errors should be reported to the user.
What should I log in an MCP implementation?
Log incoming requests, authentication results, authorization decisions, validation results, tool execution details, response results, errors, and security events. Use structured logging and consider distributed tracing for complex workflows.
Conclusion
Building AI agents with MCP requires understanding the complete request flow—from model decision through client, server, tool, and back. It requires careful attention to authentication, authorization, validation, and error handling. It requires logging and observability to maintain visibility into what the agent is doing.
The MCP request flow is a chain of nine steps, each with its own responsibilities and failure modes. The client must discover tools, authenticate, and send valid requests. The server must authenticate, authorize, validate, execute, and validate again. The agent must handle errors, retry transient failures, and maintain context across multiple tool calls.
Production implementations must include security boundaries at every level: perimeter, authentication, authorization, input validation, and output sanitization. Audit logging provides visibility and accountability.
As MCP continues to evolve and adoption grows, the patterns in this guide will become standard practice. The key is to build with security and observability from the start, not as an afterthought. The agentic AI future is built on reliable, secure tool integration—and MCP is the standard that makes it possible.