Metadata-Version: 2.4
Name: mantyx-sdk
Version: 0.3.0
Summary: Official Python SDK for the MANTYX agent runtime. Define ephemeral agents, mix server-side MANTYX tools with locally-executed tools, run them remotely.
Project-URL: Homepage, https://mantyx.com
Project-URL: Source, https://github.com/mantyx-io/mantyx-sdk
Project-URL: Documentation, https://mantyx-io.github.io/mantyx-sdk/
Project-URL: Changelog, https://github.com/mantyx-io/mantyx-sdk/blob/main/python/CHANGELOG.md
Project-URL: Issues, https://github.com/mantyx-io/mantyx-sdk/issues
Author-email: MANTYX <support@mantyx.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for describing the origin of the Work and
              reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 MANTYX
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: agent,agentic,ai,llm,mantyx,sdk,tool-use
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: anyio>=4.5
Requires-Dist: httpx<1,>=0.27
Requires-Dist: mcp<2,>=1.27
Requires-Dist: pydantic<3,>=2.6
Requires-Dist: typing-extensions>=4.5; python_version < '3.12'
Provides-Extra: a2a-server
Requires-Dist: a2a-sdk[http-server]<2,>=1.0; extra == 'a2a-server'
Requires-Dist: uvicorn>=0.30; extra == 'a2a-server'
Provides-Extra: dev
Requires-Dist: a2a-sdk[http-server]<2,>=1.0; extra == 'dev'
Requires-Dist: anyio>=4.0; extra == 'dev'
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: uvicorn>=0.30; extra == 'dev'
Description-Content-Type: text/markdown

# mantyx-sdk

The official Python SDK for the [MANTYX](https://mantyx.com) agent runtime. Define ephemeral agents that mix server-side MANTYX tools with locally-executed tools, run them remotely, and stream events back into your process.

- LLM loop runs on MANTYX (BYOK or platform-hosted models).
- Server-side tools (`mantyx`, `mantyx_plugin`, `mantyx_a2a`, `mantyx_mcp`) execute inside MANTYX.
- Client-resolved tools (`define_local_tool`, `define_local_a2a`, `define_local_mcp`) execute inside *your* Python process; the SDK shuttles inputs and outputs over an SSE stream + a tool-result POST.
- Tune the LLM's thinking budget per run with `reasoning_level` (`"off" | "low" | "medium" | "high"` or an int 0..100).
- Sync **and** async clients (`MantyxClient`, `AsyncMantyxClient`), both backed by [`httpx`](https://www.python-httpx.org/).
- One-shot runs and multi-turn sessions, both with persisted observability.
- Authenticated with a single workspace API key.

For background, see the [agent-runs protocol spec](./docs/agent-runs-protocol.md) (a copy ships with the package).

## Install

```bash
pip install mantyx-sdk
# or: uv add mantyx-sdk
# or: poetry add mantyx-sdk
```

Requires Python 3.10+ and runs on macOS, Linux, and Windows. The runtime dependencies are [`httpx`](https://www.python-httpx.org/), [`pydantic`](https://docs.pydantic.dev/) v2, the official [`mcp`](https://pypi.org/project/mcp/) package (used internally by `define_local_mcp`), and [`anyio`](https://anyio.readthedocs.io/) (sync/async bridge for the MCP client).

## Quickstart

```python
import os
from pathlib import Path

from pydantic import BaseModel
from mantyx import MantyxClient, define_local_tool, mantyx_tool


class ReadFileArgs(BaseModel):
    path: str


client = MantyxClient(
    api_key=os.environ["MANTYX_API_KEY"],
    workspace_slug=os.environ["MANTYX_WORKSPACE_SLUG"],
    # base_url="https://app.mantyx.io",  # override for self-hosted
)

result = client.run_agent(
    system_prompt="You are a helpful assistant.",
    prompt="Read /etc/hostname and summarise what it says.",
    tools=[
        # Local tool — defined and executed in this process.
        define_local_tool(
            name="read_file",
            description="Read a file from the local filesystem.",
            parameters=ReadFileArgs,
            execute=lambda args: Path(args.path).read_text(),
        ),
        # Reference to an existing MANTYX workspace tool.
        mantyx_tool("tool_cm6abc123"),
    ],
)

print(result.text)
```

The SDK opens an SSE stream to MANTYX, listens for `local_tool_call` events, runs the matching local handler, and POSTs the result back. The server keeps running the agent loop until it produces a final reply.

## Async client

```python
import asyncio

from mantyx import AsyncMantyxClient


async def main() -> None:
    async with AsyncMantyxClient(
        api_key="...",
        workspace_slug="acme-corp",
    ) as client:
        result = await client.run_agent(
            system_prompt="You are a helpful assistant.",
            prompt="Hi!",
        )
        print(result.text)


asyncio.run(main())
```

`AsyncMantyxClient` exposes the same API as `MantyxClient` with `async`/`await` semantics. Local tool handlers may be sync **or** async — the SDK awaits them as needed.

## Triggering a persisted MANTYX agent

Pass `agent_id` to run an agent that already exists in your workspace. The server hydrates the agent's system prompt, model, and server-side tools (memory, skills, plugin tools, …) from the `Agent` row at run time. Anything you pass in `tools` is **merged on top** — typically `local` tools you want the agent to be able to call back into for this specific run.

```python
from pathlib import Path

from pydantic import BaseModel
from mantyx import MantyxClient, define_local_tool


class ReadFileArgs(BaseModel):
    path: str


client = MantyxClient(api_key="...", workspace_slug="acme")

result = client.run_agent(
    agent_id="agent_cm6abc123",  # workspace agent id
    prompt="Pull the latest deploy logs and summarise them.",
    tools=[
        define_local_tool(
            name="read_local_file",
            parameters=ReadFileArgs,
            execute=lambda args: Path(args.path).read_text(),
        ),
    ],
)
print(result.text)
```

Notes:

- `system_prompt` becomes optional when `agent_id` is set; if both are sent, the agent's stored prompt wins.
- `model_id` is also optional: omit it to use the agent's configured LLM provider, or pass it to override the model for this run.
- The API key must be authorized for the agent (an empty `agentIds` allowlist on the key counts as "all agents in the workspace"). Otherwise the call returns `403`.

The same `agent_id` field works on `client.create_session(...)` for multi-turn conversations against a persisted agent.

## Picking a model

```python
catalog = client.list_models()
print("\n".join(f"{m.id}\t{m.label}" for m in catalog.models))

client.run_agent(
    system_prompt="...",
    prompt="Hi!",
    model_id="platform:cm6abc123",  # or "provider:<id>", or "<vendorModelId>"
)
```

`model_id` accepts:

- `platform:<offeringId>` — a platform-hosted model offering.
- `provider:<llmProviderId>` — your own BYOK provider's default model.
- `provider:<llmProviderId>:<vendorModelId>` — your provider, override model.
- `<vendorModelId>` — bare vendor id; only resolves when one workspace provider can run it.
- omitted — workspace default.

## Streaming tokens

```python
# Iterator
for event in client.stream_agent(system_prompt="...", prompt="Tell me a story."):
    if event.type == "assistant_delta":
        print(event.text, end="", flush=True)
    elif event.type == "result":
        print()

# Or use the on_assistant_delta callback on run_agent:
client.run_agent(
    system_prompt="...",
    prompt="...",
    on_assistant_delta=lambda d: print(d, end="", flush=True),
)

# Async equivalents
async for event in async_client.stream_agent(system_prompt="...", prompt="..."):
    ...
```

## Multi-turn sessions

Sessions own the agent spec (system prompt, model, tool defs) and the full message history. Each `send` is a run scoped to the session.

```python
from datetime import date

from pydantic import BaseModel
from mantyx import MantyxClient, define_local_tool


class TodayArgs(BaseModel):
    pass


client = MantyxClient(api_key="...", workspace_slug="acme")

session = client.create_session(
    system_prompt="You are a friendly REPL.",
    tools=[
        define_local_tool(
            name="today",
            description="Get today's date as ISO 8601.",
            parameters=TodayArgs,
            execute=lambda _args: date.today().isoformat(),
        ),
    ],
)

r1 = session.send("What day is it?")
print(r1.text)

r2 = session.send("And what about tomorrow?")
print(r2.text)

session.end()
```

Resuming a session from a different process re-binds your local tool handlers; pass them in via `resume_session`:

```python
session = client.resume_session(
    session_id,
    tools=[
        define_local_tool(name="today", parameters=TodayArgs, execute=...),
    ],
)
```

### Tagging runs and sessions with `metadata`

Attach a flat `dict[str, str]` to runs and sessions so your team can filter the dashboard by it:

```python
client.run_agent(
    system_prompt="...",
    prompt="...",
    metadata={"customer": "acme", "env": "prod", "workflow": "support_triage"},
)

session = client.create_session(
    system_prompt="...",
    metadata={"customer": "acme", "env": "prod"},
)

# Per-message override — merged on top of the session's metadata
# (run-level keys win)
session.send("trace this turn", metadata={"trace_id": "trace_abc"})
```

Limits enforced server-side: max 16 entries; keys match `[A-Za-z0-9._-]{1,64}`; values are strings ≤ 256 chars; serialised JSON ≤ 4 KB. Bigger payloads return `400 invalid_request`.

## API reference

### `MantyxClient(...)` / `AsyncMantyxClient(...)`

```python
class MantyxClient:
    def __init__(
        self,
        *,
        api_key: str,
        workspace_slug: str,
        base_url: str = "https://app.mantyx.io",
        timeout: float = 60.0,
        http_client: httpx.Client | None = None,
    ): ...
```

`AsyncMantyxClient` accepts an `httpx.AsyncClient` instead.

### Methods

| Method                                          | Returns (sync)                       |
| ----------------------------------------------- | ------------------------------------ |
| `list_models()`                                 | `ModelCatalog`                       |
| `run_agent(...)`                                | `RunResult`                          |
| `stream_agent(...)`                             | `Iterator[RunEvent]`                 |
| `create_session(...)`                           | `AgentSession`                       |
| `resume_session(session_id, *, tools=None)`     | `AgentSession`                       |
| `end_session(session_id)`                       | `None`                               |
| `cancel_run(run_id)`                            | `None`                               |

The async client returns awaitable / async-iterator equivalents (e.g. `await async_client.run_agent(...)`, `async for ev in async_client.stream_agent(...)`).

### Tools

| Helper                       | Use case                                                              |
| ---------------------------- | --------------------------------------------------------------------- |
| `define_local_tool(...)`     | Define a local tool with a Pydantic parameter schema and handler.     |
| `define_local_a2a(...)`      | Register an A2A peer by `agent_card_url`; the SDK fetches and dials it. |
| `define_local_mcp(...)`      | Declare an MCP server by URL or stdio command; the SDK manages it.    |
| `mantyx_tool(id)`            | Reference an existing MANTYX workspace tool by id.                    |
| `mantyx_plugin_tool(name)`   | Reference an installed platform plugin tool by `@plugin/tool` name.   |
| `mantyx_a2a(...)`            | Reference a remote A2A peer MANTYX dials directly.                    |
| `mantyx_mcp(...)`            | Reference a remote MCP server (Streamable HTTP) MANTYX proxies.       |

#### Agent2Agent delegation

Two flavours, addressed identically by the model with `{ "message": str }`:

```python
from mantyx import define_local_a2a, mantyx_a2a

remote_billing = mantyx_a2a(
    name="billing_agent",
    agent_card_url="https://billing.example.com/.well-known/agent-card.json",
    description="Delegate billing questions to the public Acme billing agent.",
    headers={"Authorization": "Bearer ..."},
)

local_hr = define_local_a2a(
    name="intranet_hr_agent",
    agent_card_url="https://hr.intranet.acme/.well-known/agent-card.json",
    headers={"Authorization": "Bearer ..."},  # optional
)
```

`mantyx_a2a` is server-resolved: MANTYX dials `agent_card_url` over A2A's
`message/send` RPC and forwards the reply as the tool result.

`define_local_a2a` is client-resolved but **URL-only**: you pass the
`agent_card_url` (and optional `headers`), and the SDK takes care of the
rest. On the first run / session, the SDK fetches the Agent Card with
`httpx`, ships it inline with the agent spec (so MANTYX never reaches
your intranet), and on every `local_tool_call` event with
`kind: "a2a_local"` it speaks A2A's JSON-RPC `message/send` against
`agent_card.url`, returning the reply text as the tool result. The
fetched card is cached for the duration of the run / session.

##### Exposing an agent over A2A

The inverse direction also works: wrap a MANTYX agent (ephemeral spec or a
persisted `agent_id`) and serve it as an Agent2Agent peer using the official
[`a2a-sdk`](https://pypi.org/project/a2a-sdk/) Python package mounted on
Starlette + uvicorn.

```python
import asyncio
from mantyx import AsyncMantyxClient
from mantyx.a2a_server import build_agent_card, serve_agent_over_a2a

async def main() -> None:
    async with AsyncMantyxClient(api_key="...", workspace_slug="acme") as client:
        handle = await serve_agent_over_a2a(
            client=client,
            agent_card=build_agent_card(
                name="Acme Support",
                description="Customer support questions.",
                version="1.0.0",
                public_url="http://localhost:4000",
            ),
            agent_id="agent_cm6abc123",  # or system_prompt=..., model_id=..., tools=[...]
            port=4000,
        )
        print(f"A2A peer up on {handle.url}")
        await handle.serve_forever()

asyncio.run(main())
```

`a2a-sdk[http-server]` and `uvicorn` ship as the **`[a2a-server]` extra**
so the base wheel stays slim:

```bash
pip install "mantyx-sdk[a2a-server]"
```

Each unique A2A `context_id` opens a long-lived MANTYX session by default,
so multi-turn `message/send` calls share conversational history. Pass
`conversation="stateless"` to reduce every A2A request to a one-shot
`run_agent` call. For lower-level integration (mounting the executor in
your own Starlette / FastAPI app) `mantyx.a2a_server` also exports a
`MantyxAgentExecutor` class implementing `a2a.server.agent_execution.AgentExecutor`.

#### MCP connectors

Tools surface to the model as `<server>_<tool>` regardless of flavour:

```python
from mantyx import define_local_mcp, mantyx_mcp


remote_github = mantyx_mcp(
    name="github",
    url="https://api.example.com/mcp",
    headers={"Authorization": "Bearer ..."},
    tool_filter=["create_issue", "list_issues"],  # optional allow-list
)

# Streamable HTTP transport
local_fs_http = define_local_mcp(
    name="fs",
    url="http://localhost:8080/mcp",
    headers={"Authorization": "Bearer ..."},  # optional
)

# stdio transport
local_fs_stdio = define_local_mcp(
    name="fs",
    command="mcp-server-filesystem",
    args=["."],
    env={"FOO": "bar"},  # optional
    cwd="/workspace",     # optional
)
```

`mantyx_mcp` is server-resolved: MANTYX speaks Streamable HTTP MCP to the
upstream, lists its catalog, and proxies tool calls — prefixing every
discovered tool name as `<server>_<tool>`.

`define_local_mcp` is client-resolved but **URL-only** (or stdio
`command`-only). You point at the server and the SDK does the rest using
the official [`mcp`](https://pypi.org/project/mcp/) package: it opens the
transport, runs `Initialize` + `tools/list` on the first `run_agent` /
`session.send`, ships the resolved catalog (with `<server>_<tool>` names)
inline so MANTYX can render the tools to the model, forwards every
`local_tool_call` event with `kind: "mcp_local"` to the live MCP session
via `tools/call`, and closes the transport when the run / session ends
(`session.end()` for sessions, automatically for one-shot runs). Sync
clients drive the async MCP SDK transparently via an `anyio.BlockingPortal`.

#### Reasoning effort (`reasoning_level`)

Pass `reasoning_level` on `run_agent` / `stream_agent` / `create_session`
(and per-message via `session.send(prompt, reasoning_level=...)`) to dial
provider thinking. Accepts a string anchor (`"off"`, `"low"`, `"medium"`,
`"high"`) or an integer in `[0, 100]`. The SDK forwards the value as-is;
MANTYX maps it onto each LLM's native dial — see
`docs/agent-runs-protocol.md` §4.4.

```python
client.run_agent(system_prompt="...", prompt="...", reasoning_level="medium")
client.run_agent(system_prompt="...", prompt="...", reasoning_level=80)
```

### Errors

All raised errors extend `MantyxError`. Common subclasses:

- `MantyxAuthError` — 401/403 from the server (bad API key, wrong workspace).
- `MantyxNetworkError` — transport-layer failures.
- `MantyxRunError` — the agent loop terminated with an error.
- `MantyxToolError` — a local tool handler raised or timed out.

## Examples

Self-contained example projects live under [`examples/`](./examples/):

- `examples/oneshot-local-tool` — minimal one-shot run with a local tool.
- `examples/session-chat` — interactive REPL on top of a session.
- `examples/mixed-tools` — combines local, MANTYX, and plugin tools.
- `examples/a2a-tools` — combines `mantyx_a2a` (remote) and `define_local_a2a` (intranet) peers.
- `examples/mcp-tools` — combines `mantyx_mcp` (remote) and `define_local_mcp` (in-process).
- `examples/streaming` — token streaming to stdout.
- `examples/list-models` — model catalog + pick-and-run.
- `examples/agent-by-id` — trigger a persisted MANTYX agent by id.

Each example is its own project (`pyproject.toml`, `README.md`, `main.py`) so you can copy any one of them out of the repo and run it standalone.

## Wire protocol

This SDK is a thin client over a stable HTTP/SSE protocol. The full specification ships with the package at [`docs/agent-runs-protocol.md`](./docs/agent-runs-protocol.md). Anyone can implement a compatible client in another language.

## Development

```bash
python -m venv .venv
. .venv/bin/activate
python -m pip install -e ".[dev]"

pytest -q          # unit + mock-server tests
ruff check .       # lint
ruff format .      # format
mypy src           # strict type-check
```

The SDK has no internal `workspace:*`-style dependencies. `python -m build` produces a self-contained `dist/` ready for `python -m twine upload` (or PyPI Trusted Publishing — see [`CONTRIBUTING.md`](./CONTRIBUTING.md)).

See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the contribution flow and [`EXTRACT.md`](./EXTRACT.md) for the (very small) steps to lift this folder into its own public repository.

## License

[Apache-2.0](../LICENSE)
