# MCP Localhost Errors: CORS, Ports and "Connection Refused" Fixed

> Your MCP server runs on localhost, but the client can't connect, the browser blocks it with a CORS error, or a tunnel gets "Invalid Host". How to check the server is listening, then fix localhost vs 127.0.0.1, wrong paths, Docker binding, busy ports, CORS headers and the SDKs' Host checks.

**Source:** https://mcpplaygroundonline.com/blog/mcp-localhost-cors-connection-refused  
**Author:** Nikhil Tiwari  
**Published:** 2026-11-15  
**Category:** Troubleshooting  
**Reading time:** 11 min read  
**Topics:** mcp localhost cors error, mcp server connection refused, mcp econnrefused localhost, mcp streamable http cors, mcp invalid host header, mcp server localhost not working, mcp-session-id cors expose headers, mcp server docker localhost, mcp server ngrok 403, test local mcp server http

---

📖 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 using `127.0.0.1` are 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-Id` in `Access-Control-Expose-Headers`, or every request after `initialize` fails.
-   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?](#which)
-   [Step 1: check the server is listening](#listening)
-   [2\. localhost vs 127.0.0.1](#ipv6)
-   [3\. Right port, wrong path or transport](#path)
-   [4\. Docker and WSL: bound to the wrong interface](#docker)
-   [5\. Port already in use (and macOS AirPlay)](#port)
-   [Fixing the MCP localhost CORS error](#cors)
-   [403 "Invalid Host" and 421 through a tunnel](#host)
-   [Why web tools can't reach your localhost server](#web)
-   [Test a localhost MCP server without CORS](#test)
-   [FAQ](#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](/blog/fix-spawn-npx-enoent-mcp) is the better place to start, and if MCP itself is new to you, read [what the Model Context Protocol is](/blog/what-is-model-context-protocol) 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](#cors)

403 "Invalid Host", 421 "Invalid Host header", 403 "Invalid Origin header"

The SDK's DNS-rebinding check rejected the request

[Host checks](#host)

"Local and loopback URLs are not allowed"

A hosted tool can't reach your machine

[Web tools](#web)

## 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](/blog/mcp-server-env-variables-not-working)).
-   **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 `/sse` plus `/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 `Accept` header. 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](#cors).

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](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) describes how each one works.

One more wrinkle: servers on the [2026-07-28 spec](/blog/build-mcp-server-2026-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](#host) shows how to keep the check on. For production containers, see the [Docker deployment guide](/blog/deploy-mcp-server-docker-production-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](https://learn.microsoft.com/en-us/windows/wsl/networking).

## 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`, `Accept` and `Authorization`
-   `Mcp-Session-Id`, `MCP-Protocol-Version` and `Last-Event-ID` (2025-11-25 servers)
-   `Mcp-Method` and `Mcp-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](https://www.starlette.io/middleware/#corsmiddleware).

**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](https://modelcontextprotocol.io/docs/tutorials/security/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](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#security-warning) 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 values `localhost`, `127.0.0.1` and `[::1]`.
-   **Python:** a server on `127.0.0.1` only accepts localhost hosts and origins. A tunnel gets `421 Invalid Host header`, and a browser page from another origin gets `403 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](/blog/mcp-server-oauth-authentication-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](https://mcpplaygroundonline.com/mcp-test-server) 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:

1.  **A tunnel**, like `ngrok http 3000` ([ngrok docs](https://ngrok.com/docs/getting-started/)) or `cloudflared tunnel --url http://localhost:3000` ([Cloudflare quick tunnels](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/)), plus the Host fix above.
2.  **A client that runs on your machine**, which needs no tunnel and never deals with CORS.

Already deployed? [Test any MCP server free →](https://mcpplaygroundonline.com/mcp-test-server)

## Test a localhost MCP server without CORS

[MCP Playground Desktop](/blog/mcp-playground-desktop-guide) 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/mcp` as 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](/blog/agent-studio-desktop-local-mcp-tools). And if the server connects but lists nothing, see [MCP server connected but no tools showing](/blog/mcp-server-no-tools-showing).

[Get MCP Playground Desktop for Mac and Windows →](/local-mcp-server-testing)

## FAQ

**Why do I get ECONNREFUSED connecting to my local MCP server?+**

Nothing is listening on the address and port the client used. Either the server crashed, runs on another port, started in stdio mode, or listens on a different address family, such as a Node server bound to "localhost" that only listens on ::1. Check with lsof or netstat, and use 127.0.0.1 on both sides.

**Why does localhost work but 127.0.0.1 is refused?+**

Your server probably called listen with the host "localhost". Node binds to the first address localhost resolves to, which is often IPv6 ::1, so nothing listens on 127.0.0.1. Bind the server to 127.0.0.1 explicitly.

**Do Claude Desktop or Cursor need CORS headers on my MCP server?+**

No. CORS is a browser rule. Desktop apps, IDEs and command-line clients make plain HTTP requests without a preflight. You only need CORS when a web page calls the server from a browser.

**Why does initialize work in the browser but the next request fails?+**

The server returns Mcp-Session-Id, but without Access-Control-Expose-Headers the browser hides it from JavaScript. The client can't send it back, so the server answers 400 "Mcp-Session-Id header is required". Expose Mcp-Session-Id in your CORS config.

**Why does my MCP server return 403 or 421 through ngrok?+**

The official SDKs turn on DNS-rebinding protection for servers bound to localhost and only accept localhost Host headers. The tunnel sends its public hostname. Add that hostname to allowedHosts (TypeScript) or allowed\_hosts in TransportSecuritySettings (Python).

**Can I test a localhost MCP server in a web-based tester?+**

Not directly. Hosted testers connect from their own servers, where localhost means their machine. Use a tunnel such as ngrok or cloudflared, or a desktop client that runs on your machine and has no CORS limits.

## 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 →](/local-mcp-server-testing)

## Frequently asked questions

### Why do I get ECONNREFUSED connecting to my local MCP server?

Nothing is listening on the address and port the client used. Either the server crashed, runs on another port, started in stdio mode, or listens on a different address family, such as a Node server bound to "localhost" that only listens on ::1. Check with lsof or netstat, and use 127.0.0.1 on both sides.

### Why does localhost work but 127.0.0.1 is refused?

Your server probably called listen with the host "localhost". Node binds to the first address localhost resolves to, which is often IPv6 ::1, so nothing listens on 127.0.0.1. Bind the server to 127.0.0.1 explicitly.

### Do Claude Desktop or Cursor need CORS headers on my MCP server?

No. CORS is a browser rule. Desktop apps, IDEs and command-line clients make plain HTTP requests without a preflight. You only need CORS when a web page calls the server from a browser.

### Why does initialize work in the browser but the next request fails?

The server returns Mcp-Session-Id, but without Access-Control-Expose-Headers the browser hides it from JavaScript. The client can't send it back, so the server answers 400 "Mcp-Session-Id header is required". Expose Mcp-Session-Id in your CORS config.

### Why does my MCP server return 403 or 421 through ngrok?

The official SDKs turn on DNS-rebinding protection for servers bound to localhost and only accept localhost Host headers. The tunnel sends its public hostname. Add that hostname to allowedHosts (TypeScript) or allowed_hosts in TransportSecuritySettings (Python).

### Can I test a localhost MCP server in a web-based tester?

Not directly. Hosted testers connect from their own servers, where localhost means their machine. Use a tunnel such as ngrok or cloudflared, or a desktop client that runs on your machine and has no CORS limits.


---

_Canonical page: https://mcpplaygroundonline.com/blog/mcp-localhost-cors-connection-refused — MCP Playground (mcpplaygroundonline.com), the free browser-based tool for testing MCP servers and building AI agents._
