MCP Localhost Errors: CORS, Ports and "Connection Refused" Fixed
Nikhil Tiwari
MCP Playground
π TL;DR
- "Connection refused" means nothing is listening on that address and port. CORS and auth can't cause it.
- A Node server started with
listen(port, "localhost")may only listen on IPv6::1, so clients using127.0.0.1are refused. - CORS only matters for clients running in a browser. Claude Desktop, Cursor and Claude Code don't send preflights.
- Browser clients also need
Mcp-Session-IdinAccess-Control-Expose-Headers, or every request afterinitializefails. - A 403 "Invalid Host" or 421 through ngrok comes from the SDK's DNS-rebinding check. Add the tunnel's hostname to the allowed hosts.
Table of Contents
- Which localhost error do you have?
- Step 1: check the server is listening
- 2. localhost vs 127.0.0.1
- 3. Right port, wrong path or transport
- 4. Docker and WSL: bound to the wrong interface
- 5. Port already in use (and macOS AirPlay)
- Fixing the MCP localhost CORS error
- 403 "Invalid Host" and 421 through a tunnel
- Why web tools can't reach your localhost server
- Test a localhost MCP server without CORS
- FAQ
You started your MCP server on http://localhost:3000/mcp, pointed a client at it, and got "connection refused". Or the client is a web app, and the browser console is full of CORS errors.
These get lumped together as "my local server doesn't work", but they fail at different layers. With an MCP localhost CORS error, your server did answer and the browser refused to hand the response to your code. With "connection refused", the request never reached a running server.
So the first job is working out which one you have, which takes a single curl command. After that I'll go through the five network causes and the two header causes I run into most. Error messages below are copied from the official TypeScript (v1.32) and Python SDKs, and the network tests were run on a Mac with Node 22.
This post covers HTTP servers (Streamable HTTP or SSE). If you have a stdio server that won't start, fixing spawn npx ENOENT is the better place to start, and if MCP itself is new to you, read what the Model Context Protocol is first.
Which localhost error do you have?
Start from the exact message. It usually tells you which layer broke:
| What you see | What it means | Go to |
|---|---|---|
ECONNREFUSED, "fetch failed", curl's "Couldn't connect to server" | Nothing listens on that address and port | Steps 1, 2, 4 |
| 404, 405 "Method not allowed.", 406 "Not Acceptable" | Server is up; wrong path, transport or headers | Fix 3 |
EADDRINUSE when the server starts | Another process already has the port | Fix 5 |
| "blocked by CORS policy" in the browser console | Server answered; the browser withheld the response | CORS |
| 403 "Invalid Host", 421 "Invalid Host header", 403 "Invalid Origin header" | The SDK's DNS-rebinding check rejected the request | Host checks |
| "Local and loopback URLs are not allowed" | A hosted tool can't reach your machine | Web tools |
Step 1: check the server is listening
Before you change any config, check that some process actually owns the port. It takes ten seconds and rules out half the causes on this page.
On macOS or Linux:
lsof -nP -iTCP:3000 -sTCP:LISTEN
On Windows (PowerShell or cmd):
netstat -ano | findstr :3000
If nothing comes back, nothing is listening. If something does, read the address column: 127.0.0.1:3000 is IPv4 only, [::1]:3000 is IPv6 only, and *:3000 or 0.0.0.0:3000 means every interface. That column matters in the next section.
Then send the server any request:
curl -i -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{}'
Any HTTP status, even a 400, proves the server is reachable, and the problem is higher up: path, headers or CORS. When nothing is there, curl 8 on macOS prints:
curl: (7) Failed to connect to 127.0.0.1 port 3000 after 0 ms: Couldn't connect to server
When nothing is listening
- The server crashed on startup. Scroll up in its terminal. A missing API key is the usual culprit (see env variables not reaching your server).
- It's on a different port. The Python SDK defaults to
127.0.0.1:8000, while most TypeScript examples use 3000. Trust the startup log over your memory. - It started in stdio mode. Plenty of servers choose the transport from a flag such as
--transport http. Leave it off and they sit waiting on stdin without opening a port. - It isn't running any more. Closing a terminal tab kills a dev server, and so does a watcher that crashed during a rebuild.
2. localhost vs 127.0.0.1
On most machines today, localhost resolves to two addresses. On my Mac, Node's dns.lookup returns IPv6 first:
[ { address: '::1', family: 6 }, { address: '127.0.0.1', family: 4 } ]
That ordering bites on the server side. In Node, app.listen(3000, "localhost") binds to the first address only. When I ran it, the server listened on ::1 and nothing else:
bound to { address: '::1', family: 'IPv6', port: 3458 }
fetch http://localhost:3458/ 200
fetch http://127.0.0.1:3458/ ECONNREFUSED 127.0.0.1:3458
Any client configured with 127.0.0.1 gets refused, and Python clients, Docker port forwards and plenty of config snippets use 127.0.0.1. Meanwhile curl to localhost works fine, which makes it look like the client is the broken part.
The opposite case is mostly history now. Node 17 to 19 would try only ::1 and fail with connect ECONNREFUSED ::1:3000 against an IPv4-only server. Node 20 and later fall back to IPv4 (Node 22 connected fine in my test), but you'll still see that error from older runtimes and from clients that turn the fallback off.
The fix either way: use the same literal address on both sides. I bind to 127.0.0.1 and put http://127.0.0.1:3000/mcp in the client, which takes name resolution out of the picture.
3. Right port, wrong path or transport
If curl gets any HTTP status back, the network side is fine and the URL or transport is what's wrong. These are the status codes the TypeScript SDK returns:
- 404: wrong path. Streamable HTTP servers usually serve
/mcp, older SSE servers use/sseplus/messages, and some use/or/api/mcp. - 405 "Method not allowed.": a GET or DELETE hit a server that doesn't handle it. You'll see this when a client tries SSE against a Streamable HTTP endpoint.
- 406 "Not Acceptable: Client must accept both application/json and text/event-stream": your hand-written request left out the
Acceptheader. Real clients send it. - 400 "Bad Request: Mcp-Session-Id header is required": a 2025-11-25 stateful server got a request without the session ID it handed out. In a browser this is almost always the expose-headers problem.
Make sure the client's transport setting matches the server, too. A client set to SSE won't talk to a Streamable HTTP /mcp endpoint, and the MCP transports spec describes how each one works.
One more wrinkle: servers on the 2026-07-28 spec are stateless. There's no Mcp-Session-Id at all, and each POST carries Mcp-Method and Mcp-Name headers instead.
4. Docker and WSL: bound to the wrong interface
Inside a container, 127.0.0.1 is the container's own loopback. A server bound there can't be reached from your Mac or Windows host, even with -p 3000:3000, because the forwarded traffic arrives on a different interface.
Bind to every interface inside the container, then publish the port:
# Python SDK 2.x (in 1.x, pass host and port to FastMCP(...))
mcp.run(transport="streamable-http", host="0.0.0.0", port=3000)
# then
docker run -p 127.0.0.1:3000:3000 my-mcp-server
Keep the 127.0.0.1: prefix on -p. Without it Docker publishes on all your host's interfaces, and anyone on the same Wi-Fi can reach the server.
It goes wrong the other way round as well. A client running in a container can't reach a server on your host through localhost; on Docker Desktop for Mac and Windows, use host.docker.internal.
Binding to 0.0.0.0 also switches off the SDK's automatic Host check, and the TypeScript SDK prints a warning when you do it. The Host header section shows how to keep the check on. For production containers, see the Docker deployment guide.
WSL2 forwards localhost from Windows into the Linux side by default, so a server in WSL is usually reachable from Windows at localhost. If it isn't, bind to 0.0.0.0 inside WSL and check Microsoft's WSL networking docs.
5. Port already in use (and macOS AirPlay)
Sometimes the server never starts, because another process got to the port first:
Error: listen EADDRINUSE: address already in use :::3000
Nine times out of ten it's an old copy of your own server still running in another terminal. Find it and stop it:
# macOS / Linux
lsof -nP -iTCP:3000 -sTCP:LISTEN # note the PID
kill PID
# Windows
netstat -ano | findstr :3000 # last column is the PID
taskkill /PID PID /F
The confusing variant is when the other process answers your requests. On macOS, the AirPlay Receiver listens on ports 5000 and 7000, so a client pointed at localhost:5000 gets a 403 from AirPlay instead of your server.
If curl shows a Server: AirTunes header, that's what happened. Pick another port, or turn off AirPlay Receiver in System Settings β General β AirDrop & Handoff.
Fixing the MCP localhost CORS error
CORS is a browser rule. It only applies when a web page calls your server, and Claude Desktop, Cursor, VS Code, Claude Code and desktop testers all make plain HTTP requests without a preflight. If one of those fails, look elsewhere.
When it's your own web app or a browser-based client, the console shows something like:
Access to fetch at 'http://localhost:3000/mcp' from origin 'http://localhost:5173'
has been blocked by CORS policy: Response to preflight request doesn't pass access
control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Note that a different port makes a different origin. A page on localhost:5173 calling localhost:3000 is a cross-origin request, even though both run on your machine.
The headers an MCP server needs
Streamable HTTP sends custom headers, so the browser makes an OPTIONS preflight before the real request. The server has to allow these request headers:
Content-Type,AcceptandAuthorizationMcp-Session-Id,MCP-Protocol-VersionandLast-Event-ID(2025-11-25 servers)Mcp-MethodandMcp-Name(2026-07-28 servers)
Allowing headers isn't enough on its own. The server also has to expose Mcp-Session-Id (and WWW-Authenticate if you use OAuth) through Access-Control-Expose-Headers.
Leave that out and the browser hides the session ID from JavaScript. initialize succeeds, the client has no session ID to send back, and the next call fails with 400 Bad Request: Mcp-Session-Id header is required. The server log makes it look like a client bug, which is why it takes so long to track down.
TypeScript (Express)
import cors from "cors";
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
const app = createMcpExpressApp(); // Host check on (localhost only)
app.use(cors({
origin: ["http://localhost:5173"], // your web app, not "*"
allowedHeaders: [
"Content-Type", "Accept", "Authorization",
"Mcp-Session-Id", "MCP-Protocol-Version", "Last-Event-ID",
"Mcp-Method", "Mcp-Name",
],
exposedHeaders: ["Mcp-Session-Id", "WWW-Authenticate"],
}));
Python (Starlette)
from starlette.middleware.cors import CORSMiddleware
app = CORSMiddleware(
mcp.streamable_http_app(),
allow_origins=["http://localhost:5173"],
allow_methods=["GET", "POST", "DELETE"],
allow_headers=["Content-Type", "Accept", "Authorization", "Mcp-Session-Id",
"MCP-Protocol-Version", "Last-Event-ID", "Mcp-Method", "Mcp-Name"],
expose_headers=["Mcp-Session-Id", "WWW-Authenticate"],
)
# run with: uvicorn server:app --host 127.0.0.1 --port 3000
Here mcp is your FastMCP instance, renamed MCPServer in Python SDK 2.x. Every option is in Starlette's CORSMiddleware docs.
Avoid Access-Control-Allow-Origin: * or reflecting whatever origin arrives. A local server with an open CORS policy lets any website you visit call your tools. List the origins you actually use; the MCP security best practices explain the risk.
There's one more browser rule. A page on a public website calling localhost counts as a local network request, and recent Chrome versions ask the user for permission before allowing it, on top of CORS. Serving your web app from localhost while you develop avoids the prompt.
403 "Invalid Host" and 421 through a tunnel
You've exposed the server with ngrok or a Cloudflare tunnel. The tunnel connects, and then every request is rejected. The tunnel is working; the rejection comes from DNS-rebinding protection inside the MCP SDK.
The transports spec says servers MUST validate the Origin header and SHOULD bind to 127.0.0.1 when running locally. Both official SDKs now enforce a version of this by default:
- TypeScript:
createMcpExpressApp()on a localhost host only accepts the Host valueslocalhost,127.0.0.1and[::1]. - Python: a server on
127.0.0.1only accepts localhost hosts and origins. A tunnel gets421 Invalid Host header, and a browser page from another origin gets403 Invalid Origin header.
Here's what the TypeScript SDK sent back when I replayed a request with an ngrok-style Host header:
Host: 127.0.0.1:3460 -> 200
Host: abc123.ngrok-free.app -> 403 {"jsonrpc":"2.0","error":{"code":-32000,"message":"Invalid Host: abc123.ngrok-free.app"},"id":null}
The tunnel forwards your request with its public hostname in Host, so the check is doing what it should. Rather than turning protection off, add that hostname:
// TypeScript
const app = createMcpExpressApp({
host: "127.0.0.1",
allowedHosts: ["localhost", "127.0.0.1", "abc123.ngrok-free.app"],
});
# Python
from mcp.server.transport_security import TransportSecuritySettings
security = TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=["127.0.0.1:*", "localhost:*", "abc123.ngrok-free.app"],
allowed_origins=["http://127.0.0.1:*", "http://localhost:*"],
)
app = mcp.streamable_http_app(transport_security=security)
# Python SDK 1.x: FastMCP("my-server", transport_security=security)
Keep in mind that a public tunnel makes your server public. Anyone who has the URL can list and call your tools, so add a bearer token before you share it. The MCP OAuth guide covers the proper version.
Why web tools can't reach your localhost server
Hosted tools run on someone else's servers, where localhost means their machine, not yours. That covers claude.ai and ChatGPT connectors, and it covers our web tester too.
Paste a localhost URL into the browser MCP tester and it answers "Local and loopback URLs are not allowed". It connects from our backend, so it blocks private addresses on purpose. The upside is that it never runs into CORS, which makes it a good check once your server is deployed or tunneled.
For a server that's still on your laptop, you have two options:
- A tunnel, like
ngrok http 3000(ngrok docs) orcloudflared tunnel --url http://localhost:3000(Cloudflare quick tunnels), plus the Host fix above. - A client that runs on your machine, which needs no tunnel and never deals with CORS.
Already deployed? Test any MCP server free β
Test a localhost MCP server without CORS
MCP Playground Desktop opens its connections from the app's Node process rather than from a web page. It reaches localhost directly and never sends a CORS preflight. For HTTP servers it gives you:
- HTTP and SSE transports, with
http://localhost:3000/mcpas the default URL (and stdio for local commands) - a bearer token field and custom headers, so you can test auth before you deploy
- a protocol switch (Auto, 2026-07-28 or 2025-11-25) to check both spec versions
- a JSON-RPC panel with every request and response, including the server's errors
It's also a quick way to split the problem in half. If the desktop app connects and your web app doesn't, the server is fine and you're looking at CORS.
Once tools load, you can try them with real models in Agent Studio on desktop. And if the server connects but lists nothing, see MCP server connected but no tools showing.
Get MCP Playground Desktop for Mac and Windows β
FAQ
Why do I get ECONNREFUSED connecting to my local MCP server?+
Why does localhost work but 127.0.0.1 is refused?+
Do Claude Desktop or Cursor need CORS headers on my MCP server?+
Why does initialize work in the browser but the next request fails?+
Why does my MCP server return 403 or 421 through ngrok?+
Can I test a localhost MCP server in a web-based tester?+
Conclusion
Most localhost MCP failures fall into one of two groups. "Connection refused" is a network problem: the server isn't running, it's on another port, localhost and 127.0.0.1 point at different address families, or Docker bound the wrong interface.
CORS and Host errors mean the server did answer. For browser clients, allow and expose the MCP headers; for tunnels, add the public hostname to the allowed hosts.
Test your localhost MCP server with MCP Playground Desktop β
Written by Nikhil Tiwari
15+ years in product development. AI enthusiast building developer tools that make complex technologies accessible to everyone.
Free MCP Tools (no install)
Build, compare & ship MCP agents
Connect any MCP server, run evals on it, compare 90+ models side-by-side, deploy hosted servers, and save reusable agents you can export as an API β all in your browser.