Local vs Remote MCP Servers: How Model Context Protocol Connects
- Authors

- Name
- Nino
- Occupation
- Senior Tech Editor
The Model Context Protocol (MCP) has quickly emerged as an open standard for connecting AI clients—such as Claude Code, Cursor, or custom LLM applications—to external tools and data sources. Whether you are invoking a local file evaluator or interacting with remote cloud services like Upwork, Notion, or Todoist, understanding the underlying connection mechanism is vital for architecture design, security hardening, and production scalability.
When building robust AI agent workflows or routing model inference through high-performance aggregators like n1n.ai, developers must choose between two primary MCP transport modes: Local (stdio) servers running on the host machine, and Remote (HTTP/SSE with OAuth 2.0) servers hosted on cloud infrastructure.
This guide breaks down the exact protocol exchanges, process behaviors, authentication handshakes, and token verification flows for both server types based on empirical testing and the official MCP specification.
1. Local MCP Servers: Stdio and Process Lifecycle
Local MCP servers operate as child processes spawned directly by the host AI application. Communication occurs over standard input (stdin) and standard output (stdout) pipes using JSON-RPC messages.
+-----------------------+ +-----------------------+
| Host AI Application | --- stdin ->| Local MCP Server |
| (e.g., Claude Code) | <- stdout --| (Child Process) |
+-----------------------+ +-----------------------+
Empirical Process Lifecycle Analysis
To observe how a local MCP server behaves under load, we monitored the process tree when executing a local tool server (such as doceval) inside Claude Code (claude -p) at 250ms sampling intervals:
- Initialization on Session Start: The client host spawns the server as a child process immediately when the session opens—even before any tool call is executed. If your configuration defines three local MCP servers, three distinct processes are initialized immediately.
- Process Reuse Across Calls: Subsequent tool invocations within the same session reuse the existing running process. Executing a tool ten times in a single session results in exactly one process spawn.
- Session Isolation: Each active client session spawns its own independent set of child processes. Three open terminal sessions running Claude Code will spawn three separate instances of the same local MCP server.
- Teardown & Crash Recovery: When the client session ends normally, the host sends a termination signal to close the child process cleanly. If the host process is forcibly killed (
kill -9), the child server'sstdinpipe closes immediately. Well-behaved local MCP servers detectEOF(end-of-file) onstdinand terminate within 2 seconds to prevent orphaned background processes.
Credential Injection in Local Mode
Per the MCP specification, local stdio servers should not implement OAuth 2.0 flows. Instead, secrets and API credentials must be passed via environment variables managed by the host application's configuration file.
To prevent leaking raw secrets into configuration files on disk, modern clients support shell variable expansion:
{
"mcpServers": {
"local-evaluator": {
"command": "node",
"args": ["/path/to/server.js"],
"env": {
"API_KEY": "${MY_CUSTOM_API_SECRET}"
}
}
}
}
At runtime, the host resolves ${MY_CUSTOM_API_SECRET} from the current environment before spawning the child process, maintaining security without requiring browser-based login flows.
2. Remote MCP Servers: HTTP, OAuth 2.0, and PKCE Handshakes
Remote MCP servers reside at HTTPS endpoints (e.g., ai.todoist.net or mcp.upwork.com/mcp). Because remote endpoints are accessible across public networks, they require strict authentication and authorization.
+-------------+ +---------------+ +-------------------+
| AI Client | -----> | MCP Server | -----> | Authorization |
| (Claude Code)| | (Resource Owner)| | Server (OAuth 2) |
+-------------+ +---------------+ +-------------------+
Unlike simple API keys, the MCP spec mandates OAuth 2.0 with Proof Key for Code Exchange (PKCE, RFC 7636) for user authorization.
The 9-Step Remote Connection Sequence
Here is the exact step-by-step handshake executed when an AI client connects to a remote MCP server (such as Upwork, Notion, or Todoist):
AI Client (Claude Code) MCP Server (Resource) Auth Server (OAuth 2.0) Browser / User
| | | |
1. Request resource (No Token) ---->| | |
|<--- 401 Unauthorized -----| | |
| (WWW-Authenticate link)| | |
2. Fetch Resource Metadata -------->| | |
3. Discover Auth Endpoints --------------------------------->| |
4. Resolve Client ID URL ----------------------------------->| |
5. Generate PKCE Verifier & Hash | | |
6. Open Login URL in Browser ---------------------------------------------------->| User Logs In
7. Auth Code returned via Local Redirect <----------------------------------------| User Approves
8. Exchange Auth Code + PKCE Verifier ---------------------->| |
|<--- Access Token & Refresh Token ------------------| |
9. Store Tokens & Send Bearer Token ->| | |
Step 1: Unauthenticated Probe (401 Response)
The client attempts to connect to the remote MCP server URL without a Bearer token. The server responds with 401 Unauthorized containing a WWW-Authenticate header pointing to its protected resource metadata endpoint (e.g., /.well-known/oauth-protected-resource).
Step 2: Resource Metadata Discovery
The client fetches the resource metadata file, which identifies the canonical Authorization Server URL. For example, Todoist's MCP server (ai.todoist.net) points to its authorization server at todoist.com.
Step 3: Authorization Endpoint Discovery
The client reads /.well-known/oauth-authorization-server from the authorization server to retrieve key endpoints: the authorization endpoint, token endpoint, revocation endpoint, and supported PKCE code challenge methods (S256).
Step 4: Client Identification via Metadata URL
To avoid manual registration for every local developer machine, the spec uses client metadata URLs. Claude Code identifies itself using a public metadata URL: https://claude.ai/oauth/claude-code-client-metadata. The authorization server fetches this document to learn client capabilities. Because public CLI tools cannot keep client secrets safe, the metadata specifies "token_endpoint_auth_method": "none".
Step 5: PKCE Secret Generation
Because the client has no shared app secret, it generates a high-entropy random string called the Code Verifier. It computes Code Challenge = SHA256(Code Verifier) to cryptographically bind the authorization request to the subsequent token exchange.
Step 6: User Browser Authorization
The client launches the user's web browser to the authorization URL, appending parameters:
client_id:https://claude.ai/oauth/claude-code-client-metadataredirect_uri:http://localhost/callbackcode_challenge: Base64URL(SHA256(Verifier))code_challenge_method:S256resource: Target MCP Server URL
The user authenticates directly with the provider (e.g., Notion or Todoist). The client never sees or touches the user's password.
Step 7: Authorization Code Callback
Upon approval, the authorization server redirects the browser to http://localhost/callback?code=AUTH_CODE. The client captures this request on its temporary local loopback listener and verifies the request state to prevent CSRF attacks.
Step 8: Token Exchange
The client issues a POST request to the token endpoint containing:
- The authorization code
- The original unhashed Code Verifier
The authorization server hashes the submitted verifier and compares it with the challenge sent in Step 6. If they match, it issues an Access Token (short-lived) and a Refresh Token (long-lived).
Step 9: Token Storage and Request Execution
The client stores the tokens securely in a local, permission-restricted file (e.g., ~/.claude/.credentials.json). Every subsequent HTTP request to the MCP server includes the header: Authorization: Bearer <access_token>
--- < 50ms latency checks ---
3. How Remote MCP Servers Validate Access Tokens
Once an access token reaches an MCP server, the server must validate it before executing any tool logic. Remote MCP servers process tokens using one of two strategies:
Opaque Token Introspection vs. JWT Signature Verification
| Token Mechanism | Storage / Format | Verification Method | Network Overhead | Revocation Latency |
|---|---|---|---|---|
| Opaque Token | Random String | Database lookup or RFC 7662 Introspection call | Requires server-to-auth HTTP call per request | Instant |
| Signed JWT | Header.Payload.Signature | Local cryptographic check using public key (JWKS) | Zero external network calls | Dependent on token TTL |
Deep Dive: Cryptographic JWT Verification Flow
If the MCP server receives a JSON Web Token (JWT), it verifies authenticity locally using public-key cryptography:
import jwt
import requests
def verify_mcp_jwt(token_string, trusted_issuer_url):
# 1. Decode header to extract Key ID (kid)
header = jwt.get_unverified_header(token_string)
kid = header.get("kid")
# 2. Fetch public key set (JWKS) ONLY from trusted issuer URL
jwks_url = f"{trusted_issuer_url}/.well-known/jwks.json"
jwks = requests.get(jwks_url).json()
# 3. Locate matching public key
public_key = get_public_key_by_kid(jwks, kid)
# 4. Verify signature and standard claims (aud, exp, iss)
decoded = jwt.decode(
token_string,
public_key,
algorithms=["RS256"],
audience="https://mcp.target-service.com",
issuer=trusted_issuer_url
)
return decoded
Pro Tip: A secure MCP server must fetch public keys only from the pre-configured authorization server URL (
iss), never from an unverified URL inside the token header itself. This protects against key-spoofing attacks.
Protocol Evolution: Sessionless Architecture
Recent revisions of the MCP specification (including updates leading into 2026 standards) deprecated the initial stateful handshake (initialize session setup and Mcp-Session-Id headers).
Remote MCP servers now operate sessionlessly over HTTP. Every incoming request carries its own protocol version, capability context, and Bearer token. State management is offloaded to token storage on the client disk and revocation lists on the authorization server. This allows remote MCP deployments to scale horizontally behind standard load balancers.
When scaling high-volume AI applications across multiple model providers, developers routing requests through n1n.ai can rely on low-latency inference while managing tool authentication cleanly across isolated remote MCP endpoints.
4. Comprehensive Architectural Comparison
| Feature | Local MCP Server (Stdio) | Remote MCP Server (HTTP / OAuth) |
|---|---|---|
| Transport Layer | Standard I/O Pipes (stdin/stdout) | HTTPS / Server-Sent Events (SSE) |
| Process Execution | Managed as a child process by AI client | Runs on remote cloud server/container |
| Authentication | Environment variables (${ENV_VAR}) | OAuth 2.0 with PKCE (S256) |
| User Credentials | Stored locally in environment or app config | Password kept by provider; client stores tokens |
| Concurrency | 1 process instance per client session | Shared server handling thousands of client connections |
| Process Termination | Triggered by parent pipe closure (EOF) | Stateless / Sessionless request lifecycle |
| Best For | File manipulation, local git, code execution | SaaS tools (Notion, Upwork, Jira, CRM databases) |
5. Security Analysis and Threat Vectors
Understanding the security boundary of each transport mode is essential for production deployments:
Local MCP Security Bounds
- Subprocess Vulnerability: Local MCP servers run with the host user's system privileges. A compromised local server package can execute arbitrary shell commands or access local files.
- Environment Leaks: Storing plaintext secrets in configuration files poses a risk. Developers should always use environment variable expansion (
${SECRET_KEY}) rather than hardcoding credentials.
Remote MCP Security Bounds
- Signing Key Compromise: If an attacker steals a provider's private signing key (as seen in historical security incidents like Storm-0558), they can forge valid JWTs accepted by the MCP server. Key rotation and short access token lifetimes (e.g., 15-60 minutes) mitigate this risk.
- Token Revocation: When an access token expires or is manually revoked, the refresh token exchange fails, forcing the user back to Step 1. This bounds the exposure window of compromised tokens.
For enterprise teams aggregating diverse model endpoints, using robust API infrastructure like n1n.ai ensures reliable token handling and consistent model connectivity across both local development environments and cloud deployments.
Summary Matrix of Credential Storage
| Credential Artifact | Created By | Held / Managed By | Exposure Level |
|---|---|---|---|
| App ID URL | Client Developer | Publicly accessible metadata | Public |
| PKCE Verifier | AI Client | Local memory during auth flow | Secret (Transient) |
| Authorization Code | Auth Server | Query param in browser redirect | One-time use |
| Access Token | Auth Server | Client storage (credentials.json) | Short-lived secret |
| Refresh Token | Auth Server | Client storage & Auth database | Long-lived secret |
| User Password | User | Auth Server only | Confidential |
| Local Server Key | User | Host Environment (env) | Local secret |
By matching your tool architecture to the right transport protocol—using local stdio for high-performance filesystem tasks and remote HTTP/OAuth for secure cloud service integrations—you can build resilient, production-ready AI applications.
Get a free API key at n1n.ai.