AI engineering / Advanced / 03.06
Connecting to MCP servers
How an app starts a local MCP server or reaches a remote one, where the keys go, how sign-in works, and what to check before you trust one.
14 min readFree
Plugging a server in
The last lesson, Building an MCP Client, ended with a promise: next, connecting to MCP servers, local and remote. Here it is.
Think of a power strip. Some plugs are for devices on your desk. Others reach a socket in another building. In MCP, the first kind is a local server and the second is a remote server. Each needs its own way in.
By the end you will know how an app reaches a local or a remote server, where secrets belong, how sign-in works, and what to check before you trust a server. You will also run a small Python checker.
A note on versions. The MCP lesson showed the 2025-11-25 revision of the specification, which opens each connection with an "initialize" handshake. This lesson follows the newer 2026-07-28 revision, shown as the latest on the official site when we fetched it on 2026-11-16, and says where the older one differs. Check the current specification before you build.
Key words
- Host
- The app the person uses, such as a chat app or an editor. It connects to servers.
- Local server
- An MCP server that runs as a program on your own computer.
- Remote server
- An MCP server that runs on the internet, at a web address.
- Subprocess
- A program started by another program and kept running beside it.
- stdio
- Short for standard input and output: the two plain text channels every program has. A program reads from one and writes to the other.
- Streamable HTTP
- The standard way MCP talks to a remote server: ordinary web requests sent to one address.
- Environment variable
- A named setting handed to a program when it starts, such as NOTES_TOKEN. The program reads it by name.
- OAuth
- A standard way to sign in. You prove who you are to a sign-in service, and it gives the app a pass (an access token) instead of your password.
Local servers: a program on your computer
The official guide on connecting to local servers says MCP servers "are programs that run on your computer and provide specific capabilities" to the app. Its example host is Claude Desktop, and it adds that the concepts apply to other clients too.
How does the host start one? The specification's stdio page answers in one sentence: "the client launches the MCP server as a subprocess." The host runs a command, just as you would type it in a terminal, and keeps the program alive in the background.
Then they talk through the two text channels. The specification says the server reads messages from stdin and writes messages to stdout, one message per line. The messages are the same JSON-RPC messages from the MCP lesson.
- 1
Read the config
The host opens its config file and finds the list of servers you set up.
- 2
Launch
For each server, the host runs its command with its arguments, as a subprocess.
- 3
Talk
The host writes one message per line into the server's stdin and reads the answers from its stdout.
- 4
Close
To stop, the specification says the client should close the input stream, wait for the server to exit, and only then force it to stop if it does not.
If a local server dies by accident, the latest specification says the client "SHOULD restart it", and that in-flight requests are lost and can be tried again on the fresh process.
About the handshake: in the 2026-07-28 revision, the transports page says every request carries its protocol version and client capabilities inside the message itself. The older revisions set up a session first with the "initialize" step.
Tip
A local server must keep stdout clean. The specification says it "MUST NOT write anything to its stdout that is not a valid MCP message." It may write logs to stderr. So a stray print line in your own server can break the whole connection.
What a config file lists
Most hosts keep the list of servers in a JSON file. In the official guide, Claude Desktop uses a file called claude_desktop_config.json. The guide says this file "tells Claude Desktop which servers to run and how to connect to them." Here is its filesystem example for macOS, copied from the guide. It is shown, not run here.
# From the Connect to local MCP servers docs, shown without its output (not run here)
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/username/Desktop",
"/Users/username/Downloads"
]
}
}
}The guide explains each part in plain terms. "filesystem" is a friendly name that shows in the app. "command" is the program to run, here npx, which the guide calls "Node.js's npx tool" for running the server. "args" are the arguments handed to that command. The first, "-y", answers yes to the install question. The next is the package name. The rest are the folders the server may use.
That last part matters. The guide warns that the server "runs with your user account permissions, so it can perform any file operations you can perform manually." Only list folders you are happy for the model to read and change.
Tip
If a server does not show up, the guide suggests three checks: look for typos in the JSON, make sure paths are absolute and not relative, and try running the command yourself in a terminal to see its error message.
Where secrets belong
Many servers need a key to reach another service, such as a search service. A key is like a house key. You hand a copy only to the person who needs it, and you never tape it to the front door.
For a local server, the usual hand-over is environment variables. The guide shows an "env" part in the config, next to "command" and "args". This is its example, copied exactly, with the key left as three dots.
# From the Connect to local MCP servers docs, shown without its output (not run here)
{
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"APPDATA": "C:\\Users\\user\\AppData\\Roaming\\",
"BRAVE_API_KEY": "..."
}
}
}The host sets those variables when it starts the server. The server reads them by name. The specification backs this idea. Its authorization page says implementations using stdio "SHOULD NOT follow this specification, and instead retrieve credentials from the environment." So a stdio server is not expected to run a sign-in flow. It reads its key from the environment.
Our own advice, not a rule from the pages: a config file with a real key inside is a secret file. Do not paste it into chat or commit it to a public repository. The checker later in this lesson flags a key typed straight into the config.
Remote servers: a web address
A remote server needs no command and no install. You give the host an address. The official remote guide says these servers "are hosted on the internet rather than your local machine" and that their key advantage is accessibility: they are available "from any MCP client with an internet connection."
In the guide's Claude example, you open Settings, choose Connectors, add a custom connector and paste a URL. The guide tells you to enter the complete URL "ensuring it includes the proper protocol (https://)." Its example address is https://example-server.modelcontextprotocol.io/mcp.
Under the hood, the specification calls this transport Streamable HTTP. Here is how it describes the shape of it.
One address
The server exposes "a single HTTP endpoint (the MCP endpoint)" that accepts POST, such as https://example.com/mcp.
One request each
The client sends every JSON-RPC request or notification as its own HTTP POST. That is a normal web request.
Two kinds of reply
The server answers with either a single JSON object or a Server-Sent Events (SSE) stream. SSE keeps the reply open so the server can send several pieces.
The Streamable HTTP page says revision 2026-07-28 removed protocol-level sessions, so nothing is set up first. Older revisions opened a session with the initialize handshake.
A server you run yourself on your own machine can also speak HTTP. The specification says such servers must check the Origin header, and should bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0). Without that, attackers could use a trick called DNS rebinding to reach them from websites.
Signing in to a remote server
Most remote servers want to know who you are. The remote guide says authentication "commonly involves OAuth, API keys, or username/password combinations" and that you follow the prompts the server gives, which may send you to a third-party sign-in page.
The specification is more exact for HTTP. First, it makes authorization optional: "Authorization is OPTIONAL for MCP implementations." When a server does use it, the spec says implementations using an HTTP transport should follow the specification, which is built on OAuth 2.1.
OAuth is like a hotel key card. You show your ID once at the front desk, and the desk gives you a card that opens only your room. The spec has three roles. A protected MCP server acts as an OAuth resource server, the room. The MCP client acts as an OAuth client, the guest. The authorization server issues the access tokens, the front desk. It may sit with the server or be a separate service.
- 1
A request without a pass
The client calls the server. The server answers HTTP 401 Unauthorized, and its WWW-Authenticate header can say which scope (which kind of access) is needed.
- 2
Find the front desk
The server publishes metadata that points to its authorization server. The spec says clients "MUST use OAuth 2.0 Protected Resource Metadata for authorization server discovery."
- 3
You sign in
You sign in and approve the access at the authorization server, which hands the client an access token.
- 4
Show the pass every time
The client sends the token in an Authorization: Bearer header, and the spec says it "MUST be included in every HTTP request."
Two rules protect the pass. Access tokens "MUST NOT be included in the URI query string", so a token never rides in the web address. And a client must not send a server a token that its own authorization server did not issue.
The spec also asks clients to follow "the principle of least privilege" and request only the scopes they need. As a user, read what access a sign-in screen asks for.
Trust before you connect
Connecting a server is like letting a stranger into a shared kitchen. A local server runs as you. A remote server can hold your sign-in. Both act through tools the model calls.
The security page spells out what can go wrong with local servers. Its examples include a malicious startup command hidden in a configuration. Its listed risks include arbitrary code execution, data exfiltration (your data copied out) and data loss. It says a client with one-click setup must show the exact command, mark it as potentially dangerous, and ask for approval first.
Who made it?
The remote guide says to connect only to servers from trusted sources. Treat a server like any program you install: know who wrote it and why you believe them.
What can it do?
Read the tool list before you allow anything. The remote guide lets you enable or disable specific tools, so turn off those you do not need.
What can it reach?
Give it only the folders, accounts and scopes the job needs. A local server inherits your permissions.
Tools bring a second worry. What a server says about its tools comes from the server, and the model reads it. The tools page of the specification says clients "MUST consider tool annotations to be untrusted unless they come from trusted servers." It also says there should always be a human in the loop who can deny tool calls, and that clients should show tool inputs to the user before calling the server, to avoid data leaking by accident or on purpose.
Our own point, building on that: text that comes from a server is not your instruction. A careless or hostile server can write a tool description that tries to give the model orders. How that attack works, and how to defend, is the topic of the next lesson.
Quick check
A local server needs a service key. Where should the key go?
Check a config before you use it
Let's write the safety check as plain Python. It takes a made-up host config, in the same shape as the guide's example, with two local servers and one remote server. For each one it makes three checks: a local server has a command, a remote server has an https:// address, and no value looks like a key. Then it prints the plan.
Be clear about what this is. Nothing is started and nothing is sent. No subprocess runs and no web request leaves your computer. The checker only reads the dictionary and prints sentences. The remote entry, tickets.example.com, is made up. Its guess at what a key looks like is rough: it can miss some and flag honest values.
import re
def looks_like_key(value):
"""Flag long, space-free text that mixes letters and digits, or has a known key prefix."""
if re.fullmatch(r"\$\{\w+\}", value): # ${NAME} is a pointer to an env var, not a secret
return False
if value.startswith(("sk-", "ghp_", "xox")):
return True
return bool(len(value) >= 20 and " " not in value and "/" not in value
and re.search(r"[A-Za-z]", value) and re.search(r"\d", value))
def check(name, server):
problems = []
if "url" in server:
if not server["url"].startswith("https://"):
problems.append("remote url must start with https://")
elif not server.get("command"):
problems.append("local server needs a command")
values = list(server.get("args", [])) + list(server.get("env", {}).values())
values += [server.get("url", "").partition("?")[2]] # a key hidden in the web address
for v in values:
if v and looks_like_key(v):
problems.append("a value looks like a key, move it to an env var")
break
return problems
def plan(name, server):
if "url" in server:
return f"{name}: send HTTPS POST requests to {server['url']}; sign in (OAuth) if asked"
names = ", ".join(server.get("env", {})) or "none"
cmd = " ".join([server["command"]] + server.get("args", []))
return f"{name}: start subprocess '{cmd}', talk over stdin/stdout, env names: {names}"
def run(title, config):
print(title)
for name, server in config["mcpServers"].items():
problems = check(name, server)
if problems:
print(f" SKIP {name}: " + "; ".join(problems))
else:
print(" OK " + plan(name, server))
good = {"mcpServers": {
"files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/sam/Desktop"]},
"notes": {"command": "python3", "args": ["notes_server.py"], "env": {"NOTES_TOKEN": "${NOTES_TOKEN}"}},
"tickets": {"url": "https://tickets.example.com/mcp"},
}}
bad = {"mcpServers": {
"notes": {"command": "", "args": ["notes_server.py"]},
"search": {"command": "npx", "args": ["-y", "search-server"], "env": {"SEARCH_KEY": "sk-demo1234567890abcdefgh"}},
"tickets": {"url": "http://tickets.example.com/mcp"},
}}
run("Config 1", good)
run("Config 2", bad)Output
Config 1 OK files: start subprocess 'npx -y @modelcontextprotocol/server-filesystem /Users/sam/Desktop', talk over stdin/stdout, env names: none OK notes: start subprocess 'python3 notes_server.py', talk over stdin/stdout, env names: NOTES_TOKEN OK tickets: send HTTPS POST requests to https://tickets.example.com/mcp; sign in (OAuth) if asked Config 2 SKIP notes: local server needs a command SKIP search: a value looks like a key, move it to an env var SKIP tickets: remote url must start with https://
Read the output. The first config passes all three checks, and each plan names the exact command or address. Look at the notes line: it prints only the variable name NOTES_TOKEN, never a value. The second config breaks three rules, one each. The notes server has an empty command. The search server has a long key-like text, so it is skipped. The tickets address starts with http:// instead of https://, so it is skipped too.
Recap
In short: a local server is a subprocess the host starts, a remote server is an https address, and either one deserves the same care you give any program you install.
Quick check
How does a host reach a remote MCP server over Streamable HTTP?
Next: prompt injection attacks, when text tries to take over your app.
Sources
- Model Context Protocol: Connect to local MCP servers
- Model Context Protocol: Connect to remote MCP Servers
- Model Context Protocol: Transports overview (specification, latest)
- Model Context Protocol: stdio transport (specification, latest)
- Model Context Protocol: Streamable HTTP transport (specification, latest)
- Model Context Protocol: Authorization (specification, latest)
- Model Context Protocol: Security best practices (specification, latest)
- Model Context Protocol: Tools (specification, latest)
Last updated on 16 November 2026
Learn with me
Every lesson is free. I add new ones as I learn. Have a question, or want help with your own work? Book a short call.