Wooden chess pieces on a real board, a child blurred behind them: the opponent he talks to lives on a server, and it has to sign in before it can play.

My son wanted to play chess against an AI agent, so I built him one that plays at a real board. He says a move out loud, the AI answers, and he moves its piece for it.

The first full game worked through the Claude app on my iPhone. Every move was spoken, read back, and answered with a move from Stockfish. I gave Stockfish the chess decisions after the agent lost all six games it played on its own. An MCP server now holds the board, and the agent only listens and speaks.

Getting that game working was easier than getting the phone signed in. Unlike Claude Code connecting to a local server, the Claude app connects through Anthropic’s cloud, so my server needed a public address and real OAuth. The MCP Python SDK (I used 2.3.0) ships an authorization server that does most of that work. What it does not do is agree with every valid client, and neither did my first version of the code around it.

TL;DR: MCP clients differ in their redirect port, in which URL they send as the resource, and in how they authenticate at /token. The Python SDK’s auth server matches redirects exactly, and advertises HTTP Basic at /token but refuses it when the body has no client_id. Accept only the variations you mean to support, then bind every token to your /mcp URL.

Standards-compliant clients, SDK defaults, and a real deployment can disagree in ways you only see when you put them together.


The phone cannot reach localhost

On a laptop this was easy. The server listened on 127.0.0.1, Claude Code connected to it, and nothing needed a password.

The iPhone app is different. Per Claude’s connector authentication docs, traffic to your server comes from Anthropic’s published IP range, not from the device. The phone visits the server only to show the sign-in page. Every tool call comes from Anthropic’s side, and a server on my laptop was invisible to it.

For hosting, TLS, and the bearer-token setup I started from, see how to deploy a Python MCP server. This time it was a small Amazon Lightsail instance with Caddy in front.

The SDK covers the protocol: discovery documents, client registration, PKCE, and the /authorize, /token, and /revoke endpoints. I wrote the rest. It is a single-user server: one password, set in an environment variable, guards every game on it. Around that sit a SQLite store for clients and hashed tokens, a sign-in page, a cap on registered clients, and a lockout after five wrong passwords.

Some of what follows is an SDK limitation. Some was my own code, and one is configuration the SDK expects you to do. I mark which is which:

Symptom Whose Check first
Redirect URI ... not registered SDK default registered vs requested callback, port included
invalid_target my code resource sent vs your canonical URL
401 invalid_client at /token SDK defect Basic header vs form-body client_id
403 Invalid Origin header configuration request Origin vs the allowlist

The four cases are supported by different kinds of evidence: an origin refusal I reproduced, a resource check in my own code that refused a spelling the spec allows, a Basic auth defect in the SDK source, and a loopback port mismatch I guarded against without ever seeing it happen.


Problem 1: “Redirect URI not registered” when the port moves (SDK default)

A native client like Claude Code signs in by opening your sign-in page in a browser, then listening on a local port for the redirect back. The SDK stores the redirect URIs at registration and later checks the one in the authorization request with redirect_uri not in self.redirect_uris. That is an exact string match, port included.

Claude’s docs say Claude Code uses “an ephemeral port that varies per session”. If it registers with one port and later authorizes with another, the exact match fails. RFC 8252 section 7.3 says the server “MUST allow any port to be specified at the time of the request for loopback IP redirect URIs”. Strictly, that rule names loopback IP literals like 127.0.0.1. Claude Code uses localhost, so I apply the same rule to that one host name and to nothing else.

Other servers have tripped on this. Notion’s MCP server rejected Claude Code’s random port in claude-code issue #52961, and strict loopback matching broke VS Code in one developer’s test of five MCP clients.

My server matches loopback redirects on host and path and ignores the port. The pattern must match the whole URI, and the port must be in range:

LOOPBACK = re.compile(
    r"http://(localhost|127\.0\.0\.1)"
    r"(?::([0-9]{1,5}))?/callback"
)

def loopback_host(uri: str) -> str | None:
    m = LOOPBACK.fullmatch(uri)
    if m is None:
        return None
    if m[2] is not None and not 0 < int(m[2]) < 65536:
        return None
    return m[1]

This is deliberately narrow: only /callback, only on localhost or 127.0.0.1. It is not general loopback validation. A request passes when its loopback host equals a registered loopback host; every other redirect still goes through the SDK’s exact check. Registration accepts only three kinds of URI: Claude’s fixed callback https://claude.ai/api/mcp/auth_callback, ChatGPT’s two documented callback paths on chatgpt.com (one fixed, one /connector/oauth/<id>), and this loopback pattern. Each is matched against the whole URI, never just the domain.

That port-blind check was there before the server went public, because the docs warned about it. Making the port optional came later. Claude’s docs say Claude Code’s client metadata document declares http://localhost/callback with no port, and Pydantic’s AnyUrl drops a default :80, so a pattern that demanded a port would refuse both.

What Claude Code actually sent

Docs describe what a client should do. I wanted to see what one does. So I wrote a 65-line Python server that serves the discovery documents, accepts any registration, and logs every request. I pointed Claude Code 2.1.316 at it and chose Authenticate in /mcp. This is the registration it sent:

{
  "client_name": "Claude Code (oauthprobe)",
  "redirect_uris": ["http://localhost:49625/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none",
  "application_type": "native",
  "scope": "chess"
}

It used dynamic registration, because my test server did not offer client metadata documents. It registered a specific port, and that port stayed at 49625 even after I restarted Claude Code. The sign-in URL it built used the same port and sent the /mcp URL as its resource.

What this does not show is a failure. I never saw the port change, so I never saw an exact match break. What it does show is that the registered URI carries a port, so an exact match is one port change away from refusing the client. The docs say that change happens. This is one client version on one machine, and the port may well move under other conditions, for example when 49625 is taken.


Problem 2: invalid_target when the client sends the origin (my code)

The MCP authorization spec has clients send a resource parameter naming the server they want a token for. Its examples of valid resource identifiers include both https://mcp.example.com/mcp and https://mcp.example.com, and it asks clients to send the most specific one they can.

My server advertises https://chess.example.com/mcp, and my first version compared the parameter against it as a plain string, so a client that sent the origin would have got invalid_target. I have not seen a client send the origin; Claude Code sent the /mcp URL. The spec allowing it was reason enough to change the check. My original strict comparison was defensible, because the spec asks clients to use the canonical identifier, and the SDK had nothing to do with it. But this server has exactly one MCP resource, so I chose to accept the origin as an alias for it rather than fail the sign-in.

The change accepts either spelling, normalized the way the SDK normalizes URLs. Then, whatever the client sent, the server records the /mcp URL on the request:

self.resource = f"{public_url}/mcp"
self.resource_names = {
    normal_url(self.resource),
    normal_url(public_url),
}

The second step matters more. Accepting the origin at the door does not widen what a token is good for. Every access and refresh token is bound to the /mcp URL. With validate_token_resource=True, the SDK’s bearer middleware rejects a token issued for any other resource on every request to /mcp.

One more trap on the same URL: the connector address must be exactly https://chess.example.com/mcp. With a trailing slash, the server answers 404.


Problem 3: 401 invalid_client with Basic auth at /token (SDK defect)

This is the one I would call a bug. The SDK writes the server’s discovery document, and mine says:

"token_endpoint_auth_methods_supported": [
  "client_secret_post",
  "client_secret_basic"
]

Then its client authenticator (in 2.3.0, middleware/client_auth.py) does this, before it looks at any header:

client_id = form_data.get("client_id")
if not client_id:
    raise AuthenticationError("Missing client_id")

So a client that registers for client_secret_basic, trusts the metadata, and sends its credentials only in the Authorization header gets 401 invalid_client. That client is doing what RFC 6749 section 2.3.1 asks: servers “MUST support the HTTP Basic authentication scheme”, and credentials in the body are “NOT RECOMMENDED”. The SDK tracks this as issue #1315. SDK 2.3.0, the version I tested in November 2026, behaves this way. Check the issue to see whether a later release has fixed it.

Claude Code is not affected, because it registers as a public client with no secret. A client that uses Basic and leaves client_id out of the body is.

My workaround is a small ASGI wrapper on /token and /revoke. When a request has a Basic header and no client_id in the form, the wrapper decodes the header and adds the ID and secret to the form. RFC 6749 has the client form-encode the ID and secret before Base64, so decode both layers, strictly:

raw = base64.b64decode(encoded, validate=True)
client_id, colon, secret = raw.decode().partition(":")
client_id = unquote_plus(client_id, errors="strict")
secret = unquote_plus(secret, errors="strict")

Use unquote_plus, not unquote: in form encoding a + is a space. Treat a header with no colon or an empty ID as unreadable. The wrapper does not authenticate anything. The SDK still checks the ID and secret, and anything the wrapper cannot read passes through untouched, so the SDK writes the error, not my code.

This fixes the missing client_id and nothing more. A request that already has a client_id in the body passes through untouched. For a client registered to use Basic, the SDK also checks that the header ID matches it. The wrapper leaves the Basic header in place, and the SDK decodes it a second time with plain unquote. If a client encodes a space as +, the wrapper reads a space but the SDK reads a literal plus, so authentication still fails. This server’s clients all come through dynamic registration, where the SDK issues UUID IDs and hex secrets, so they never hit it. A pre-registered ID or secret containing a space can.

The wrapper also fixed a blind spot. In public mode the server keeps no access log, by design, so a failed token exchange left nothing behind. Now each /token failure logs one line, with the status and client ID only:

OAuth /token failed: status=401 client_id='...'

Problem 4: 403 Invalid Origin header after sign-in (configuration)

The SDK’s transport security refuses a request whose Origin header is not on its allowed list, with 403 Invalid Origin header. That is a guard against DNS rebinding, where a web page in your browser tricks it into calling a server on your own machine. It is doing its job. On a public server, though, the list has to include the apps that call you. With the default list, the SDK refused Origin: https://chatgpt.com in my tests.

Public mode adds https://claude.ai, https://chatgpt.com, and the server’s own URL. Requests with no Origin header, like Claude Code’s, still pass.

Origin is a header browsers set honestly and any other program can set to anything. The list makes the server refuse requests that carry an origin not on it, which blocks a page on some other site from using a visitor’s browser against the server. It is one layer of browser defense, not a boundary, and it does not identify ChatGPT. Nothing here does. The bearer token authorizes access, and it is checked on every request whatever the origin says.

The trap is the order on this stack. The SDK’s bearer check runs before its transport security, so a request without a valid token gets 401 whatever its origin. The 403 only appears after a successful sign-in, which makes it look like a token problem. To tell them apart, send the same request with a valid token twice, once without an Origin header and once with the app’s origin. If only the second fails, it is the origin list.


Two production lessons

Neither of these is a compatibility trap. Both come with running an authorization server at all.

Registration creates a client per connection. Claude’s docs say dynamic registration “causes Claude to register a new client on every fresh connection”. My registration endpoint is open to anyone who can reach it, so the store holds at most 100 clients. At the cap, a new registration pushes out the oldest client that never finished signing in. Registration is refused only when all 100 have signed in.

I added a refresh retry window. With rotation and reuse detection, an old refresh token coming back is treated as theft, so a lost response would end a game mid-move. My server accepts a rotated token again for 60 seconds from its first use, and a retry gets back the pair the first refresh issued, never a new one. Reuse after the window revokes every token the client holds. The cost: a thief who uses the old token within that minute gets the same pair the client holds, and nothing notices. Retries live in memory, so after a restart a retry inside the window is refused without revoking anything.


What I still have not tested

ChatGPT. The server accepts its redirects and its origin, but I have not completed a sign-in from it. Which resource it sends, whether it uses Basic auth, and whether a given plan allows write tools are all open. The Basic fix exists because the SDK advertises a method it cannot read, not because I watched ChatGPT fail.


Accept narrowly, bind what you issue

The Python SDK gave me a solid starting point. It handled PKCE, discovery, registration, and token validation. But a working authorization server is not automatically a compatible one. The four problems had four different causes: an SDK default, a strict choice in my own code, an SDK defect, and missing configuration. From the client’s side, any of them can look like a failed sign-in.

Being generous in OAuth is dangerous if it means accepting anything. The answer was to accept a few named variations without weakening what the server trusts: any port, but only for approved loopback callbacks; two resource identifiers, but for one MCP endpoint; two credential formats, but checked by the same authenticator. Every token still belongs to one resource.

My son never sees any of this. He says his move, the agent answers, and the game goes on. Getting there meant checking client requests and SDK behavior, not assuming the first client that worked spoke for them all. For what an open registration endpoint exposes, see the MCP server security checklist.

mcp security ai-agents llm
Kevin Tan

Kevin Tan

Cloud Solutions Architect and Engineering Leader based in Singapore. I write about AWS, distributed systems, and building reliable software at scale.