pyt3client 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyt3client/__init__.py ADDED
@@ -0,0 +1,60 @@
1
+ """pyt3client: thin, typed Python client for T3 Code environments.
2
+
3
+ T3 Code (https://github.com/pingdotgg/t3code) runs coding agents (Claude Code,
4
+ Codex, Cursor, OpenCode, ACP agents, ...) on a machine and exposes them to its
5
+ clients. This package talks to an environment through its MCP endpoint
6
+ (`/mcp`), the interface T3 Code offers to outside agents and scripts.
7
+
8
+ ```python
9
+ from pyt3client import T3Client, pair
10
+ from pyt3client.models.tools import THREAD_LIST, ThreadListInput
11
+
12
+ credentials = await pair("http://127.0.0.1:3773", "PAIRING-CODE")
13
+ async with T3Client.from_credentials(credentials) as t3:
14
+ threads = await t3.call(THREAD_LIST, ThreadListInput(all_projects=True))
15
+ ```
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from importlib.metadata import version
21
+
22
+ from pyt3client.auth import fetch_descriptor, pair
23
+ from pyt3client.client import T3Client
24
+ from pyt3client.errors import (
25
+ T3AuthError,
26
+ T3Error,
27
+ T3HttpError,
28
+ T3McpError,
29
+ T3ProtocolError,
30
+ T3ToolError,
31
+ )
32
+ from pyt3client.models.auth import T3Credentials
33
+ from pyt3client.models.environment import EnvironmentDescriptor
34
+ from pyt3client.tool import JsonOutput, ToolSpec
35
+
36
+ __version__ = version("pyt3client")
37
+ __title__ = "pyt3client"
38
+
39
+ __author__ = "Philipp Temminghoff"
40
+ __author_email__ = "philipptemminghoff@googlemail.com"
41
+ __copyright__ = "Copyright (c) 2026 Philipp Temminghoff"
42
+ __license__ = "MIT"
43
+ __url__ = "https://github.com/phil65/pyt3client"
44
+
45
+ __all__ = [
46
+ "EnvironmentDescriptor",
47
+ "JsonOutput",
48
+ "T3AuthError",
49
+ "T3Client",
50
+ "T3Credentials",
51
+ "T3Error",
52
+ "T3HttpError",
53
+ "T3McpError",
54
+ "T3ProtocolError",
55
+ "T3ToolError",
56
+ "ToolSpec",
57
+ "__version__",
58
+ "fetch_descriptor",
59
+ "pair",
60
+ ]
pyt3client/auth.py ADDED
@@ -0,0 +1,270 @@
1
+ """Sign in to a T3 Code environment's `/mcp` endpoint without a browser.
2
+
3
+ T3 Code lets outside agents use its MCP server through OAuth 2.1
4
+ (authorization code + PKCE, dynamic client registration). Interactive clients
5
+ send the user to an approval page; this module does what the page does, with a
6
+ pairing code instead of a click. It is the same flow T3 Code itself uses to
7
+ link one environment to another: upstream `PeerLinks.signIn` in
8
+ apps/server/src/peer/PeerLinks.ts.
9
+
10
+ The flow:
11
+
12
+ 1. `GET /.well-known/t3/environment` public descriptor (environment id).
13
+ 2. `POST /oauth/mcp/register` register a public client (stateless).
14
+ 3. `POST /oauth/mcp/decision` approve with the pairing code; the answer
15
+ is the redirect URL carrying `code`.
16
+ 4. `POST /oauth/mcp/token` exchange code + PKCE verifier for a token.
17
+
18
+ Server side: apps/server/src/auth/mcpOAuthHttp.ts (routes) and
19
+ apps/server/src/auth/McpOAuth.ts (validation, `approve`, `exchangeCode`).
20
+ Get a pairing code on the host with `t3 auth pairing create`, or in the app via
21
+ Settings -> Sharing & access.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import base64
27
+ from contextlib import asynccontextmanager
28
+ from datetime import UTC, datetime, timedelta
29
+ import hashlib
30
+ import re
31
+ import secrets
32
+ from typing import TYPE_CHECKING, get_args
33
+ from urllib.parse import parse_qs, urlsplit
34
+
35
+ import httpx
36
+ from pydantic import ValidationError
37
+
38
+ from pyt3client.errors import T3AuthError, T3HttpError, T3ProtocolError
39
+ from pyt3client.models.auth import (
40
+ ApprovalRedirect,
41
+ McpAccess,
42
+ McpTokenResult,
43
+ OAuthAuthorizationServerMetadata,
44
+ RegisteredClient,
45
+ T3Credentials,
46
+ )
47
+ from pyt3client.models.environment import EnvironmentDescriptor
48
+
49
+
50
+ if TYPE_CHECKING:
51
+ from collections.abc import AsyncGenerator
52
+
53
+ from pydantic import BaseModel
54
+
55
+
56
+ DEFAULT_CLIENT_NAME = "pyt3client"
57
+ # Loopback redirects are accepted for any port (RFC 8252), and nothing has to
58
+ # listen here: `/oauth/mcp/decision` returns the redirect URL in its response
59
+ # body instead of redirecting a browser. Upstream uses the same trick with
60
+ # `http://127.0.0.1/t3code-peer-link`.
61
+ REDIRECT_URI = "http://127.0.0.1/pyt3client"
62
+
63
+ # Approval codes such as `AUTO-Q8RZ3NWD5KTC` carry their own level; the server
64
+ # applies that level whatever the request asks for. Upstream: `mcpApprovalCode`
65
+ # and `parseMcpApprovalCode` in packages/contracts/src/auth.ts.
66
+ _APPROVAL_CODE_PREFIXES: dict[str, McpAccess] = {
67
+ "READ": "read-only",
68
+ "SUPERVISED": "approval-required",
69
+ "EDITS": "auto-accept-edits",
70
+ "AUTO": "auto",
71
+ "FULL": "full-access",
72
+ }
73
+ _PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
74
+ _APPROVAL_CODE_PATTERN = re.compile(
75
+ rf"^({'|'.join(_APPROVAL_CODE_PREFIXES)})-([{_PAIRING_CODE_ALPHABET}]{{12}})$", re.IGNORECASE
76
+ )
77
+
78
+
79
+ def parse_approval_code(code: str) -> tuple[McpAccess, str] | None:
80
+ """Level and canonical form of an app approval code (`AUTO-…`), or None for a plain code.
81
+
82
+ Mirrors upstream `parseMcpApprovalCode`: matching ignores case and
83
+ surrounding space, and the canonical code is upper case.
84
+
85
+ Args:
86
+ code: A pairing code as shown by T3 Code.
87
+ """
88
+ if match := _APPROVAL_CODE_PATTERN.match(code.strip()):
89
+ prefix = match.group(1).upper()
90
+ return _APPROVAL_CODE_PREFIXES[prefix], f"{prefix}-{match.group(2).upper()}"
91
+ return None
92
+
93
+
94
+ def _base64url(data: bytes) -> str:
95
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
96
+
97
+
98
+ def _decode[ModelT: BaseModel](model: type[ModelT], response: httpx.Response, what: str) -> ModelT:
99
+ try:
100
+ return model.model_validate_json(response.content)
101
+ except ValidationError as error:
102
+ msg = f"Unexpected {what} response from {response.url}: {error}"
103
+ raise T3ProtocolError(msg) from error
104
+
105
+
106
+ def _oauth_error(response: httpx.Response, what: str) -> T3AuthError:
107
+ """Turn an OAuth or approval error body into a readable exception.
108
+
109
+ `/oauth/mcp/register` and `/oauth/mcp/token` answer RFC 6749 style
110
+ `{"error", "error_description"}`; `/oauth/mcp/decision` answers
111
+ `{"_tag": "AuthMcpApprovalError", "message"}`.
112
+ """
113
+ detail = response.text
114
+ try:
115
+ body = response.json()
116
+ except ValueError:
117
+ body = None
118
+ if isinstance(body, dict):
119
+ description = body.get("error_description") or body.get("message") or body.get("error")
120
+ if isinstance(description, str):
121
+ detail = description
122
+ return T3AuthError(f"{what} failed (HTTP {response.status_code}): {detail}")
123
+
124
+
125
+ def _normalize_base_url(base_url: str) -> str:
126
+ url = base_url.rstrip("/")
127
+ return url.removesuffix("/mcp")
128
+
129
+
130
+ async def fetch_descriptor(
131
+ base_url: str, *, http_client: httpx.AsyncClient | None = None
132
+ ) -> EnvironmentDescriptor:
133
+ """Read an environment's public descriptor; needs no credential.
134
+
135
+ Args:
136
+ base_url: Environment origin, such as `http://127.0.0.1:3773`.
137
+ http_client: Client to reuse; a short-lived one is created otherwise.
138
+ """
139
+ url = f"{_normalize_base_url(base_url)}/.well-known/t3/environment"
140
+ async with _client_scope(http_client) as client:
141
+ response = await client.get(url)
142
+ if response.status_code != httpx.codes.OK:
143
+ msg = f"{url} is not a T3 Code environment"
144
+ raise T3HttpError(msg, status=response.status_code, body=response.text)
145
+ return _decode(EnvironmentDescriptor, response, "environment descriptor")
146
+
147
+
148
+ async def pair(
149
+ base_url: str,
150
+ pairing_code: str,
151
+ *,
152
+ access: McpAccess = "auto",
153
+ client_name: str = DEFAULT_CLIENT_NAME,
154
+ http_client: httpx.AsyncClient | None = None,
155
+ ) -> T3Credentials:
156
+ """Sign in to an environment's `/mcp` with a one-time pairing code.
157
+
158
+ The code is spent by this call. The resulting session shows up in T3 Code
159
+ under Settings -> Sharing & access with `client_name` as its label, lasts
160
+ 30 days, and does not renew.
161
+
162
+ Agents only send credentials over `https` or to `localhost`, so use a
163
+ loopback, Tailscale HTTPS or T3 Connect address. A plain-http LAN address
164
+ works technically but sends the code unencrypted.
165
+
166
+ Args:
167
+ base_url: Environment origin, such as `http://127.0.0.1:3773`. A trailing
168
+ `/mcp` (as shown by "Copy MCP URL") is accepted.
169
+ pairing_code: Code from `t3 auth pairing create` or the app. An app
170
+ approval code (`AUTO-…`) fixes the level itself and overrides `access`;
171
+ it is matched case-insensitively and sent in canonical upper case.
172
+ access: Level to approve the client at. Must not exceed what the code grants.
173
+ client_name: Label the environment shows for this client.
174
+ http_client: Client to reuse; a short-lived one is created otherwise.
175
+
176
+ Raises:
177
+ T3AuthError: The environment rejected the code or the sign-in.
178
+ T3HttpError: The address does not answer like a T3 Code environment.
179
+ """
180
+ origin = _normalize_base_url(base_url)
181
+ code = pairing_code.strip()
182
+ if approval := parse_approval_code(code):
183
+ access, code = approval
184
+ if access not in get_args(McpAccess.__value__):
185
+ msg = f"Unknown access level {access!r}"
186
+ raise ValueError(msg)
187
+ async with _client_scope(http_client) as client:
188
+ descriptor = await fetch_descriptor(origin, http_client=client)
189
+ metadata_response = await client.get(f"{origin}/.well-known/oauth-authorization-server")
190
+ if metadata_response.status_code != httpx.codes.OK:
191
+ msg = "Environment does not offer MCP sign-in"
192
+ raise T3HttpError(
193
+ msg, status=metadata_response.status_code, body=metadata_response.text
194
+ )
195
+ metadata = _decode(
196
+ OAuthAuthorizationServerMetadata, metadata_response, "authorization server metadata"
197
+ )
198
+
199
+ registered_response = await client.post(
200
+ metadata.registration_endpoint,
201
+ json={"client_name": client_name, "redirect_uris": [REDIRECT_URI]},
202
+ )
203
+ if registered_response.status_code not in {httpx.codes.OK, httpx.codes.CREATED}:
204
+ raise _oauth_error(registered_response, "Client registration")
205
+ registered = _decode(RegisteredClient, registered_response, "client registration")
206
+
207
+ verifier = _base64url(secrets.token_bytes(32))
208
+ challenge = _base64url(hashlib.sha256(verifier.encode("ascii")).digest())
209
+ state = _base64url(secrets.token_bytes(16))
210
+ # `resource` must name this server's `/mcp` (RFC 8707); the server derives
211
+ # its own from Host and X-Forwarded-Proto, so a rewriting proxy breaks this.
212
+ resource = f"{origin}/mcp"
213
+ authorization = {
214
+ "response_type": "code",
215
+ "client_id": registered.client_id,
216
+ "redirect_uri": REDIRECT_URI,
217
+ "code_challenge": challenge,
218
+ "code_challenge_method": "S256",
219
+ "state": state,
220
+ "resource": resource,
221
+ }
222
+ decision_response = await client.post(
223
+ f"{origin}/oauth/mcp/decision",
224
+ json={
225
+ "authorization": authorization,
226
+ "decision": {"_tag": "pairing-code", "access": access, "code": code},
227
+ },
228
+ )
229
+ if decision_response.status_code != httpx.codes.OK:
230
+ raise _oauth_error(decision_response, "Approval")
231
+ redirect = _decode(ApprovalRedirect, decision_response, "approval")
232
+ params = parse_qs(urlsplit(redirect.redirect_to).query)
233
+ if params.get("state") != [state] or "code" not in params:
234
+ description = params.get("error_description") or params.get("error") or ["no code"]
235
+ msg = f"Approval was refused: {description[0]}"
236
+ raise T3AuthError(msg)
237
+
238
+ token_response = await client.post(
239
+ metadata.token_endpoint,
240
+ data={
241
+ "grant_type": "authorization_code",
242
+ "code": params["code"][0],
243
+ "redirect_uri": REDIRECT_URI,
244
+ "client_id": registered.client_id,
245
+ "code_verifier": verifier,
246
+ "resource": resource,
247
+ },
248
+ )
249
+ if token_response.status_code != httpx.codes.OK:
250
+ raise _oauth_error(token_response, "Token exchange")
251
+ token = _decode(McpTokenResult, token_response, "token")
252
+ return T3Credentials(
253
+ base_url=origin,
254
+ environment_id=descriptor.environment_id,
255
+ access_token=token.access_token,
256
+ expires_at=datetime.now(UTC) + timedelta(seconds=token.expires_in),
257
+ scopes=tuple(token.scope.split()),
258
+ access=access,
259
+ client_id=registered.client_id,
260
+ )
261
+
262
+
263
+ @asynccontextmanager
264
+ async def _client_scope(client: httpx.AsyncClient | None) -> AsyncGenerator[httpx.AsyncClient]:
265
+ """Use a caller's httpx client, or own a short-lived one for the duration."""
266
+ if client is not None:
267
+ yield client
268
+ return
269
+ async with httpx.AsyncClient(timeout=30) as owned:
270
+ yield owned
@@ -0,0 +1,10 @@
1
+ """The `pyt3` command line tool (`pip install pyt3client[cli]`).
2
+
3
+ Kept out of `pyt3client`'s own imports so the library never needs typer.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pyt3client.cli.app import app
9
+
10
+ __all__ = ["app"]