Skip to content

auth

Class info

Classes

Name Children Inherits
ApprovalRedirect
pyt3client.models.auth
`POST /oauth/mcp/decision` result (upstream `AuthMcpApprovalRedirect`).
    EnvironmentDescriptor
    pyt3client.models.environment
    `GET /.well-known/t3/environment`.
      McpTokenResult
      pyt3client.models.auth
      `POST /oauth/mcp/token` result (upstream `AuthMcpTokenResult`).
        OAuthAuthorizationServerMetadata
        pyt3client.models.auth
        `GET /.well-known/oauth-authorization-server`.
          RegisteredClient
          pyt3client.models.auth
          `POST /oauth/mcp/register` result (upstream `AuthMcpRegisteredClient`).
            T3AuthError
            pyt3client.errors
            Signing in failed, or the server no longer accepts the credential.
              T3Credentials
              pyt3client.models.auth
              What a successful sign-in yields; persist it to reconnect without pairing again.
                T3HttpError
                pyt3client.errors
                The server answered with an unexpected HTTP status.
                  T3ProtocolError
                  pyt3client.errors
                  The server answered in a shape this client does not understand.

                    🛈 DocStrings

                    Sign in to a T3 Code environment's /mcp endpoint without a browser.

                    T3 Code lets outside agents use its MCP server through OAuth 2.1 (authorization code + PKCE, dynamic client registration). Interactive clients send the user to an approval page; this module does what the page does, with a pairing code instead of a click. It is the same flow T3 Code itself uses to link one environment to another: upstream PeerLinks.signIn in apps/server/src/peer/PeerLinks.ts.

                    The flow:

                    1. GET /.well-known/t3/environment public descriptor (environment id).
                    2. POST /oauth/mcp/register register a public client (stateless).
                    3. POST /oauth/mcp/decision approve with the pairing code; the answer is the redirect URL carrying code.
                    4. POST /oauth/mcp/token exchange code + PKCE verifier for a token.

                    Server side: apps/server/src/auth/mcpOAuthHttp.ts (routes) and apps/server/src/auth/McpOAuth.ts (validation, approve, exchangeCode). Get a pairing code on the host with t3 auth pairing create, or in the app via Settings -> Sharing & access.

                    fetch_descriptor async

                    fetch_descriptor(base_url: str, *, http_client: AsyncClient | None = None) -> EnvironmentDescriptor
                    

                    Read an environment's public descriptor; needs no credential.

                    Parameters:

                    Name Type Description Default
                    base_url str

                    Environment origin, such as http://127.0.0.1:3773.

                    required
                    http_client AsyncClient | None

                    Client to reuse; a short-lived one is created otherwise.

                    None
                    Source code in src/pyt3client/auth.py
                    130
                    131
                    132
                    133
                    134
                    135
                    136
                    137
                    138
                    139
                    140
                    141
                    142
                    143
                    144
                    145
                    async def fetch_descriptor(
                        base_url: str, *, http_client: httpx.AsyncClient | None = None
                    ) -> EnvironmentDescriptor:
                        """Read an environment's public descriptor; needs no credential.
                    
                        Args:
                            base_url: Environment origin, such as `http://127.0.0.1:3773`.
                            http_client: Client to reuse; a short-lived one is created otherwise.
                        """
                        url = f"{_normalize_base_url(base_url)}/.well-known/t3/environment"
                        async with _client_scope(http_client) as client:
                            response = await client.get(url)
                        if response.status_code != httpx.codes.OK:
                            msg = f"{url} is not a T3 Code environment"
                            raise T3HttpError(msg, status=response.status_code, body=response.text)
                        return _decode(EnvironmentDescriptor, response, "environment descriptor")
                    

                    pair async

                    pair(
                        base_url: str,
                        pairing_code: str,
                        *,
                        access: McpAccess = "auto",
                        client_name: str = DEFAULT_CLIENT_NAME,
                        http_client: AsyncClient | None = None
                    ) -> T3Credentials
                    

                    Sign in to an environment's /mcp with a one-time pairing code.

                    The code is spent by this call. The resulting session shows up in T3 Code under Settings -> Sharing & access with client_name as its label, lasts 30 days, and does not renew.

                    Agents only send credentials over https or to localhost, so use a loopback, Tailscale HTTPS or T3 Connect address. A plain-http LAN address works technically but sends the code unencrypted.

                    Parameters:

                    Name Type Description Default
                    base_url str

                    Environment origin, such as http://127.0.0.1:3773. A trailing /mcp (as shown by "Copy MCP URL") is accepted.

                    required
                    pairing_code str

                    Code from t3 auth pairing create or the app. An app approval code (AUTO-…) fixes the level itself and overrides access; it is matched case-insensitively and sent in canonical upper case.

                    required
                    access McpAccess

                    Level to approve the client at. Must not exceed what the code grants.

                    'auto'
                    client_name str

                    Label the environment shows for this client.

                    DEFAULT_CLIENT_NAME
                    http_client AsyncClient | None

                    Client to reuse; a short-lived one is created otherwise.

                    None

                    Raises:

                    Type Description
                    T3AuthError

                    The environment rejected the code or the sign-in.

                    T3HttpError

                    The address does not answer like a T3 Code environment.

                    Source code in src/pyt3client/auth.py
                    148
                    149
                    150
                    151
                    152
                    153
                    154
                    155
                    156
                    157
                    158
                    159
                    160
                    161
                    162
                    163
                    164
                    165
                    166
                    167
                    168
                    169
                    170
                    171
                    172
                    173
                    174
                    175
                    176
                    177
                    178
                    179
                    180
                    181
                    182
                    183
                    184
                    185
                    186
                    187
                    188
                    189
                    190
                    191
                    192
                    193
                    194
                    195
                    196
                    197
                    198
                    199
                    200
                    201
                    202
                    203
                    204
                    205
                    206
                    207
                    208
                    209
                    210
                    211
                    212
                    213
                    214
                    215
                    216
                    217
                    218
                    219
                    220
                    221
                    222
                    223
                    224
                    225
                    226
                    227
                    228
                    229
                    230
                    231
                    232
                    233
                    234
                    235
                    236
                    237
                    238
                    239
                    240
                    241
                    242
                    243
                    244
                    245
                    246
                    247
                    248
                    249
                    250
                    251
                    252
                    253
                    254
                    255
                    256
                    257
                    258
                    259
                    260
                    async def pair(
                        base_url: str,
                        pairing_code: str,
                        *,
                        access: McpAccess = "auto",
                        client_name: str = DEFAULT_CLIENT_NAME,
                        http_client: httpx.AsyncClient | None = None,
                    ) -> T3Credentials:
                        """Sign in to an environment's `/mcp` with a one-time pairing code.
                    
                        The code is spent by this call. The resulting session shows up in T3 Code
                        under Settings -> Sharing & access with `client_name` as its label, lasts
                        30 days, and does not renew.
                    
                        Agents only send credentials over `https` or to `localhost`, so use a
                        loopback, Tailscale HTTPS or T3 Connect address. A plain-http LAN address
                        works technically but sends the code unencrypted.
                    
                        Args:
                            base_url: Environment origin, such as `http://127.0.0.1:3773`. A trailing
                                `/mcp` (as shown by "Copy MCP URL") is accepted.
                            pairing_code: Code from `t3 auth pairing create` or the app. An app
                                approval code (`AUTO-…`) fixes the level itself and overrides `access`;
                                it is matched case-insensitively and sent in canonical upper case.
                            access: Level to approve the client at. Must not exceed what the code grants.
                            client_name: Label the environment shows for this client.
                            http_client: Client to reuse; a short-lived one is created otherwise.
                    
                        Raises:
                            T3AuthError: The environment rejected the code or the sign-in.
                            T3HttpError: The address does not answer like a T3 Code environment.
                        """
                        origin = _normalize_base_url(base_url)
                        code = pairing_code.strip()
                        if approval := parse_approval_code(code):
                            access, code = approval
                        if access not in get_args(McpAccess.__value__):
                            msg = f"Unknown access level {access!r}"
                            raise ValueError(msg)
                        async with _client_scope(http_client) as client:
                            descriptor = await fetch_descriptor(origin, http_client=client)
                            metadata_response = await client.get(f"{origin}/.well-known/oauth-authorization-server")
                            if metadata_response.status_code != httpx.codes.OK:
                                msg = "Environment does not offer MCP sign-in"
                                raise T3HttpError(
                                    msg, status=metadata_response.status_code, body=metadata_response.text
                                )
                            metadata = _decode(
                                OAuthAuthorizationServerMetadata, metadata_response, "authorization server metadata"
                            )
                    
                            registered_response = await client.post(
                                metadata.registration_endpoint,
                                json={"client_name": client_name, "redirect_uris": [REDIRECT_URI]},
                            )
                            if registered_response.status_code not in {httpx.codes.OK, httpx.codes.CREATED}:
                                raise _oauth_error(registered_response, "Client registration")
                            registered = _decode(RegisteredClient, registered_response, "client registration")
                    
                            verifier = _base64url(secrets.token_bytes(32))
                            challenge = _base64url(hashlib.sha256(verifier.encode("ascii")).digest())
                            state = _base64url(secrets.token_bytes(16))
                            # `resource` must name this server's `/mcp` (RFC 8707); the server derives
                            # its own from Host and X-Forwarded-Proto, so a rewriting proxy breaks this.
                            resource = f"{origin}/mcp"
                            authorization = {
                                "response_type": "code",
                                "client_id": registered.client_id,
                                "redirect_uri": REDIRECT_URI,
                                "code_challenge": challenge,
                                "code_challenge_method": "S256",
                                "state": state,
                                "resource": resource,
                            }
                            decision_response = await client.post(
                                f"{origin}/oauth/mcp/decision",
                                json={
                                    "authorization": authorization,
                                    "decision": {"_tag": "pairing-code", "access": access, "code": code},
                                },
                            )
                            if decision_response.status_code != httpx.codes.OK:
                                raise _oauth_error(decision_response, "Approval")
                            redirect = _decode(ApprovalRedirect, decision_response, "approval")
                            params = parse_qs(urlsplit(redirect.redirect_to).query)
                            if params.get("state") != [state] or "code" not in params:
                                description = params.get("error_description") or params.get("error") or ["no code"]
                                msg = f"Approval was refused: {description[0]}"
                                raise T3AuthError(msg)
                    
                            token_response = await client.post(
                                metadata.token_endpoint,
                                data={
                                    "grant_type": "authorization_code",
                                    "code": params["code"][0],
                                    "redirect_uri": REDIRECT_URI,
                                    "client_id": registered.client_id,
                                    "code_verifier": verifier,
                                    "resource": resource,
                                },
                            )
                            if token_response.status_code != httpx.codes.OK:
                                raise _oauth_error(token_response, "Token exchange")
                            token = _decode(McpTokenResult, token_response, "token")
                        return T3Credentials(
                            base_url=origin,
                            environment_id=descriptor.environment_id,
                            access_token=token.access_token,
                            expires_at=datetime.now(UTC) + timedelta(seconds=token.expires_in),
                            scopes=tuple(token.scope.split()),
                            access=access,
                            client_id=registered.client_id,
                        )
                    

                    parse_approval_code

                    parse_approval_code(code: str) -> tuple[McpAccess, str] | None
                    

                    Level and canonical form of an app approval code (AUTO-…), or None for a plain code.

                    Mirrors upstream parseMcpApprovalCode: matching ignores case and surrounding space, and the canonical code is upper case.

                    Parameters:

                    Name Type Description Default
                    code str

                    A pairing code as shown by T3 Code.

                    required
                    Source code in src/pyt3client/auth.py
                    79
                    80
                    81
                    82
                    83
                    84
                    85
                    86
                    87
                    88
                    89
                    90
                    91
                    def parse_approval_code(code: str) -> tuple[McpAccess, str] | None:
                        """Level and canonical form of an app approval code (`AUTO-…`), or None for a plain code.
                    
                        Mirrors upstream `parseMcpApprovalCode`: matching ignores case and
                        surrounding space, and the canonical code is upper case.
                    
                        Args:
                            code: A pairing code as shown by T3 Code.
                        """
                        if match := _APPROVAL_CODE_PATTERN.match(code.strip()):
                            prefix = match.group(1).upper()
                            return _APPROVAL_CODE_PREFIXES[prefix], f"{prefix}-{match.group(2).upper()}"
                        return None