How to add OAuth sign-in to your ChatGPT plugin server

Day 4, 30 minutes · advanced

Goal of this lessonAdd OAuth sign-in to your MCP server: two tools that need a login, the metadata ChatGPT looks for, and six sign-in cases tested locally with practice tokens.

Why it matters

To add sign-in to a ChatGPT plugin server, you publish where the login service is, refuse calls without a valid token, and return the error ChatGPT uses to show its sign-in prompt.

Two of Ingrid's tools talk about one person's booking. A server that answers anybody who asks would show Pien's booking to Siebe. ChatGPT cannot hold your own API keys or special certificates for you, so for per-person data the plugin pages ask for OAuth: the visitor signs in with a login service, ChatGPT receives a token (a short-lived pass), and your server must check that pass on every call.

Today you build the half of this that lives in your own server and that you can test on your own computer: publish where the login service is, refuse calls without a valid pass, and return the error in the form ChatGPT uses to show its sign-in prompt. The login service itself you cannot build here honestly, so you test with practice tokens and write down what only a real one can prove.

What the auth page requires

The plugin auth page describes OAuth 2.1 with PKCE (a way to stop a stolen code from being reused) using the S256 method. Your server is the resource server: it holds the data. A separate authorization server (the login service) signs people in and issues tokens. Your server has to:

  • publish protected resource metadata at /.well-known/oauth-protected-resource, naming itself and its authorization server;
  • answer a call without a good token with a 401 and a WWW-Authenticate header that points to that metadata;
  • check every call: the signature, the issuer (iss), the audience (aud, the address of your server), the expiry (exp) and the scopes the tool needs.

For the general theory see the MCP advanced course. Here only the ChatGPT-specific part is new.

What ChatGPT needs to show its sign-in prompt

Per tool, a security scheme: noauth, or oauth2 with scopes. The page also says that the tool-level sign-in prompt needs both the metadata and a result from the tool itself with _meta["mcp/www_authenticate"], holding a challenge that contains error and error_description. The code here returns exactly that for a refused call. The page's example wraps that value in stray single quotes; the code does not, and which form ChatGPT accepts was not tested (see the open questions of this course).

Limits to say out loud

  • ChatGPT does not support machine-to-machine OAuth (client credentials, service accounts, JWT bearer), custom API keys or customer mTLS certificates. It presents an OpenAI-managed certificate.
  • The authorization server must list S256 under code_challenge_methods_supported.
  • The iss value must match exactly, with no normalising of a trailing slash. In a test run, the SDK's own helper turned https://auth.example.com into https://auth.example.com/. Check the exact string.
  • Client registration is by CIMD (preferred), DCR or a predefined client. The stable redirect is https://chatgpt.com/connector_platform_oauth_redirect.
  • For refresh tokens the help article says to include offline_access in the provider's advertised scopes.
  • In the Add form, a server with public and signed-in tools matches the choice OAuth or no authentication.

What you can run, and what you cannot

You run your server, the metadata route, the token checks and six cases. You cannot run a real authorization server, the sign-in prompt in ChatGPT or a real registration. The practice token maker in signin_check.py stands in for the login service. Never reuse it for real.

The steps

  1. Add the practice key to .env.
  2. Write signin_check.py, the token check.
  3. Write moorhen_signin.py in three parts.
  4. Run the server and read the metadata.
  5. Run try_calls.py and read six answers.

Pick your tool below and follow the steps.

If something fails

  • import jwt fails: the virtual environment is not active, or PyJWT is not installed.
  • Every call says InvalidAudienceError: PUBLIC_URL in .env changed between making and checking the token. Use the same address in both.
  • Port already in use: stop the earlier server.

Common mistakes

  • Trusting a token without checking the audience.
  • Putting the practice signing key in code or in git.
  • Returning the user's data in the error text.

Today's actions

Ticks are not saved without an account

Do it in OpenAI API

OpenAI API

  1. Add one line to your .env (git ignores it). The key is a practice value on purpose: it is 32 characters or longer, only works on your computer and must never be reused.
    PRACTICE_SIGNING_KEY=practice-only-key-not-a-real-secret
  2. Create signin_check.py: it checks a token's signature, issuer, audience, expiry and scope, and can mint practice tokens.
    import os
    import time
    
    import jwt  # the PyJWT package
    from dotenv import load_dotenv
    
    load_dotenv()
    
    ISSUER = "https://auth.example.com"  # placeholder: no real sign-in lives here
    RESOURCE = os.environ.get("PUBLIC_URL", "http://localhost:3000")
    KEY = os.environ["PRACTICE_SIGNING_KEY"]
    
    
    def check_token(token, needed_scope):
        """Return (claims, None) or (None, (error_code, short_reason))."""
        try:
            claims = jwt.decode(
                token, KEY, algorithms=["HS256"], issuer=ISSUER, audience=RESOURCE,
                options={"require": ["iss", "aud", "sub", "exp"]},
            )
        except jwt.PyJWTError as error:
            return None, ("invalid_token", type(error).__name__)
        if needed_scope not in claims.get("scope", "").split():
            return None, ("insufficient_scope", f"needs {needed_scope}")
        return claims, None
    
    
    def mint(who, scope, audience=RESOURCE, minutes=10):
        """Practice only: a real authorization server issues tokens, not your code."""
        now = int(time.time())
        claims = {"iss": ISSUER, "aud": audience, "sub": who, "scope": scope,
                  "iat": now, "exp": now + minutes * 60}
        return jwt.encode(claims, KEY, algorithm="HS256")
    
  3. Create moorhen_signin.py and paste part one: the metadata route and the function that turns a bad token into a ready error result.
    from mcp.server.fastmcp import Context
    from mcp.types import CallToolResult, TextContent, ToolAnnotations
    from starlette.responses import JSONResponse
    
    from moorhen import KAYAKS, TAKEN, server
    from signin_check import ISSUER, RESOURCE, check_token
    
    BOOKINGS = {"pien": {"date": "2027-06-12", "kayak": "K3"}}
    
    
    @server.custom_route("/.well-known/oauth-protected-resource", methods=["GET"])
    async def protected_resource(request):
        return JSONResponse({
            "resource": RESOURCE,
            "authorization_servers": [ISSUER],
            "scopes_supported": ["booking:read", "booking:write"],
        })
    
    
    def check_request(ctx, scope):
        """Return (who, None) when signed in, else (None, a ready error result)."""
        header = ctx.request_context.request.headers.get("authorization", "")
        token = header[7:] if header.lower().startswith("bearer ") else ""
        claims, problem = check_token(token, scope) if token else (None, ("invalid_token", "no token"))
        if problem is None:
            return claims["sub"], None
        code, reason = problem
        challenge = (
            f'Bearer resource_metadata="{RESOURCE}/.well-known/oauth-protected-resource", '
            f'error="{code}", error_description="{reason}"'
        )
        return None, CallToolResult(
            isError=True,
            content=[TextContent(type="text", text=f"Access refused: {reason}.")],
            _meta={"mcp/www_authenticate": [challenge]},
        )
    
  4. Add part two to the end of the file: the tool that shows your own booking.
    
    
    @server.tool(
        title="Get my booking",
        description="Use this when the signed-in visitor asks about their own kayak booking.",
        annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False, openWorldHint=False),
        meta={"securitySchemes": [{"type": "oauth2", "scopes": ["booking:read"]}]},
    )
    def get_my_booking(ctx: Context) -> CallToolResult:
        who, error = check_request(ctx, "booking:read")
        if error:
            return error
        booking = BOOKINGS.get(who)
        text = f"Booking for {who}: {booking}" if booking else f"No booking for {who}."
        return CallToolResult(content=[TextContent(type="text", text=text)])
    
    
    
  5. Add part three to the end: the tool that books a kayak, which changes data.
    
    
    @server.tool(
        title="Book a kayak",
        description="Use this when the signed-in visitor asks to book a free kayak for a day.",
        annotations=ToolAnnotations(
            readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False
        ),
        meta={"securitySchemes": [{"type": "oauth2", "scopes": ["booking:write"]}]},
    )
    def book_kayak(date: str, kayak_id: str, ctx: Context) -> CallToolResult:
        who, error = check_request(ctx, "booking:write")
        if error:
            return error
        if kayak_id not in {k["id"] for k in KAYAKS} or kayak_id in TAKEN.get(date, set()):
            return CallToolResult(isError=True, content=[TextContent(
                type="text", text=f"Kayak {kayak_id} is not free on {date}.")])
        TAKEN.setdefault(date, set()).add(kayak_id)
        BOOKINGS[who] = {"date": date, "kayak": kayak_id}
        return CallToolResult(content=[TextContent(type="text", text=f"Booked {kayak_id} on {date} for {who}.")])
    
    
    if __name__ == "__main__":
        server.run(transport="streamable-http")
    
  6. Stop any earlier server on port 3000. Run python moorhen_signin.py, then in a second terminal curl http://localhost:3000/.well-known/oauth-protected-resource. You should get one line of JSON naming the resource and the placeholder login service.
  7. Create try_calls.py, run python try_calls.py and compare. Expect: no token refused, read token works, wrong audience refused, expired refused, read token trying to book refused, write token books.
    import asyncio
    
    from mcp import ClientSession
    from mcp.client.streamable_http import streamablehttp_client
    
    from signin_check import mint
    
    URL = "http://localhost:3000/mcp"
    DAY = {"date": "2027-06-19", "kayak_id": "K1"}
    CASES = [
        ("no token", None, "get_my_booking", {}),
        ("read token", mint("pien", "booking:read"), "get_my_booking", {}),
        ("wrong audience", mint("pien", "booking:read", "https://other.example.com"), "get_my_booking", {}),
        ("expired", mint("pien", "booking:read", minutes=-5), "get_my_booking", {}),
        ("read token books", mint("pien", "booking:read"), "book_kayak", DAY),
        ("write token books", mint("siebe", "booking:write"), "book_kayak", DAY),
    ]
    
    
    async def call(token, name, args):
        headers = {"Authorization": f"Bearer {token}"} if token else {}
        async with streamablehttp_client(URL, headers=headers) as (read, write, _):
            async with ClientSession(read, write) as session:
                await session.initialize()
                return await session.call_tool(name, args)
    
    
    for label, token, name, args in CASES:
        result = asyncio.run(call(token, name, args))
        print(f"{label}: error={result.isError} | {result.content[0].text}")
        if result.meta:
            print("   _meta:", result.meta)
    
  8. Write signin-notes.md: one list of what you ran for real, and one of what needs a real login service and ChatGPT (sign-in prompt, registration, exact iss, offline_access).

Note: The practice tokens only work on your computer. auth.example.com is a placeholder: no real sign-in lives behind it. A real authorization server, CIMD or DCR and the sign-in prompt in ChatGPT were not tested here. Never put real tokens in code or in a command you share.

Paid planThe local tests need no plan. Connecting a signed-in server in ChatGPT needs the same plan and role as lesson 3.

Checked on 4 December 2026 · Source: OpenAI Plugins docs: Authentication (opens in a new tab)

Create a free account to save your progress. Sign in or sign up