Skip to main content
Glama
README.md
# mcpyse

Turn any mixin-based Python API client into a governed set of AI tools. `mcpyse` adds
**access tiers, approval gating, redaction and audit for AI tool access**, then serves the
tools over [MCP](https://modelcontextprotocol.io) (Model Context Protocol) or exports them as
plain LLM tool definitions.

It is built for the small house-style MSP platform clients (one `<Product>Client` composed of
`*Mixin` classes, one per API domain, with Google-style docstrings), but works with any object
whose public methods live on `*Mixin` bases, or with methods you mark with `@tool`.

## Features

- **Tool registration from existing clients.** Public methods on `*Mixin` classes are
  discovered automatically. JSON schemas come from type hints and Google-style `Args:`
  docstrings. Override anything with `@tool(...)` or a config dict.
- **Three tiers:** `read`, `write`, `high_risk`. A toolkit is created with a `max_tier`; tools
  above it are neither listed nor callable. Tiers not set explicitly are inferred from the
  method name (`get_`/`list_` → read, `create_`/`update_` → write, `delete_`/`revoke_`/
  `isolate_` and *unknown verbs* → high risk, so it fails closed).
- **Approval gating.** `high_risk` tools never execute. Calling one returns a *proposed
  action* that is handed to an approval backend for a named human to review. Ships with
  in-memory and file backends; implement `ApprovalBackend` to send proposals to a ticketing
  system.
- **Redaction and size caps.** Passwords, secrets, tokens and API keys are redacted from
  results and from logged arguments by default; add per-tool fields. `SecretString` values
  are never serialised. Results over a size cap are truncated.
- **Audit log.** Every call records tool, tier, redacted arguments, caller, outcome, result
  size and duration, to a JSONL file, a logger or your own callback.
- **Serving.** MCP over stdio or streamable HTTP via the official `mcp` SDK, plus
  Anthropic- and OpenAI-style tool definitions for agents that don't speak MCP.
- **Metadata.** Owner, data location or any other key/values per instance, published as an
  MCP resource and via `Toolkit.describe()` for a connector inventory.

## Installation

```bash
pip install "mcpyse[mcp] @ git+https://github.com/Ruderali/mcpyse.git"
```

The core (registry, gating, redaction, audit, export) has no dependencies and supports Python
3.9+. The MCP server extra needs Python 3.10+.

## Wrapping a client

```python
# my_tools.py
from mcpyse import Toolkit, AuditLog, JsonlFileSink, FileApprovalBackend
from examplepy import ExampleClient  # any mixin-based client

def build() -> Toolkit:
    client = ExampleClient.from_env(prefix="EXAMPLE_")
    return Toolkit(
        client,
        name="example-tools",
        max_tier="write",                      # read | write | high_risk
        prefix="example_",                     # tool names: example_list_organizations, ...
        config={
            "get_password": False,             # never expose this method
            "rotate_api_key": "high_risk",     # explicit tier (prepare-only)
            "list_passwords": {"redact": ["notes", "otp_secret"]},
            "search_documents": {"max_result_chars": 20_000},
        },
        approvals=FileApprovalBackend("approvals/"),
        approver="service-desk-lead",
        audit=AuditLog(JsonlFileSink("logs/example-tools.audit.jsonl")),
        metadata={"owner": "service desk", "data_location": "vendor cloud (US)"},
    )

if __name__ == "__main__":
    from mcpyse.server import serve_stdio
    serve_stdio(build())
```

Run it as an MCP server:

```bash
mcpyse serve my_tools:build                       # stdio
mcpyse serve my_tools:build --transport http --port 8000
mcpyse serve my_tools:build --max-tier read       # lower the tier for this instance
mcpyse tools my_tools:build --format anthropic    # print tool definitions
```

Or use it from a plain LLM tool loop:

```python
from mcpyse import to_anthropic_tools, handle_tool_call

tk = build()
tools = to_anthropic_tools(tk)                       # pass to the model
result_json = handle_tool_call(tk, name, arguments, caller="agent-42")
```

### Marking methods in the client itself

```python
from mcpyse import tool, exclude

class DevicesMixin:
    @tool("high_risk", redact=["recovery_key"])
    def isolate_device(self, device_id: str) -> dict:
        """Isolate a device from the network.

        Args:
            device_id: Device UID.
        """

    @exclude
    def raw_device_dump(self) -> dict: ...
```

## What a high-risk call returns

```json
{
  "tool": "example_delete_organization",
  "outcome": "proposed",
  "proposed_action": {
    "id": "7f3c...", "tool": "example_delete_organization",
    "arguments": {"org_id": 12}, "reason": "duplicate record",
    "approver": "service-desk-lead", "status": "pending", "server": "example-tools"
  },
  "message": "This action is high risk and was NOT executed. ..."
}
```

High-risk tools get an extra optional `reason` argument so the agent can justify the request,
and their description is prefixed `[PREPARE-ONLY ...]`.

## Configuration reference

| Toolkit argument | Default | Meaning |
|---|---|---|
| `max_tier` | `"read"` | Highest tier listed and callable |
| `config` | `{}` | Per-method tier / options / `False`; `"*": False` disables auto-discovery |
| `include` / `exclude` | all / none | Method-name allow / deny lists |
| `prefix` | `""` | Prefix for tool names |
| `redactor` | `Redactor()` | Field redaction policy (`NoRedaction()` to turn off key redaction) |
| `approvals` | in-memory | Where proposed actions go |
| `audit` | no sinks | `AuditLog(JsonlFileSink(...), logging_sink(), callback)` |
| `approver` | `None` | Named human recorded on proposals |
| `max_result_chars` | `50000` | Default result-size cap |
| `metadata` | `{}` | Owner, data location, etc. |

Credentials belong to the wrapped client (usually its `from_env(prefix=...)`); `mcpyse`
itself reads no environment variables.

## Not in this version

- Multi-user auth on the HTTP transport: run it behind the host's own auth.
- An approval UI, or executing approved actions automatically.
- Cost metering.

## Docs

- [API reference](docs/api-reference.md)
- [Using mcpyse with AI agents](docs/agents.md)

## License

MIT