# Python MCP SDK

Connect the official mcp package to your tenant's MCP server, list the nineteen tools, call one, chat with a published agent and search your knowledge from Python.

The `mcp` package is the reference Model Context Protocol client for Python. Point its streamable HTTP transport at your tenant's MCP endpoint with the key in a header, open a session, and the platform's tools become ordinary awaitable calls in your own program or agent framework.

**Who can use it:** anyone holding an API key. Each tool needs the scope of the public API route it calls, listed on [Tools](/developers/libraries/mcp-server/tools).

## Prerequisites

- Python 3.10 or later and `pip install mcp`. Verified with `mcp` 2.2.0; the 1.x shape is noted below.
- Your tenant's MCP endpoint, `https://<your tenant host>/mcp`, and a key from the Developer Hub's **API keys** tab.
- For the chat tool, the id of a published agent built in Studio. `katonic_list_agents` returns the ids.

![The Connect from your client panel: the client switch with Claude Desktop, Python (MCP SDK), TypeScript (MCP SDK), OpenAI Agents and OpenCode, and the JSON snippet for Claude Desktop with the endpoint URL and a Bearer kapi_ placeholder; above it, the last rows of the built-in tool grid and the note about tools/list.](https://docs.katonic.ai/img/developers/libraries/mcp-server/connect/dev-hub-mcp-connect.png)
*Connect from your client: pick the client, select Copy on its snippet and replace the kapi_ placeholder with your key.*

## Connect

On `mcp` 2.x the key travels on an HTTP client that the SDK's own helper builds; the transport yields the read and write streams, and `ClientSession` speaks the protocol over them:

```python

from mcp import ClientSession
from mcp.client.streamable_http import create_mcp_http_client, streamable_http_client

URL = "https://<your tenant host>/mcp"
KEY = "kapi_YOUR_KEY"

async def main():
    http = create_mcp_http_client(headers={"Authorization": f"Bearer {KEY}"})
    async with streamable_http_client(URL, http_client=http) as streams:
        read, write = streams[0], streams[1]
        async with ClientSession(read, write) as session:
            init = await session.initialize()
            print(init.server_info.name, init.server_info.version)
            tools = await session.list_tools()
            print([tool.name for tool in tools.tools])

asyncio.run(main())
```

On `mcp` 1.x the helper is `streamablehttp_client(url, headers={...})`, it yields `(read, write, _)` directly, and result fields are camel case (`serverInfo`). Neither name exists on the other major version, so pin the one you write against.

## Call the tools

Every tool takes a dictionary of arguments and returns content blocks; the platform's tools answer with one text block carrying JSON.

```python

agents = await session.call_tool("katonic_list_agents", {})
data = json.loads(agents.content[0].text)
agent_id = data["agents"][0]["id"]

reply = await session.call_tool(
    "katonic_chat",
    {"agent_id": agent_id, "message": "Summarise our onboarding guide in three bullet points."},
)
turn = json.loads(reply.content[0].text)
print(turn["message"]["content"])
session_id = turn["session_id"]      # pass it back to continue the conversation

hits = await session.call_tool("katonic_knowledge_search", {"query": "onboarding", "top_k": 5})
print(json.loads(hits.content[0].text)["results"][0]["content"])
```

`katonic_chat` takes `agent_id`, `message` and an optional `session_id`; `katonic_knowledge_search` takes `query`, `top_k` and an optional `source_ids` list. A failed call sets `is_error` on the result (2.x) rather than raising.

## Verify

1. `initialize` returns the server name and version, and `list_tools` returns nineteen tools. That proves the endpoint and the protocol, not the key: the server accepts the handshake from any key that starts with `kapi_`.
2. The first `call_tool` returning content proves the key and its scope. `katonic_list_agents` needs only the agents read scope, so it is the cheapest check.
3. The key's row on the Developer Hub's **API keys** tab shows a new last-used time, and a `katonic_chat` or `katonic_completions` call appears in the Control Room's **AI Gateway** under **Logs** as a line naming the model, tier, tokens, cost and latency.

## What does not carry over

- **A server session.** The server issues no session id, so each `call_tool` stands alone; conversation memory belongs to the platform's sessions, addressed by the `session_id` the chat tool returns.
- **Streaming.** Tool results arrive whole. To stream a model's tokens, call the public API's chat completions route directly with an OpenAI client instead.
- **Agents created through the API.** An agent created with `katonic_create_agent` or the API's create route cannot yet hold a conversation on the current build; chat with agents published from Studio.
- **Response headers.** The MCP server answers JSON-RPC; nothing about rate limits reaches you as a header. A refused call comes back as a JSON-RPC error, an internal error on the current build, which the SDK raises.

## Troubleshooting

- **`ImportError: cannot import name 'streamablehttp_client'`.** You have `mcp` 2.x; use `streamable_http_client` with `create_mcp_http_client` as above. The reverse error means 1.x.
- **`'InitializeResult' object has no attribute 'serverInfo'`.** Same cause: 2.x fields are snake case, `server_info`, `input_schema`, `is_error`.
- **Handshake and `list_tools` succeed, the first `call_tool` returns an internal error.** The key is invalid, expired, revoked, or lacks the tool's scope; the server reports all four the same way on the current build. Check the key's row and scopes on the **API keys** tab.
- **`katonic_chat` fails on the first turn for a new agent.** The agent was created through the API; publish one from Studio and use its id.
- **A `TaskGroup` exception with no obvious cause.** The SDK runs the transport in an anyio task group, which wraps the real error. Walk `exc.exceptions` down to the leaf; the leaf is the message worth reading.

## Related

- [Katonic MCP Server](/developers/libraries/mcp-server)
- [Tools](/developers/libraries/mcp-server/tools)
- [TypeScript MCP SDK](/developers/integrations/mcp-typescript-sdk)
- [Integrations](/developers/integrations/overview)

Source: https://docs.katonic.ai/developers/integrations/mcp-python-sdk
