# MCP Python SDK

> Call paid MCP tools through Nexus402 from MCP Python SDK: one URL, one header, and the framework's own MCP client. Nothing of ours to install.

Source: https://www.nexus402.dev/docs/developers/frameworks/python-mcp/

The MCP Python SDK is the official Python client for the Model Context Protocol. Use it when you are writing your own agent loop in Python and want to call tools directly, with no framework in between.

The example connects to `https://api.nexus402.dev/v1/mcp` over streamable HTTP, sends your key in the `X-Nexus-Api-Key` header, lists the tools the key may call, and calls the one you name in `NEXUS402_TOOL`. **A call to a paid tool is charged to your wallet.** If you name none, nothing is called. It is run against a test gateway at `mcp` 1.30.0, so a release that changes how headers are passed is caught before you meet it.

> **Careful**
>
> Keep the key in the
>
> NEXUS402_API_KEY
>
> environment variable, never in code or a committed file. Give each agent its own key with a 24-hour spend cap and, if it chooses tools on its own, a maximum price per call. See
>
> how to give an agent a budget
>
> .

## Install and run

Python. Give the SDK an httpx.AsyncClient that carries the header.

```
pip install -r requirements.txt
export NEXUS402_API_KEY=nx_dev_...
# The tool to call, by its name in the marketplace. A paid tool is charged.
export NEXUS402_TOOL='<tool name>'
python main.py
```

## The example

```
"""Call a Nexus402 tool with the official MCP Python SDK (ADR-0236).

The key comes from NEXUS402_API_KEY and travels in the X-Nexus-Api-Key
header. It is never written in code. NEXUS402_TOOL names the tool to call
(required: a call is charged) and NEXUS402_ARGS its JSON arguments.
"""

import asyncio
import json
import os
import sys

import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client

URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp")
TOOL = os.environ.get("NEXUS402_TOOL", "")


def refusal(error: BaseException) -> httpx.HTTPStatusError | None:
    """The HTTP refusal inside an error, however deeply the SDK grouped it."""
    if isinstance(error, httpx.HTTPStatusError):
        return error
    if isinstance(error, BaseExceptionGroup):
        for inner in error.exceptions:
            found = refusal(inner)
            if found is not None:
                return found
    return None


async def main() -> int:
    # The SDK raises an HTTP refusal (a 402 when the wallet cannot pay) from
    # its transport's task group, so it surfaces here, as an ExceptionGroup,
    # rather than from call_tool.
    try:
        return await call()
    except Exception as error:
        refused = refusal(error)
        if refused is None:
            raise
        print(f"call refused: HTTP {refused.response.status_code}")
        return 2


async def call() -> int:
    headers = {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]}
    async with httpx.AsyncClient(headers=headers, timeout=60) as http:
        async with streamable_http_client(URL, http_client=http) as (read, write, _):
            async with ClientSession(read, write) as session:
                await session.initialize()
                tools = (await session.list_tools()).tools
                print(f"{len(tools)} tools listed")
                args = json.loads(os.environ.get("NEXUS402_ARGS", "{}"))
                try:
                    result = await session.call_tool(TOOL, args)
                except Exception as error:  # a 402 or another refusal
                    print(f"call refused: {error}")
                    return 2
                if result.isError:
                    print(f"call refused: {result.content}")
                    return 2
                for block in result.content:
                    print(getattr(block, "text", block))
    return 0


if __name__ == "__main__":
    # Never a default: a call is charged, and you choose who is paid.
    if not TOOL:
        sys.exit(
            "Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. "
            "A call to a paid tool is charged to your wallet."
        )
    sys.exit(asyncio.run(main()))
```

## When a call is refused

A call your wallet or your key's cap cannot cover is refused with HTTP `402` before anything is charged, and the example prints `call refused` and exits with code 2. A call that fails before any output reaches your agent is not charged either. Every refusal code is in [the error reference](https://www.nexus402.dev/docs/developers/errors/).

## Next

- [All four framework examples](https://www.nexus402.dev/docs/developers/frameworks/), side by side.
- [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/), for a key per agent.
- [The marketplace](https://www.nexus402.dev/marketplace/), for the tools your agent can call.
