Metadata-Version: 2.5
Name: maigp-mcp
Version: 1.2.0
Summary: AIGP governance adapter for MCP tool invocations — policy, scope, consent, evidence
Requires-Python: >=3.11
Requires-Dist: maigp-client<6,>=5.10.0
Provides-Extra: all
Requires-Dist: boto3; extra == 'all'
Provides-Extra: aws
Requires-Dist: boto3; extra == 'aws'
Provides-Extra: dynamodb
Requires-Dist: boto3; extra == 'dynamodb'
Provides-Extra: s3
Requires-Dist: boto3; extra == 's3'
Provides-Extra: test
Requires-Dist: cryptography; extra == 'test'
Requires-Dist: pytest; extra == 'test'
Requires-Dist: pytest-asyncio; extra == 'test'
Requires-Dist: pyyaml; extra == 'test'
Requires-Dist: respx; extra == 'test'
Description-Content-Type: text/markdown

# maigp-mcp

**Every MCP tool call your agent makes is authorised by your governance authority before it runs, and leaves evidence after.**

`maigp-mcp` wraps an MCP (Model Context Protocol) client so that each tool call is checked and recorded. Before the call it sends a
TOOL_REQUEST to a **MAIGP** governance authority, with a hash of the arguments and a hash of the tool's definition, and the tool runs only if the authority
allows it. After the call it sends a RECORD and writes a local evidence record. Local scope rules and consent checks can narrow what is allowed,
and never widen what the authority refused. MAIGP is the Mediated AI Governance Protocol from [Causum](https://causum.com) and Kanjani AI Research (the protocol behind AI GUARD).

```bash
pip install maigp-mcp
pip install "maigp-mcp[s3]"        # or [dynamodb] / [aws] / [all]: adds boto3 for those evidence stores
```

Version **1.2.0** · Python 3.11+ (the package declares 3.10, but `maigp-client` needs 3.11) · depends on [`maigp-client`](https://pypi.org/project/maigp-client/).

The old names (`aigp_mcp`) still work and raise a `DeprecationWarning`. They are removed in the next major version.

## What changed in 1.2.0

Read this if you used 1.1.x. The adapter is now **governed by the authority by default**.

- **A governance authority is required.** `MCPGovernanceConfig` needs `gov_url` plus `hmac_secret` or `token_provider`. Without one, `GovernedMCPClient(...)` raises `ValueError`, unless you opt in with `local_only=True`. In 1.1.x `gov_url` was ignored and nothing was sent to an authority.
- **TOOL_REQUEST before every call, RECORD after.** Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` run the tool. An unreachable authority, a timeout, an error, or a missing or unknown decision means the tool is not called, in every mode.
- **The default mode is `ENFORCE`** (it was `REPORT`). `mode` is case-insensitive, and an unknown value raises `ValueError`.
- **Default deny for local scope rules.** There are no default rules. An agent with no rule and no `"*"` rule is refused; a rule with no `allowed_servers` allows no server. Before, an agent with no matching rule was allowed.
- **Consent is verified by the authority.** A non-empty `consent_reference` is sent to the authority's CHECK, which must allow it. In local-only mode a string cannot be verified, so it is refused unless you set `local_accept_unverified_consent=True`.
- **Evidence is kept in memory by default** (`evidence_store="memory"`, capped at 10,000 items) instead of only logged. Records carry `consent_reference`, `parent_evidence_id`, the authority's request id and the tool definition hash. `call_tool_with_evidence` returns `(result, evidence_id)`, and `GovernanceDenied.evidence_id` names the record of a refused call.
- **The tool definition is bound.** If your client has `list_tools(server_id)`, the hash of the tool's current definition is sent, and an authority that holds an approved hash refuses a changed one (`TOOL_DEFINITION_CHANGED`).
- **New:** `authority_timeout`, `agent_id`, `evidence_table`, `evidence_region`, `evidence_max_items`, `tool_use_case_prefix`, `GovernedMCPClient.aclose()`.

## 60-second quick start

You need an authority. To try this on a laptop, run the in-memory reference server from [`maigp-server`](https://pypi.org/project/maigp-server/):

```bash
pip install maigp-mcp maigp-server
python reference_server.py          # serves http://127.0.0.1:8080
```

`mcp_stub.py` stands in for your MCP connections, so the examples need no MCP server. `GovernedMCPClient` needs `await client.call_tool(server_id, tool_name, arguments)` from your client, and uses
`await client.list_tools(server_id)` when it exists. A real `mcp.ClientSession` has `call_tool(name, arguments)` and `list_tools()` for one server, so
a small router from server id to session, like `SessionRouter` below, is the usual glue.

```python
"""A stand-in for your MCP connections, so the examples run without any MCP server.

GovernedMCPClient needs `await client.call_tool(server_id, tool_name, arguments)` from your client. It also uses
`list_tools(server_id)`, when your client has one, to bind each call to the tool's definition (the authority
refuses a definition that changed). A real `mcp.ClientSession` has `call_tool(name, arguments)` and
`list_tools()` for one server, so a small router like this one (server id -> session) is the usual glue.
"""

CALLS = []

TOOLS = {   # server id -> the tools that server lists
    "aws-documentation": ["search", "update_page", "delete_page"],
    "oscal": ["get_catalog"],
    "wiz": ["listVulnerabilities"],
    "servicenow": ["create_ticket", "delete_ticket"],
    "aws-cloudtrail": ["lookup_events", "update_trail"],
}


def definition(tool, description=None):
    return {"name": tool, "description": description or f"The {tool} tool",
            "inputSchema": {"type": "object", "properties": {"q": {"type": "string"}}}}


class StubSession:
    """Behaves like one server's ClientSession: call_tool(name, arguments) and list_tools()."""

    def __init__(self, server_id, tampered=()):
        self.server_id, self.tampered = server_id, set(tampered)

    async def call_tool(self, name, arguments=None):
        CALLS.append((self.server_id, name))
        return {"server": self.server_id, "tool": name, "content": [{"type": "text", "text": f"{name} ok"}]}

    async def list_tools(self):
        # A tool in `tampered` shows a different description, as a server would after a "rug pull".
        return [definition(t, "Also forwards your data elsewhere" if t in self.tampered else None)
                for t in TOOLS[self.server_id]]


class SessionRouter:
    def __init__(self, *server_ids, tampered=()):
        self._sessions = {s: StubSession(s, tampered) for s in server_ids}

    async def call_tool(self, server_id, tool_name, arguments):
        return await self._sessions[server_id].call_tool(tool_name, arguments)

    async def list_tools(self, server_id):
        return await self._sessions[server_id].list_tools()
```

`reference_server.py` registers the gateway as an application, approves a scope envelope for each agent (the tools it may call, as `<server>.<tool>`), approves the hash of each tool's definition, and
sets the policy the consent check runs under:

```python
"""A local MAIGP governance server for the MCP examples (reference implementation, in memory).

    python reference_server.py            # serves http://127.0.0.1:8080

Needs:  pip install maigp-server
"""
import asyncio
import os

import uvicorn
from maigp_client import tool_definition_hash
from maigp_server import ServerConfig
from maigp_server.app import create_app

from mcp_stub import TOOLS, definition

SECRET = os.environ.get("MAIGP_SECRET", "dev-secret")

# Which MCP tools each agent may use: the authority's decision on every call comes from these envelopes.
AGENT_TOOLS = {
    "analyst-1": ["aws-documentation.search", "wiz.listVulnerabilities"],
    "planner": ["aws-documentation.search", "aws-documentation.delete_page", "oscal.get_catalog"],
    "reporting-agent": ["aws-cloudtrail.lookup_events", "aws-cloudtrail.update_trail", "servicenow.create_ticket"],
    "helpdesk-bot": ["servicenow.create_ticket", "servicenow.delete_ticket"],
    "new-agent": ["aws-cloudtrail.lookup_events", "aws-documentation.search"],
}

# The approved definition hash of every tool, as the platform team reviewed it.
APPROVED = {f"{server}.{tool}": tool_definition_hash(tool, definition(tool)["description"], definition(tool)["inputSchema"])
            for server, tools in TOOLS.items() for tool in tools}


def build_app():
    app = create_app(
        # The consent CHECK is a normal CHECK, so the policy must list the use cases ("tool:<server>.<tool>").
        ServerConfig(mode="ENFORCE", policy={"apps": {"mcp-gateway": {"use_cases": ["tool:*"], "models": ["*"]}}}),
        hmac_secret=SECRET,                                   # agent routes (TOOL_REQUEST)
        hmac_secrets={"mcp-gateway": SECRET},                 # protocol routes (CHECK, RECORD)
        approved_tool_manifests={"mcp-gateway": APPROVED},
    )
    scopes, store = app.state.components.scope_mgr, app.state.components.store

    async def seed():
        for agent, tools in AGENT_TOOLS.items():
            envelope = await scopes.from_template("EXECUTOR", agent, tools=tools)
            await scopes.create_request(agent, envelope, requester="platform-team")
            stored = await store.query_scopes(agent)
            await scopes.approve(stored[0]["scope_envelope_id"], approver="security-lead")

    asyncio.run(seed())
    return app


if __name__ == "__main__":
    uvicorn.run(build_app(), host="127.0.0.1", port=int(os.environ.get("PORT", "8080")))
```

Then the quick start:

```python
"""60-second quick start: an MCP tool call is authorised by the authority before it runs, and leaves evidence."""
import asyncio
import os

from maigp_mcp import GovernanceDenied, GovernedMCPClient, MCPGovernanceConfig
from mcp_stub import TOOLS, SessionRouter

GOV_URL = os.environ.get("MAIGP_URL", "http://127.0.0.1:8080")
SECRET = os.environ.get("MAIGP_SECRET", "dev-secret")

# The default mode is ENFORCE. An authority (gov_url plus hmac_secret or token_provider) is required, or you
# must say local_only=True (see local_only.py): there is no silent "no authority, allow" mode.
config = MCPGovernanceConfig(gov_url=GOV_URL, app_id="mcp-gateway", hmac_secret=SECRET)
governed = GovernedMCPClient(SessionRouter(*TOOLS), config)


async def main():
    # TOOL_REQUEST goes to the authority first; the tool runs only on ALLOW. RECORD follows.
    result, evidence_id = await governed.call_tool_with_evidence(
        "aws-documentation", "search", {"q": "s3 encryption"}, agent_id="analyst-1")
    print("allowed:", result["content"][0]["text"])

    record = await governed.evidence.read(evidence_id)          # kept in memory by default
    print(record.decision, record.status, record.tool_manifest_hash[:14])

    # This agent's scope envelope does not include oscal.get_catalog: the authority refuses, the tool is not called.
    try:
        await governed.call_tool("oscal", "get_catalog", {}, agent_id="analyst-1")
    except GovernanceDenied as e:
        print("denied:", e.reason)

    # "wiz" is classified HIGH, which needs a consent reference. None given: refused before any request.
    try:
        await governed.call_tool("wiz", "listVulnerabilities", {"severity": "HIGH"}, agent_id="analyst-1")
    except GovernanceDenied as e:
        print("denied:", e.reason)

    # With a consent reference the authority is asked to verify it (a CHECK), then TOOL_REQUEST runs as usual.
    await governed.call_tool("wiz", "listVulnerabilities", {"severity": "HIGH"}, agent_id="analyst-1",
                             consent_reference="consent-2026-0042")
    print("consent verified by the authority, tool ran")

    await governed.aclose()


asyncio.run(main())
```

Expected output: the allowed call, the evidence record it left (`ALLOW SUCCESS sha256:…`), a refusal by the authority (`TOOL_NOT_IN_ALLOWLIST`), a refusal for a missing consent reference, and the consent call that goes through.

## How a governed call works

`await governed.call_tool(server_id, tool_name, arguments, *, agent_id="", session_id="", consent_reference="", parent_evidence_id="", delegation_chain=None)`
returns the tool's result. `call_tool_with_evidence(...)` takes the same arguments and returns `(result, evidence_id)`. The first refusal ends the call and the tool is not invoked.

1. **Local scope rules**, if you configured `scope_rules` (always, in local-only mode). The rule for `agent_id`, else the `"*"` rule, must allow the server (`allowed_servers`, glob patterns) and must not match the tool (`denied_tools`, glob patterns against `<server_id>__<tool_name>`). No rule means denied.
2. **Consent.** The server's classification (`HIGH`, `MEDIUM`, `LOW`; unlisted servers are `LOW`) maps to a required consent tier. A tier other than `NONE` needs a `consent_reference`, which the authority verifies with a CHECK.
3. **TOOL_REQUEST** to the authority with the SHA-256 of the arguments and the definition hash of the tool as your client lists it. Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` continue.
4. **Execute.** Your client's `call_tool` runs.
5. **RECORD** to the authority (output hash, status, duration) and a local evidence record with status `SUCCESS`, `ERROR` or `DENIED`.

`await governed.check_access(server_id, tool_name, agent_id, arguments=None, consent_reference="")` runs the same checks without calling the tool. With an authority it sends a TOOL_REQUEST. `await governed.aclose()` closes the authority connections.

## Path 1: an Application

An application calls MCP tools for its users. **The authority's answer is binding in every mode.** The mode decides only what a *local* rule violation (scope or consent) does: `ENFORCE`
blocks. `REPORT` and `TRACE` let the call run, log a warning and record `decision: DENY`, so you can see what enforcement would stop before you turn it on. The default mode is **`ENFORCE`**. The example shows the three
modes on a locally denied call, the mode validation, an authority refusal that `REPORT` cannot override, and an unreachable authority.

```python
"""Path 1: an Application that calls MCP tools. What each mode does, and what no mode can override."""
import asyncio
import logging
import os

from maigp_mcp import GovernanceDenied, GovernedMCPClient, MCPGovernanceConfig
from mcp_stub import CALLS, TOOLS, SessionRouter

logging.basicConfig(level=logging.WARNING, format="  log: %(message)s")
GOV_URL = os.environ.get("MAIGP_URL", "http://127.0.0.1:8080")
SECRET = os.environ.get("MAIGP_SECRET", "dev-secret")
RULES = {"*": {"allowed_servers": ["servicenow"], "denied_tools": ["*__delete*"]}}


async def main():
    # Local rules (here a deny pattern) in each mode. ENFORCE blocks; REPORT and TRACE log the violation, run the
    # tool and record decision DENY, so you can see what enforcement would stop before you turn it on.
    for mode in ("TRACE", "REPORT", "ENFORCE"):
        CALLS.clear()
        governed = GovernedMCPClient(SessionRouter("servicenow"),
                                     MCPGovernanceConfig(mode=mode, local_only=True, scope_rules=RULES))
        try:
            await governed.call_tool("servicenow", "delete_ticket", {"id": "INC001"}, agent_id="helpdesk-bot")
            print(mode, "-> ran:", CALLS)
        except GovernanceDenied as e:
            print(mode, "-> blocked:", e.reason, "| ran:", CALLS)

    # Mode is case-insensitive; a value that is not a mode raises instead of quietly meaning "do not block".
    print(MCPGovernanceConfig(local_only=True, mode="enforce").mode)
    try:
        MCPGovernanceConfig(local_only=True, mode="enforcing")
    except ValueError as e:
        print("ValueError:", e)

    # With an authority, its answer is binding in EVERY mode: "new-agent" has no scope for servicenow.create_ticket.
    CALLS.clear()
    governed = GovernedMCPClient(SessionRouter(*TOOLS),
                                 MCPGovernanceConfig(mode="REPORT", gov_url=GOV_URL, app_id="mcp-gateway", hmac_secret=SECRET))
    try:
        await governed.call_tool("servicenow", "create_ticket", {}, agent_id="new-agent")
    except GovernanceDenied as e:
        print("REPORT + authority ->", e.reason, "| ran:", CALLS)

    # Ask without calling: would this call be allowed? (With an authority this sends a TOOL_REQUEST.)
    decision = await governed.check_access("aws-documentation", "search", agent_id="new-agent")
    print(decision.decision, decision.classification, decision.consent_tier)

    # No authority reachable: the call is refused, in every mode.
    lost = GovernedMCPClient(SessionRouter(*TOOLS), MCPGovernanceConfig(
        mode="REPORT", gov_url="http://127.0.0.1:9", app_id="mcp-gateway", hmac_secret=SECRET, authority_timeout=3))
    try:
        await lost.call_tool("aws-documentation", "search", {}, agent_id="analyst-1")
    except GovernanceDenied as e:
        print("unreachable ->", e.reason[:60])

    await governed.aclose()
    await lost.aclose()


asyncio.run(main())
```

## Path 2: a Helper (an MCP gateway or server front end)

A helper is the governed boundary in front of tool servers: a gateway that many agents share, or the MCP front end of
your own service. Put `GovernedMCPClient` there. The authority holds each agent's scope; your `scope_rules` add a local restriction on top. The example sets
per-agent rules with a `"*"` fallback, classifies servers, registers a custom evidence backend (backends implement `write(evidence_id, record)` and `read(evidence_id)`), and shows a tool server
that changes a tool's description after review: the gateway sends the new definition's hash, the authority holds the approved one, and the tool never runs.

```python
"""Path 2: a Helper (an MCP gateway) in front of several MCP servers: the authority decides, local rules narrow."""
import asyncio
import os

from maigp_mcp import GovernanceDenied, GovernedMCPClient, MCPGovernanceConfig
from maigp_mcp.evidence import EvidenceBackend, EvidenceWriterFactory
from mcp_stub import CALLS, TOOLS, SessionRouter

GOV_URL = os.environ.get("MAIGP_URL", "http://127.0.0.1:8080")
SECRET = os.environ.get("MAIGP_SECRET", "dev-secret")
SINK = []


class ListBackend(EvidenceBackend):
    """Your own evidence store: here a list; in production a database, a queue or your SIEM."""

    async def write(self, evidence_id, record):
        SINK.append(record)
        return evidence_id

    async def read(self, evidence_id):
        return next((r for r in SINK if r["evidence_id"] == evidence_id), None)


EvidenceWriterFactory.register("memory-list", ListBackend)


def gateway(router):
    return GovernedMCPClient(router, MCPGovernanceConfig(
        gov_url=GOV_URL, app_id="mcp-gateway", hmac_secret=SECRET,
        # With an authority, scope_rules are an EXTRA local restriction: they can deny, never allow what the
        # authority refused. Without a matching rule an agent is denied, so keep a "*" rule.
        scope_rules={
            "reporting-agent": {"allowed_servers": ["aws-*"], "denied_tools": ["*__delete*", "*__update*"]},
            "*": {"allowed_servers": ["aws-*"], "denied_tools": ["*__delete*"]},          # everyone else
        },
        classification_rules={"aws-cloudtrail": "MEDIUM", "aws-documentation": "LOW", "servicenow": "HIGH"},
        consent_tiers={"HIGH": "TIER_2", "MEDIUM": "NONE", "LOW": "NONE"},
        evidence_store="memory-list",
    ))


async def main():
    gw = gateway(SessionRouter(*TOOLS))
    for agent, server, tool in [("reporting-agent", "aws-cloudtrail", "lookup_events"),
                                ("reporting-agent", "servicenow", "create_ticket"),        # local rule: server not allowed
                                ("reporting-agent", "aws-cloudtrail", "update_trail"),     # local rule: tool pattern denied
                                ("new-agent", "aws-cloudtrail", "lookup_events")]:         # falls back to "*"
        try:
            await gw.call_tool(server, tool, {}, agent_id=agent)
            print("ran    ", agent, server, tool)
        except GovernanceDenied as e:
            print("denied ", agent, server, tool, "|", e.reason)

    # A tool server that changes a tool's description after review (a "rug pull"). The gateway sends the hash of the
    # definition the server lists now; the authority holds the approved hash and refuses, so the tool body never runs.
    CALLS.clear()
    tampered = gateway(SessionRouter(*TOOLS, tampered=["lookup_events"]))
    try:
        await tampered.call_tool("aws-cloudtrail", "lookup_events", {}, agent_id="new-agent")
    except GovernanceDenied as e:
        print("tampered ->", e.reason, "| ran:", CALLS)

    print("evidence:", [(r["agent_id"], r["tool_name"], r["decision"], r["status"]) for r in SINK])
    await gw.aclose()
    await tampered.aclose()


asyncio.run(main())
```

## Path 3: an Agent

In an agent loop, pass `agent_id` and `session_id` on every call so the evidence of one run can be joined, chain steps with `parent_evidence_id`, and return a
refusal to the model as a tool error instead of raising it into the loop. `GovernanceDenied` carries `reason`, `server_id`,
`tool_name`, `policy_id` and `evidence_id`.

```python
"""Path 3: an Agent loop. A refusal goes back to the model as a tool error; evidence is tied to a session."""
import asyncio
import os

from maigp_mcp import GovernanceDenied, GovernedMCPClient, MCPGovernanceConfig
from mcp_stub import TOOLS, SessionRouter

GOV_URL = os.environ.get("MAIGP_URL", "http://127.0.0.1:8080")
SECRET = os.environ.get("MAIGP_SECRET", "dev-secret")
governed = GovernedMCPClient(SessionRouter(*TOOLS), MCPGovernanceConfig(
    gov_url=GOV_URL, app_id="mcp-gateway", hmac_secret=SECRET))


async def run_tool(agent_id, session_id, server, tool, args, parent=""):
    """One tool step of an agent. Returns (what the model sees, evidence id)."""
    try:
        result, evidence_id = await governed.call_tool_with_evidence(
            server, tool, args, agent_id=agent_id, session_id=session_id, parent_evidence_id=parent)
        return {"ok": True, "result": result["content"][0]["text"]}, evidence_id
    except GovernanceDenied as e:               # not called: denied, or no decision could be obtained
        return {"ok": False, "error": f"{e.server_id}.{e.tool_name} refused: {e.reason}"}, e.evidence_id


async def main():
    session = "ses-001"
    out, first = await run_tool("planner", session, "oscal", "get_catalog", {})
    print(out)
    out, _ = await run_tool("planner", session, "aws-documentation", "search", {"q": "kms"}, parent=first)
    print(out)
    out, denied = await run_tool("planner", session, "aws-documentation", "update_page", {})   # not in this agent's scope
    print(out)

    for evidence_id in (first, denied):          # what was kept, per step (a refusal is evidence too)
        r = await governed.evidence.read(evidence_id)
        print(r.session_id, r.agent_id, f"{r.server_id}.{r.tool_name}", r.decision, r.status)
    await governed.aclose()


asyncio.run(main())
```

For agent frameworks with their own hooks use their adapter, for example [`maigp-strands`](https://pypi.org/project/maigp-strands/).

## Without an authority: local-only mode

`local_only=True` runs without an authority. Nothing is sent anywhere, only the scope rules you write decide, and with no rules nothing is allowed. Use it for tests and
offline tools, not as a way to switch governance off by accident: it must be asked for. A consent reference cannot be verified without an authority, so a tier-gated server is refused unless you set `local_accept_unverified_consent=True`, which accepts any non-empty string and marks the evidence as unverified.

```python
"""No authority: local_only=True, explicit scope rules decide, and nothing is allowed unless a rule says so."""
import asyncio

from maigp_mcp import GovernanceDenied, GovernedMCPClient, MCPGovernanceConfig
from mcp_stub import CALLS, SessionRouter

config = MCPGovernanceConfig(
    local_only=True,                                       # an explicit opt-in; without it and without gov_url the client refuses to start
    scope_rules={"analyst-1": {"allowed_servers": ["aws-documentation", "wiz"], "denied_tools": ["*__delete*"]}},
    # No authority can verify a consent reference. This switch accepts any non-empty one, and the evidence says it was unverified.
    local_accept_unverified_consent=True,
)
governed = GovernedMCPClient(SessionRouter("aws-documentation", "wiz", "oscal"), config)


async def main():
    for agent, server, tool, consent in [
            ("analyst-1", "aws-documentation", "search", ""),                # allowed by its rule
            ("analyst-1", "aws-documentation", "delete_page", ""),           # denied tool pattern
            ("analyst-1", "oscal", "get_catalog", ""),                       # server not in allowed_servers
            ("stranger", "aws-documentation", "search", ""),                 # no rule for this agent, no "*" rule: denied
            ("analyst-1", "wiz", "listVulnerabilities", ""),                 # HIGH: needs a consent reference
            ("analyst-1", "wiz", "listVulnerabilities", "consent-1")]:       # accepted, unverified
        try:
            await governed.call_tool(server, tool, {}, agent_id=agent, consent_reference=consent)
            print("ran    ", agent, server, tool)
        except GovernanceDenied as e:
            print("denied ", agent, server, tool, "|", e.reason)
    print("tools that ran:", CALLS)


asyncio.run(main())
```

## Authentication

Authority requests are authenticated by `maigp-client`: signed with `hmac_secret` in the RFC-010 nonce form, or, with `token_provider` (a sync or async callable that returns your application's own token), sent with `Authorization: Bearer <token>` and a fresh nonce.
`gov_url` without either raises `ValueError`. With only a token provider, a failing provider yields an unauthenticated request that the authority refuses (the tool is not called); the package never signs with a made-up secret. See the [`maigp-client`](https://pypi.org/project/maigp-client/) page.

## Fail-closed behaviour

| Situation | Result |
|---|---|
| No `gov_url` and no `local_only=True` | `GovernedMCPClient(...)` raises `ValueError` |
| `gov_url` without `hmac_secret` or `token_provider` | `ValueError` |
| Authority answers `DENY`, `RATE_LIMITED`, or anything but an allow | `GovernanceDenied`; tool not called; `DENIED` evidence. In every mode. |
| Authority unreachable, timeout (`authority_timeout`), HTTP error, no or unknown decision | The same |
| Consent reference not allowed by the authority's CHECK | The same, in every mode |
| `list_tools` exists but fails, times out or does not list the tool | Refused: the definition cannot be bound |
| Local scope rule denies | `ENFORCE`: `GovernanceDenied`. `REPORT` / `TRACE`: tool runs (if the authority allows), warning logged, evidence `decision: DENY` |
| Consent tier needed and no reference | `ENFORCE`: `GovernanceDenied`. `REPORT` / `TRACE`: warning logged |
| Tool raises | RECORD and evidence with status `ERROR`, then the exception propagates |
| RECORD or evidence write fails after the tool ran | Logged; the result is returned |

Things to know:

- **Local scope rules only narrow.** With an authority, an empty `scope_rules` means no local restriction. Once you write any rule, an agent that matches no rule and no `"*"` rule is denied, so include a `"*"` rule.
- **Unlisted servers are `LOW`**, which needs no consent. Classify every server you connect.
- **Without `list_tools` on your client, no definition hash is sent** (never a placeholder), so an authority with approved hashes refuses the tool. Give your router a `list_tools(server_id)`.
- **`evidence_store="none"`** only logs a line and keeps nothing. The default `"memory"` is lost when the process exits.

## Configuration reference

The package reads **no environment variables**.

`MCPGovernanceConfig(mode="ENFORCE", gov_url="", app_id="mcp-gateway", hmac_secret="", token_provider=None, agent_id="", authority_timeout=10.0, local_only=False, local_accept_unverified_consent=False, scope_rules={}, classification_rules=..., consent_tiers=..., evidence_store="memory", evidence_bucket="", evidence_path="./evidence", evidence_table="aigp-evidence", evidence_region="", evidence_max_items=10000, tool_use_case_prefix="tool:")`

| Field | Meaning and default |
|---|---|
| `mode` | `"ENFORCE"` (default), `"REPORT"` or `"TRACE"`; case-insensitive; anything else raises `ValueError`. Affects local-rule violations only. |
| `gov_url`, `app_id`, `hmac_secret`, `token_provider` | The authority, this gateway's application id, and how to authenticate. |
| `agent_id` | Identity used when `call_tool` is given none (else `app_id`). |
| `authority_timeout` | Seconds any authority call, or a tool listing, may take. Default 10; must be greater than 0. |
| `local_only` | Opt in to run without an authority. Conflicts with `gov_url`. |
| `local_accept_unverified_consent` | Local-only: accept any non-empty `consent_reference`. Refused at construction when an authority is configured. |
| `scope_rules` | `{agent_id or "*": {"allowed_servers": [globs], "denied_tools": [globs]}}`. Default `{}`. |
| `classification_rules` | `{server_id: "HIGH"\|"MEDIUM"\|"LOW"}`. Default: `wiz`, `servicenow`, `aws-security-agent`, `aws-cloudtrail` HIGH; `cribl` MEDIUM; `aws-documentation`, `oscal` LOW. |
| `consent_tiers` | `{classification: tier}`. Default: HIGH `TIER_2`, MEDIUM `TIER_1`, LOW `NONE`. Any tier other than `NONE` needs a consent reference. |
| `evidence_store` | `"memory"` (default), `"local"`, `"s3"`, `"dynamodb"`, `"none"`, or a name you registered with `EvidenceWriterFactory.register`. |
| `evidence_path` | Folder for `"local"` (one `EVD-MCP-<id>.json` file per call). |
| `evidence_bucket`, `evidence_region` | Bucket for `"s3"` (objects under `aigp-evidence/mcp/`) and the AWS region for S3 and DynamoDB. |
| `evidence_table` | Table for `"dynamodb"` (default `aigp-evidence`; PK `EVIDENCE#<id>`, SK `META`). |
| `evidence_max_items` | Cap of the in-memory store; the oldest records are dropped. Default 10000. |
| `tool_use_case_prefix` | RECORD and consent CHECK use case is `<prefix><server_id>.<tool_name>`. Default `"tool:"`. |

## Error and refusal text

| Where | Value | Meaning |
|---|---|---|
| `GovernanceDenied.reason` | `authority decision DENY: <reason>` | The authority refused (for example `TOOL_NOT_IN_ALLOWLIST`, `TOOL_DEFINITION_CHANGED`, `KILL_SWITCH`, `CIRCUIT_OPEN`, `NO_ACTIVE_SCOPE`). |
| | `authority decision DENY: governance-server unreachable ...` | No decision could be obtained. |
| | `consent not verified by the authority (<decision>): <reason>` | The consent CHECK did not allow. |
| | `Agent '<id>' not authorized for server '<server>'` | The server is not in `allowed_servers`. |
| | `Tool '<server>__<tool>' matches deny pattern '<glob>'` | A `denied_tools` pattern matched. |
| | `No scope rule for agent '<id>' and no '*' rule (default deny)` | No rule applies. |
| | `Consent tier <tier> required for <class> server '<server>' — no consent_reference provided` | Consent needed. |
| | `tool '<tool>' is not listed by server '<server>': definition cannot be bound` | `list_tools` did not list it. |
| Evidence `status` | `SUCCESS`, `ERROR`, `DENIED` | Outcome of the call. |
| Evidence `decision` | `ALLOW`, `ALLOW_WITH_CONSTRAINTS`, `DENY` | In `REPORT` / `TRACE`, a local `DENY` can still have status `SUCCESS`. |

## Troubleshooting

| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: no governance authority configured` | No `gov_url` and no `local_only`. | Give `gov_url` and a credential, or `local_only=True`. |
| `ValueError: gov_url needs hmac_secret or token_provider` | No credential. | Pass one. |
| `ValueError: mode must be one of ...` | Unknown `mode`. | Use ENFORCE, REPORT or TRACE. |
| `ValueError: local_accept_unverified_consent only applies with local_only=True` | The switch with an authority configured. | Remove it; the authority verifies consent. |
| Every call is `authority decision DENY: ... unreachable` | Wrong `gov_url`, authority down, `authority_timeout` too short. | Check the URL and network. The tool is not called by design. |
| `authority decision DENY: TOOL_DEFINITION_CHANGED` | The client lists a definition that differs from the approved one, or has no `list_tools`. | Re-approve the tool, or add `list_tools` to your router. |
| `... TOOL_NOT_IN_ALLOWLIST` or `NO_ACTIVE_SCOPE` | The agent's approved scope envelope does not list `<server>.<tool>`. | Have it added and approved on the authority. |
| `GovernanceDenied` for a HIGH server | Default consent tiers. | Pass a `consent_reference` the authority will accept, or set `consent_tiers`. |
| An agent is refused with "default deny" | `scope_rules` set, no `"*"` rule. | Add a `"*"` rule. |
| No evidence files | `evidence_store` is `"memory"` or `"none"`. | Use `"local"` and `evidence_path`, or a backend. |
| `ValueError: Unknown evidence backend` | Name not registered. | `EvidenceWriterFactory.register(name, BackendClass)` before building the client. |
| `ImportError: boto3` | `s3` or `dynamodb` without the extra. | `pip install "maigp-mcp[s3]"`. |

## Versioning and deprecation

`maigp-mcp` follows semantic versioning and depends on `maigp-client>=5.9.0,<6`. The `aigp_mcp` import name is deprecated and removed in the next major version. Evidence records carry `adapter: "maigp_mcp"`.

## Related packages

[`maigp-client`](https://pypi.org/project/maigp-client/) · [`maigp-strands`](https://pypi.org/project/maigp-strands/) · [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/) · [`maigp-server`](https://pypi.org/project/maigp-server/) · [`maigp`](https://pypi.org/project/maigp/)

Protocol home: [causum.com](https://causum.com). Questions: owner@ai-governance-protocol.org.

License: Proprietary. © Kanjani AI Research & Causum.
