Skip to content

mcp

Class info

Classes

Name Children Inherits
CallToolResult
pyt3client.mcp
MCP `tools/call` result.
    ContentBlock
    pyt3client.mcp
    One block of a tool result. T3 Code answers with a single JSON `text` block.
      McpHttpSession
      pyt3client.mcp
      One MCP session against a T3 Code environment's `/mcp`.
        T3AuthError
        pyt3client.errors
        Signing in failed, or the server no longer accepts the credential.
          T3HttpError
          pyt3client.errors
          The server answered with an unexpected HTTP status.
            T3McpError
            pyt3client.errors
            The server answered a request with a JSON-RPC error.
              T3ProtocolError
              pyt3client.errors
              The server answered in a shape this client does not understand.
                ToolAnnotations
                pyt3client.mcp
                  ToolInfo
                  pyt3client.mcp
                  One entry of `tools/list`.
                    _JsonRpcError
                    pyt3client.mcp
                      _JsonRpcResponse
                      pyt3client.mcp

                        🛈 DocStrings

                        Minimal MCP Streamable HTTP client, just enough for T3 Code's /mcp.

                        T3 Code needs only initialize, tools/list and tools/call, with no sampling, elicitation or server-initiated requests, so this speaks that subset directly over httpx rather than pulling in a full MCP SDK. It mirrors upstream's own client for linked environments, apps/server/src/peer/PeerMcpClient.ts (https://github.com/pingdotgg/t3code):

                        • POST JSON-RPC to /mcp with accept: application/json, text/event-stream.
                        • initialize answers with an mcp-session-id header; later requests send it plus mcp-protocol-version. The server returns 400 without that header.
                        • Sessions live in server memory, so after a server restart a request gets 404. The session is then opened again and the request retried once.
                        • Requests must not carry an Origin header: /mcp answers 403 to anything that looks like a browser (apps/server/src/mcp/McpHttpServer.ts). httpx sends none by default.

                        PROTOCOL_VERSION module-attribute

                        PROTOCOL_VERSION = '2025-06-18'
                        

                        MCP revision T3 Code speaks (PROTOCOL_VERSION in upstream PeerMcpClient.ts).

                        CallToolResult

                        Bases: BaseModel

                        MCP tools/call result.

                        Source code in src/pyt3client/mcp.py
                        67
                        68
                        69
                        70
                        71
                        72
                        73
                        74
                        75
                        76
                        77
                        78
                        79
                        80
                        class CallToolResult(BaseModel):
                            """MCP `tools/call` result."""
                        
                            model_config = ConfigDict(extra="allow", populate_by_name=True)
                        
                            content: list[ContentBlock] = Field(default_factory=list)
                            structured_content: dict[str, JsonValue] | None = Field(None, alias="structuredContent")
                            """Present for tools with an `outputSchema`; the same JSON as the text block."""
                            is_error: bool = Field(False, alias="isError")
                        
                            @property
                            def text(self) -> str:
                                """All text blocks joined, as upstream reads them."""
                                return "".join(block.text or "" for block in self.content)
                        

                        structured_content class-attribute instance-attribute

                        structured_content: dict[str, JsonValue] | None = Field(None, alias='structuredContent')
                        

                        Present for tools with an outputSchema; the same JSON as the text block.

                        text property

                        text: str
                        

                        All text blocks joined, as upstream reads them.

                        ContentBlock

                        Bases: BaseModel

                        One block of a tool result. T3 Code answers with a single JSON text block.

                        Source code in src/pyt3client/mcp.py
                        58
                        59
                        60
                        61
                        62
                        63
                        64
                        class ContentBlock(BaseModel):
                            """One block of a tool result. T3 Code answers with a single JSON `text` block."""
                        
                            model_config = ConfigDict(extra="allow")
                        
                            type: str
                            text: str | None = None
                        

                        McpHttpSession

                        One MCP session against a T3 Code environment's /mcp.

                        Safe for concurrent use: requests are independent HTTP POSTs, and the session is opened once, lazily, under a lock.

                        Source code in src/pyt3client/mcp.py
                        124
                        125
                        126
                        127
                        128
                        129
                        130
                        131
                        132
                        133
                        134
                        135
                        136
                        137
                        138
                        139
                        140
                        141
                        142
                        143
                        144
                        145
                        146
                        147
                        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
                        261
                        262
                        263
                        264
                        265
                        266
                        267
                        268
                        269
                        270
                        271
                        272
                        273
                        274
                        275
                        276
                        277
                        278
                        279
                        280
                        281
                        282
                        283
                        284
                        285
                        286
                        287
                        288
                        289
                        290
                        291
                        292
                        293
                        294
                        295
                        296
                        297
                        298
                        299
                        300
                        301
                        302
                        303
                        304
                        305
                        306
                        307
                        308
                        309
                        310
                        311
                        312
                        313
                        314
                        315
                        316
                        317
                        318
                        319
                        320
                        321
                        322
                        323
                        324
                        325
                        326
                        327
                        328
                        329
                        330
                        331
                        332
                        333
                        334
                        class McpHttpSession:
                            """One MCP session against a T3 Code environment's `/mcp`.
                        
                            Safe for concurrent use: requests are independent HTTP POSTs, and the
                            session is opened once, lazily, under a lock.
                            """
                        
                            def __init__(
                                self,
                                url: str,
                                token: SecretStr,
                                *,
                                http_client: httpx.AsyncClient,
                                headers: Mapping[str, str] | None = None,
                                client_name: str = "pyt3client",
                                client_version: str = "0",
                            ) -> None:
                                """Create a session; nothing is sent until the first request.
                        
                                Args:
                                    url: Full `/mcp` endpoint URL.
                                    token: Bearer token for the endpoint.
                                    http_client: Client used for every request; owned by the caller.
                                    headers: Extra headers sent with every request (such as `t3-mode-limit`).
                                    client_name: `clientInfo.name` reported in `initialize`.
                                    client_version: `clientInfo.version` reported in `initialize`.
                                """
                                self._url = url
                                self._token = token
                                self._http = http_client
                                self._headers = dict(headers or {})
                                self._client_info = {"name": client_name, "version": client_version}
                                self._session_id: str | None = None
                                self._lock = asyncio.Lock()
                                self._ids = count(1)
                                self.server_info: dict[str, JsonValue] | None = None
                                """`serverInfo` from `initialize`, such as `{"name": "T3 Code", "version": ...}`."""
                        
                            def _request_headers(self, *, session: bool) -> dict[str, str]:
                                headers = {
                                    "accept": "application/json, text/event-stream",
                                    "authorization": f"Bearer {self._token.get_secret_value()}",
                                    **self._headers,
                                }
                                if session and self._session_id is not None:
                                    headers["mcp-session-id"] = self._session_id
                                    headers["mcp-protocol-version"] = PROTOCOL_VERSION
                                return headers
                        
                            def _check_status(self, response: httpx.Response, method: str) -> None:
                                match response.status_code:
                                    case httpx.codes.OK | httpx.codes.ACCEPTED:
                                        return
                                    case httpx.codes.UNAUTHORIZED:
                                        msg = (
                                            f"{method}: the environment no longer accepts this credential. It may have"
                                            " been revoked under Settings -> Sharing & access or expired; pair again."
                                        )
                                        raise T3AuthError(msg)
                                    case status:
                                        msg = f"{method} was refused"
                                        raise T3HttpError(msg, status=status, body=response.text)
                        
                            async def _open(self) -> str:
                                response = await self._http.post(
                                    self._url,
                                    json={
                                        "jsonrpc": "2.0",
                                        "id": 0,
                                        "method": "initialize",
                                        "params": {
                                            "protocolVersion": PROTOCOL_VERSION,
                                            "capabilities": {},
                                            "clientInfo": self._client_info,
                                        },
                                    },
                                    headers=self._request_headers(session=False),
                                )
                                self._check_status(response, "initialize")
                                session_id = response.headers.get("mcp-session-id")
                                if session_id is None:
                                    msg = "initialize: the server did not start an MCP session"
                                    raise T3ProtocolError(msg)
                                result = self._result("initialize", response, 0)
                                server_info = result.get("serverInfo")
                                self.server_info = server_info if isinstance(server_info, dict) else None
                                self._session_id = session_id
                                notified = await self._http.post(
                                    self._url,
                                    json={"jsonrpc": "2.0", "method": "notifications/initialized"},
                                    headers=self._request_headers(session=True),
                                )
                                self._check_status(notified, "notifications/initialized")
                                logger.debug("Opened MCP session %s on %s", session_id, self._url)
                                return session_id
                        
                            async def _ensure_session(self, stale: str | None = None) -> None:
                                async with self._lock:
                                    # Another task may already have replaced the stale session.
                                    if self._session_id is None or self._session_id == stale:
                                        self._session_id = None
                                        await self._open()
                        
                            def _result(
                                self, method: str, response: httpx.Response, request_id: int
                            ) -> dict[str, JsonValue]:
                                try:
                                    messages = _parse_messages(response)
                                except (ValidationError, ValueError) as error:
                                    msg = f"{method}: unreadable response: {error}"
                                    raise T3ProtocolError(msg) from error
                                message = next((m for m in messages if m.id == request_id), None)
                                if message is None:
                                    msg = f"{method}: the server sent no response for request {request_id}"
                                    raise T3ProtocolError(msg)
                                if message.error is not None:
                                    raise T3McpError(method, message.error.code, message.error.message)
                                if message.result is None:
                                    msg = f"{method}: the server returned neither a result nor an error"
                                    raise T3ProtocolError(msg)
                                return message.result
                        
                            async def request(
                                self,
                                method: str,
                                params: Mapping[str, JsonValue] | None = None,
                                *,
                                timeout: float | None = None,
                            ) -> dict[str, JsonValue]:
                                """Send one JSON-RPC request and return its `result`.
                        
                                Args:
                                    method: JSON-RPC method, such as `tools/call`.
                                    params: Request params.
                                    timeout: Read timeout in seconds for this request; the client's default otherwise.
                        
                                Raises:
                                    T3AuthError: The token was rejected (HTTP 401).
                                    T3McpError: The server answered with a JSON-RPC error.
                                    T3HttpError: Any other unexpected HTTP status.
                                    T3ProtocolError: The response could not be read.
                                """
                                await self._ensure_session()
                                for attempt in range(2):
                                    session_id = self._session_id
                                    request_id = next(self._ids)
                                    response = await self._http.post(
                                        self._url,
                                        json={
                                            "jsonrpc": "2.0",
                                            "id": request_id,
                                            "method": method,
                                            "params": dict(params or {}),
                                        },
                                        headers=self._request_headers(session=True),
                                        timeout=httpx.USE_CLIENT_DEFAULT if timeout is None else timeout,
                                    )
                                    if response.status_code == httpx.codes.NOT_FOUND and attempt == 0:
                                        logger.debug("MCP session %s is gone (server restart?); reopening", session_id)
                                        await self._ensure_session(stale=session_id)
                                        continue
                                    self._check_status(response, method)
                                    return self._result(method, response, request_id)
                                msg = f"{method}: the server dropped the MCP session twice"
                                raise T3ProtocolError(msg)
                        
                            async def list_tools(self) -> list[ToolInfo]:
                                """All tools the server offers this credential, following pagination."""
                                tools: list[ToolInfo] = []
                                cursor: str | None = None
                                while True:
                                    result = await self.request("tools/list", {} if cursor is None else {"cursor": cursor})
                                    try:
                                        tools.extend(
                                            ToolInfo.model_validate(tool) for tool in _as_list(result.get("tools"))
                                        )
                                    except ValidationError as error:
                                        msg = f"tools/list: unexpected tool shape: {error}"
                                        raise T3ProtocolError(msg) from error
                                    next_cursor = result.get("nextCursor")
                                    if not isinstance(next_cursor, str) or not next_cursor:
                                        return tools
                                    cursor = next_cursor
                        
                            async def call_tool(
                                self,
                                name: str,
                                arguments: Mapping[str, JsonValue],
                                *,
                                timeout: float | None = None,
                            ) -> CallToolResult:
                                """Call a tool and return the raw MCP result (refusals are not raised here)."""
                                result = await self.request(
                                    "tools/call", {"name": name, "arguments": dict(arguments)}, timeout=timeout
                                )
                                try:
                                    return CallToolResult.model_validate(result)
                                except ValidationError as error:
                                    msg = f"tools/call {name}: unexpected result shape: {error}"
                                    raise T3ProtocolError(msg) from error
                        
                            async def close(self) -> None:
                                """End the session on the server (best effort)."""
                                if self._session_id is None:
                                    return
                                try:
                                    await self._http.delete(self._url, headers=self._request_headers(session=True))
                                except httpx.HTTPError as error:
                                    logger.debug("Closing MCP session failed: %s", error)
                                finally:
                                    self._session_id = None
                        

                        server_info instance-attribute

                        server_info: dict[str, JsonValue] | None = None
                        

                        serverInfo from initialize, such as {"name": "T3 Code", "version": ...}.

                        __init__

                        __init__(
                            url: str,
                            token: SecretStr,
                            *,
                            http_client: AsyncClient,
                            headers: Mapping[str, str] | None = None,
                            client_name: str = "pyt3client",
                            client_version: str = "0"
                        ) -> None
                        

                        Create a session; nothing is sent until the first request.

                        Parameters:

                        Name Type Description Default
                        url str

                        Full /mcp endpoint URL.

                        required
                        token SecretStr

                        Bearer token for the endpoint.

                        required
                        http_client AsyncClient

                        Client used for every request; owned by the caller.

                        required
                        headers Mapping[str, str] | None

                        Extra headers sent with every request (such as t3-mode-limit).

                        None
                        client_name str

                        clientInfo.name reported in initialize.

                        'pyt3client'
                        client_version str

                        clientInfo.version reported in initialize.

                        '0'
                        Source code in src/pyt3client/mcp.py
                        131
                        132
                        133
                        134
                        135
                        136
                        137
                        138
                        139
                        140
                        141
                        142
                        143
                        144
                        145
                        146
                        147
                        148
                        149
                        150
                        151
                        152
                        153
                        154
                        155
                        156
                        157
                        158
                        159
                        160
                        def __init__(
                            self,
                            url: str,
                            token: SecretStr,
                            *,
                            http_client: httpx.AsyncClient,
                            headers: Mapping[str, str] | None = None,
                            client_name: str = "pyt3client",
                            client_version: str = "0",
                        ) -> None:
                            """Create a session; nothing is sent until the first request.
                        
                            Args:
                                url: Full `/mcp` endpoint URL.
                                token: Bearer token for the endpoint.
                                http_client: Client used for every request; owned by the caller.
                                headers: Extra headers sent with every request (such as `t3-mode-limit`).
                                client_name: `clientInfo.name` reported in `initialize`.
                                client_version: `clientInfo.version` reported in `initialize`.
                            """
                            self._url = url
                            self._token = token
                            self._http = http_client
                            self._headers = dict(headers or {})
                            self._client_info = {"name": client_name, "version": client_version}
                            self._session_id: str | None = None
                            self._lock = asyncio.Lock()
                            self._ids = count(1)
                            self.server_info: dict[str, JsonValue] | None = None
                            """`serverInfo` from `initialize`, such as `{"name": "T3 Code", "version": ...}`."""
                        

                        call_tool async

                        call_tool(
                            name: str, arguments: Mapping[str, JsonValue], *, timeout: float | None = None
                        ) -> CallToolResult
                        

                        Call a tool and return the raw MCP result (refusals are not raised here).

                        Source code in src/pyt3client/mcp.py
                        308
                        309
                        310
                        311
                        312
                        313
                        314
                        315
                        316
                        317
                        318
                        319
                        320
                        321
                        322
                        323
                        async def call_tool(
                            self,
                            name: str,
                            arguments: Mapping[str, JsonValue],
                            *,
                            timeout: float | None = None,
                        ) -> CallToolResult:
                            """Call a tool and return the raw MCP result (refusals are not raised here)."""
                            result = await self.request(
                                "tools/call", {"name": name, "arguments": dict(arguments)}, timeout=timeout
                            )
                            try:
                                return CallToolResult.model_validate(result)
                            except ValidationError as error:
                                msg = f"tools/call {name}: unexpected result shape: {error}"
                                raise T3ProtocolError(msg) from error
                        

                        close async

                        close() -> None
                        

                        End the session on the server (best effort).

                        Source code in src/pyt3client/mcp.py
                        325
                        326
                        327
                        328
                        329
                        330
                        331
                        332
                        333
                        334
                        async def close(self) -> None:
                            """End the session on the server (best effort)."""
                            if self._session_id is None:
                                return
                            try:
                                await self._http.delete(self._url, headers=self._request_headers(session=True))
                            except httpx.HTTPError as error:
                                logger.debug("Closing MCP session failed: %s", error)
                            finally:
                                self._session_id = None
                        

                        list_tools async

                        list_tools() -> list[ToolInfo]
                        

                        All tools the server offers this credential, following pagination.

                        Source code in src/pyt3client/mcp.py
                        290
                        291
                        292
                        293
                        294
                        295
                        296
                        297
                        298
                        299
                        300
                        301
                        302
                        303
                        304
                        305
                        306
                        async def list_tools(self) -> list[ToolInfo]:
                            """All tools the server offers this credential, following pagination."""
                            tools: list[ToolInfo] = []
                            cursor: str | None = None
                            while True:
                                result = await self.request("tools/list", {} if cursor is None else {"cursor": cursor})
                                try:
                                    tools.extend(
                                        ToolInfo.model_validate(tool) for tool in _as_list(result.get("tools"))
                                    )
                                except ValidationError as error:
                                    msg = f"tools/list: unexpected tool shape: {error}"
                                    raise T3ProtocolError(msg) from error
                                next_cursor = result.get("nextCursor")
                                if not isinstance(next_cursor, str) or not next_cursor:
                                    return tools
                                cursor = next_cursor
                        

                        request async

                        request(
                            method: str, params: Mapping[str, JsonValue] | None = None, *, timeout: float | None = None
                        ) -> dict[str, JsonValue]
                        

                        Send one JSON-RPC request and return its result.

                        Parameters:

                        Name Type Description Default
                        method str

                        JSON-RPC method, such as tools/call.

                        required
                        params Mapping[str, JsonValue] | None

                        Request params.

                        None
                        timeout float | None

                        Read timeout in seconds for this request; the client's default otherwise.

                        None

                        Raises:

                        Type Description
                        T3AuthError

                        The token was rejected (HTTP 401).

                        T3McpError

                        The server answered with a JSON-RPC error.

                        T3HttpError

                        Any other unexpected HTTP status.

                        T3ProtocolError

                        The response could not be read.

                        Source code in src/pyt3client/mcp.py
                        246
                        247
                        248
                        249
                        250
                        251
                        252
                        253
                        254
                        255
                        256
                        257
                        258
                        259
                        260
                        261
                        262
                        263
                        264
                        265
                        266
                        267
                        268
                        269
                        270
                        271
                        272
                        273
                        274
                        275
                        276
                        277
                        278
                        279
                        280
                        281
                        282
                        283
                        284
                        285
                        286
                        287
                        288
                        async def request(
                            self,
                            method: str,
                            params: Mapping[str, JsonValue] | None = None,
                            *,
                            timeout: float | None = None,
                        ) -> dict[str, JsonValue]:
                            """Send one JSON-RPC request and return its `result`.
                        
                            Args:
                                method: JSON-RPC method, such as `tools/call`.
                                params: Request params.
                                timeout: Read timeout in seconds for this request; the client's default otherwise.
                        
                            Raises:
                                T3AuthError: The token was rejected (HTTP 401).
                                T3McpError: The server answered with a JSON-RPC error.
                                T3HttpError: Any other unexpected HTTP status.
                                T3ProtocolError: The response could not be read.
                            """
                            await self._ensure_session()
                            for attempt in range(2):
                                session_id = self._session_id
                                request_id = next(self._ids)
                                response = await self._http.post(
                                    self._url,
                                    json={
                                        "jsonrpc": "2.0",
                                        "id": request_id,
                                        "method": method,
                                        "params": dict(params or {}),
                                    },
                                    headers=self._request_headers(session=True),
                                    timeout=httpx.USE_CLIENT_DEFAULT if timeout is None else timeout,
                                )
                                if response.status_code == httpx.codes.NOT_FOUND and attempt == 0:
                                    logger.debug("MCP session %s is gone (server restart?); reopening", session_id)
                                    await self._ensure_session(stale=session_id)
                                    continue
                                self._check_status(response, method)
                                return self._result(method, response, request_id)
                            msg = f"{method}: the server dropped the MCP session twice"
                            raise T3ProtocolError(msg)
                        

                        ToolInfo

                        Bases: BaseModel

                        One entry of tools/list.

                        Source code in src/pyt3client/mcp.py
                         92
                         93
                         94
                         95
                         96
                         97
                         98
                         99
                        100
                        101
                        102
                        class ToolInfo(BaseModel):
                            """One entry of `tools/list`."""
                        
                            model_config = ConfigDict(extra="allow", populate_by_name=True)
                        
                            name: str
                            title: str | None = None
                            description: str | None = None
                            input_schema: dict[str, JsonValue] = Field(alias="inputSchema")
                            output_schema: dict[str, JsonValue] | None = Field(None, alias="outputSchema")
                            annotations: ToolAnnotations | None = None