> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiveth.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Verify Aiveth tokens and webhooks and call the admin API from a Python server with gooclaim-aiveth-sdk.

`gooclaim-aiveth-sdk` is the Aiveth by Gooclaim SDK for Python servers. Use it to check ID tokens, access tokens, machine tokens and AI agent tokens, to verify webhooks, and to call the admin API. It is synchronous and uses `httpx`.

## Install

Requires Python 3.10 or later.

```bash theme={null}
pip install gooclaim-aiveth-sdk
```

The import name is `gooclaim_aiveth_sdk`.

## Configure

```python theme={null}
import os
from gooclaim_aiveth_sdk import Aiveth

aiveth = Aiveth(
    "https://accounts.aiveth.com",
    api_key=os.environ.get("AIVETH_API_KEY"),  # only for the admin API and events
)
```

| Argument | Type | Description |
| - | - | - |
| `base_url` | `str` | Your Aiveth address. Required. |
| `api_key` | `str \| None` | An [API key](https://docs.aiveth.com/account/api-keys.md) (`aiveth_sk_...`). Needed only for the admin API and events. |
| `client` | `httpx.Client \| None` | Your own client, for tests. |
| `timeout` | `float` | Seconds per request. Default `10.0`. |

`Aiveth` is a context manager. Call `close()`, or use `with`, to close its HTTP client:

```python theme={null}
with Aiveth("https://accounts.aiveth.com", api_key=key) as aiveth:
    people = aiveth.people.list()
```

Each environment has its own keys: `aiveth_sk_test_...` for Development and `aiveth_sk_live_...` for production.

## Tokens

All token methods return the claims as a `dict`.

### `tokens.verify_id_token(token, *, client_id)`

Checks an app's ID token offline against Aiveth's published keys: signed by Aiveth, for this app, and not expired.

```python theme={null}
user = aiveth.tokens.verify_id_token(id_token, client_id="your-app-client-id")
user["sub"], user["org_id"], user.get("email")
```

### `tokens.user_from_access_token(access_token)`

An app's access token is opaque. Aiveth says who it stands for. Returns `None` when the token has ended.

```python theme={null}
user = aiveth.tokens.user_from_access_token(access_token)
if user is None:
    ...  # answer 401
```

### `tokens.verify_machine_token(token, *, org_id)`

Checks a [machine app's](https://docs.aiveth.com/apps/machine-to-machine.md) token meant for your organization's services.

```python theme={null}
machine = aiveth.tokens.verify_machine_token(token, org_id="your-organization-id")
```

### `tokens.verify_mcp_token(token, *, resource, scopes=())`

Checks an AI agent's token for your MCP server. `resource` is the server's address as registered in Aiveth. A token for any other server is refused. Missing `scopes` raise `InsufficientScopeError`.

```python theme={null}
who = aiveth.tokens.verify_mcp_token(bearer, resource="https://mcp.example.com/mcp", scopes=("files:read",))
```

### `tokens.connected_token(*, access_token, connection, client_id, client_secret)`

Gets the Google, Microsoft or GitHub token a person connected for your organization's apps. Returns `{access_token, expires_in?, scope}`. Server only: it needs your app's secret, and the app must have Connected accounts turned on.

```python theme={null}
google = aiveth.tokens.connected_token(
    access_token=access_token,
    connection="google",  # "google" | "microsoft" | "github"
    client_id=os.environ["AIVETH_CLIENT_ID"],
    client_secret=os.environ["AIVETH_CLIENT_SECRET"],
)
```

### `tokens.discover()`

Returns Aiveth's OpenID Connect discovery document. The other token methods call it for you.

### `has_flag(claims, key)`

Is a feature flag on for this person? Aiveth puts the flags that are on for the person in the ID token as `feature_flags`.

```python theme={null}
from gooclaim_aiveth_sdk import has_flag

if has_flag(user, "new-billing"):
    ...
```

## Webhooks

### `verify_webhook(raw_body, headers, secret, *, tolerance_seconds=300, now=None)`

Checks that Aiveth signed exactly these bytes, recently, and returns the parsed message. Raises `WebhookVerificationError` otherwise. `secret` is the `whsec_...` secret the console showed once. Pass the **raw** request body.

```python theme={null}
from flask import request
from gooclaim_aiveth_sdk import verify_webhook

@app.post("/webhooks/aiveth")
def aiveth_webhook():
    event = verify_webhook(request.get_data(), request.headers, os.environ["AIVETH_WEBHOOK_SECRET"])
    # handle event
    return "", 204
```

A message may arrive twice. Keep the `webhook-id`s you have handled and skip repeats. See [Webhooks](https://docs.aiveth.com/events/webhooks.md).

## Admin API

These need an API key with the right power. Every refusal raises `AivethError` with Aiveth's message and `status`. The powers are the same as in the [Node SDK](https://docs.aiveth.com/sdks/node.md#admin-api).

### People

| Method | Power |
| - | - |
| `people.list(email=None)` | `people:read` |
| `people.get(person_id)` | `people:read` |
| `people.set_role(person_id, role)` | `people:roles` |
| `people.set_active(person_id, active)` | `people:manage` |
| `people.sign_out(person_id)` | `people:manage` |
| `people.fields(person_id)` | `people:manage` |
| `people.set_fields(person_id, public=..., private=..., person=...)` | `people:manage` (`public` also needs `organization:fields`) |
| `people.import_people(people)` (up to 500) | `people:manage` |
| `people.import_all(people)` (any number, 500 at a time) | `people:manage` |
| `people.send_reset_emails()` | `people:manage` |

```python theme={null}
[asha] = aiveth.people.list(email="asha@example.com")
aiveth.people.set_active(asha["id"], False)

report = aiveth.people.import_all([
    {"email": "ravi@example.com", "first_name": "Ravi"},
])
```

### Invitations, roles and organization fields

| Method | Power |
| - | - |
| `invitations.list()` | `people:manage` |
| `invitations.send(email, role=None)` | `people:manage` |
| `invitations.withdraw(invitation_id)` | `people:manage` |
| `roles.list()` | `roles:read` |
| `organization.fields()` | `organization:fields` |
| `organization.set_fields(public=..., private=...)` | `organization:fields` |

### Fine-grained permissions

See [Fine-grained authorization](https://docs.aiveth.com/access/fine-grained-authorization.md).

| Method | Power |
| - | - |
| `authorization.check(person_id, permission, resource_type, resource_external_id)` | `authorization:read` |
| `authorization.resources_for(person_id, permission, type=None)` | `authorization:read` |
| `authorization.access_of(person_id)` | `authorization:read` |
| `authorization.register(type=..., external_id=..., name=..., parent_type=..., parent_external_id=...)` | `resources:write` |
| `authorization.find(type, external_id)` (or `None`) | `authorization:read` |
| `authorization.get(part_id)` | `authorization:read` |
| `authorization.people_with(part_id, permission)` | `authorization:read` |
| `authorization.change(part_id, name=..., parent_type=..., parent_external_id=...)` | `resources:write` |
| `authorization.remove(part_id, *, everything_below=False)` | `resources:write` |
| `authorization.give(resource_type, resource_external_id, role, *, person_id=None, group_id=None)` | `authorization:write` |
| `authorization.take(access_id)` | `authorization:write` |

```python theme={null}
aiveth.authorization.register(type="branch", external_id="mumbai", name="Mumbai",
                              parent_type="region", parent_external_id="west")
aiveth.authorization.give("branch", "mumbai", "branch_approver", person_id=ravi_id)
answer = aiveth.authorization.check(ravi_id, "claim:approve", "branch", "mumbai")
answer["allowed"]
```

### Consent

See [Consent](https://docs.aiveth.com/privacy/consent.md).

| Method | Power |
| - | - |
| `consents.record(person_id, notice_version, choices, language=None)` | `consent:write` |
| `consents.check(person_id, purpose)` | `consent:read` |
| `consents.allows(person_id, purpose)` | `consent:read` |
| `consents.get(person_id)` | `consent:read` |
| `consents.withdraw(person_id, purpose)` | `consent:write` |
| `consents.receipt(person_id)` | `consent:read` |
| `consents.import_earlier(notice_version, people)` (up to 500) | `consent:write` |
| `consents.import_all(notice_version, people)` (any number) | `consent:write` |

```python theme={null}
aiveth.consents.record(person_id, 3, {"account": True, "newsletter": False})

if aiveth.consents.allows(person_id, "newsletter"):
    send_newsletter()

aiveth.consents.withdraw(person_id, "newsletter")
```

A time-bound yes stops counting on its end date, so ask `allows` each time rather than storing the answer.

### Events

### `events.list(*, types=None, after=None, limit=None, range_start=None)`

Reads your organization's events, oldest first. Page on with `list_metadata["after"]`. Needs `events:read`.

```python theme={null}
after = None
while True:
    page = aiveth.events.list(types=["user.created"], after=after)
    for event in page["data"]:
        handle(event)
    after = page["list_metadata"]["after"]
    if not after:
        break
```

## Protect an MCP server

Register your MCP server in the console under **AI agents**, then:

```python theme={null}
from gooclaim_aiveth_sdk import (
    Aiveth, InsufficientScopeError, TokenVerificationError,
    challenge, protected_resource_metadata,
)

MCP = "https://mcp.example.com/mcp"
aiveth = Aiveth("https://accounts.aiveth.com")

# GET /.well-known/oauth-protected-resource/mcp
metadata = protected_resource_metadata(resource=MCP, base_url="https://accounts.aiveth.com", scopes=["files:read"])

# on every MCP request
try:
    who = aiveth.tokens.verify_mcp_token(bearer, resource=MCP, scopes=("files:read",))
except InsufficientScopeError:
    status, header = 403, challenge(resource=MCP, scope=["files:read"], error="insufficient_scope")
except TokenVerificationError:
    status, header = 401, challenge(resource=MCP, scope=["files:read"])
```

`metadata_url(resource)` gives the address where the metadata document lives. An agent token is for one MCP server. It lasts 10 minutes, and the agent renews it. See [MCP servers](https://docs.aiveth.com/agents/mcp-server.md).

## Errors

| Error | When |
| - | - |
| `AivethError` | Aiveth refused a call, or couldn't be reached. Has `status`. |
| `TokenVerificationError` | A token isn't valid. |
| `InsufficientScopeError` | An agent token lacks permissions. |
| `WebhookVerificationError` | A webhook's signature, timestamp or secret doesn't check out. |

All of them are subclasses of `AivethError`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.