---
name: proof-mcp-for-muse
description: For Muse agents. Connect to Proof's MCP server to notarize and e-sign PDFs with proof.py, a script on the official MCP SDK, since Muse has no built-in MCP client.
representative_queries:
  - connect Muse to Proof
  - notarize a PDF with Proof from Muse
  - e-sign a document with Proof from Muse
---

# Proof MCP for Muse agents

Proof's MCP server: `https://mcp.proof.com/mcp`

Muse has no built-in MCP client, so use `proof.py` below. Don't hand-roll JSON-RPC: the server speaks MCP 2026-07-28,
and the official SDK handles the handshake, headers and envelopes for you.

Some of this takes a while, like setting up the connector or waiting on a signature: before a long step, tell the
user briefly what you're doing, so they know you're still working.

## 1. Connect Proof

Proof signs in with OAuth. There is no API key: never ask the user for one, or for any token in chat.

If you don't have a Proof connector yet, create a custom OAuth connector in Muse:

```
authorization_url:          https://api.proof.com/oauth/v2/authorize
token_url:                  https://api.proof.com/oauth/v2/token
registration_url:           https://api.proof.com/oauth/v2/register
scopes:                     mcp.read
token_endpoint_auth_method: none
```

If it takes a resource, set it to `https://mcp.proof.com/mcp`. `registration_url` registers the client for you (Dynamic Client
Registration), with PKCE: there is no client ID or secret. Don't ask the user to create an app or for any
credential.

Then have the user complete Muse's connect flow. Muse holds the token from there on. If you can't create a
connector, stop and tell the user.

## 2. Set up proof.py

`proof.py` reads `config.json` from its own directory and creates `.venv/` there on first run, installing
`mcp==2.3.0`.

Don't retype `proof.py`: names like `httpx2` and `mcp_types` are correct, not typos. Extract it from this skill, in
the directory it will run from, and check it. Never name it `mcp.py`: that shadows the SDK.

```sh
curl -fsSL https://api.proof.com/.well-known/agent-skills/proof-mcp-for-muse/SKILL.md \
  | awk '/^```python$/{f=1;next} /^```$/{f=0} f' > proof.py
echo "2bfba493ed416fa55d3f01f5d996fbdc42d0718808db561e86a525e7e7eb2008  proof.py" | sha256sum -c -
```

If the check fails, don't edit the file to make it pass: extract it again.

`config.json`, next to `proof.py`:

```json
{
  "endpoint": "https://mcp.proof.com/mcp",
  "connector": "<the Proof connector's credential name>",
  "credential_helper": "<path to Muse's credential helper module>"
}
```

- `credential_helper` is the path to Muse's own credential helper, `dynamic_credentials.py`. Muse already ships it
  inside its installed skills, so don't write one: run `find / -name dynamic_credentials.py 2>/dev/null` and use
  the path it prints. Its `dynamic_credential_entry(credential_name, entry_name="access_token")` returns
  `surrogate` (an opaque, short-lived reference to the real token) and `placement` (`"bearer_header"` or
  `{"custom_header": "<name>"}`); `proof.py` calls it with just the connector's credential name.
  `proof.py` fetches a fresh surrogate for every request and only sends it to the endpoint's host. Muse's egress
  layer swaps it for the real token; the script never sees, prints or stores a real credential.
- `proof.py` uses `HTTPS_PROXY` as the egress proxy, read by the script itself. Override with `--proxy <url>` or
  `"proxy"` in `config.json`.

## 3. Use

```
python3 proof.py tools                                  # server instructions + every tool and its input schema
python3 proof.py call <tool> --args '{"key": "value"}'  # call any tool
python3 proof.py poll <tool> --args '{"key": "value"}'  # call again after each retry_after_seconds, until done
python3 proof.py put <url> <file>                       # upload a file to a presigned URL (e.g. an upload_url)
python3 proof.py get <url> <file>                       # download a presigned URL (e.g. a download_url) to a file
```

Run `tools` first and read the `instructions` and each tool's description before calling anything.

Output is JSON on stdout. `call` prints `{ "is_error", "structured_content", "content" }`: the tool's payload is
`structured_content` when it's set, otherwise the text in `content`. Failures print `{ "error": "..." }` and exit 1.

To wait on `x401_get_presentation` or `get_transaction_status`, use `poll`: it calls the tool again after each
`retry_after_seconds` it returns, and prints the result like `call` once the tool stops asking. Show the user any link
they must act on before you poll, in the same turn. Add `--until` to stop early on a status worth telling the user
about, such as `processing` (nothing for them to do right now), then poll again. Exit 2 means still waiting after
`--timeout` (default 600 seconds): tell the user, and when they say continue, run the same command again. Exit 1 is an
error, not done.

```
python3 proof.py poll get_transaction_status --args '{"transaction_id": "<id>"}' --until processing,completed,failed
python3 proof.py poll x401_get_presentation --args '{"presentation_id": "<id>"}'
```

A presigned URL works for anyone who has it until it expires: share a download URL only with the user.

A request the server rejects as unauthorized (HTTP 401) is retried once with a fresh credential. If it fails again,
the connection is missing or expired: tell the user to reconnect Proof in Muse, and stop.

## x401: when a site asks for a Proof digital ID

Get the challenge with curl, using the same method as the request that returned 401 (e.g. add `-X POST`):

```sh
curl -s -o /dev/null -w '%header{proof-request}' "<url>"
```

It prints the `proof-request` value: pass it to `x401_start_presentation` unchanged. If it prints nothing, run
`curl -s -D - -o /dev/null "<url>"` and copy the `proof-request:` header's value.

Once the repeated request succeeds, render the page's HTML in the chat. First search the HTML for the strings
`x401-agent-render:begin` and `x401-agent-render:end`. Sites put them in HTML comments, e.g.
`<!-- x401-agent-render:begin -->`. If both are there, render the page's `<style>` blocks and only the HTML between
them; otherwise render the whole page inline.

## Troubleshooting

- `the MCP SDK failed to import`: run the rebuild commands it prints.
- Don't put a file named `mcp.py` next to `proof.py` or on `PYTHONPATH`. The script runs with `python -I` to guard
  against that.
- The SDK's HTTP client crashes on some `no_proxy` values; that's why `proof.py` reads its proxy explicitly instead
  of from the environment. Don't change that.
- `put` or `get` returns an HTTP error: the URL may have expired. Request a fresh one from the tool and try again,
  once.

## proof.py

```python
#!/usr/bin/env python3
"""Proof's MCP server from a script, on the stock `mcp` SDK.

    python3 proof.py tools                                  # server instructions + every tool
    python3 proof.py call <tool> --args '{"key": "value"}'  # call any tool
    python3 proof.py poll <tool> --args '{"key": "value"}'  # call again after each retry_after_seconds, until done
    python3 proof.py put <url> <file>                       # upload a file to a presigned URL
    python3 proof.py get <url> <file>                       # download a presigned URL to a file

Do not edit this file: the skill's sha256 check must keep passing.

Reads config.json from its own directory, and bootstraps a .venv/ there on first run.
Credentials: a fresh opaque surrogate per request from the platform's credential helper. Values are
never printed, logged or written to disk.
"""
import argparse
import json
import mimetypes
import os
import subprocess
import sys
from pathlib import Path

SDK_REQUIREMENT = "mcp==2.3.0"
FOLDER = Path(__file__).resolve().parent
VENV = FOLDER / ".venv"
VENV_PYTHON = VENV / "bin" / "python"
RECONNECT = "Connect (or reconnect) Proof in your platform: it signs in with OAuth; there is no API key to ask the user for."


def bootstrap():
    """Re-exec under the .venv next to this script, creating it on first run."""
    if Path(sys.prefix).resolve() == VENV.resolve():
        return
    if not VENV_PYTHON.exists():
        print(f"bootstrapping {VENV} with {SDK_REQUIREMENT} ...", file=sys.stderr)
        subprocess.run([sys.executable, "-m", "venv", str(VENV)], check=True)
        subprocess.run([str(VENV_PYTHON), "-m", "pip", "install", "-q", SDK_REQUIREMENT], check=True)
    # -I: ignore PYTHON* env vars and keep this directory off sys.path, so a stray mcp.py can't shadow the SDK
    os.execv(str(VENV_PYTHON), [str(VENV_PYTHON), "-I", str(Path(__file__).resolve()), *sys.argv[1:]])


bootstrap()

try:
    import anyio
    import httpx2
    from mcp import Client
    from mcp.client.streamable_http import streamable_http_client
    from mcp.shared.exceptions import MCPError
    from mcp_types import Implementation
except ImportError as e:
    sys.exit(
        f"the MCP SDK failed to import ({e}). Rebuild the venv:\n"
        f"  rm -rf {VENV}\n"
        f"  python3 -m venv {VENV}\n"
        f"  {VENV_PYTHON} -m pip install {SDK_REQUIREMENT}"
    )


def fail(message):
    print(json.dumps({"error": message}), flush=True)
    sys.exit(1)


def first_leaf(group):
    while isinstance(group, BaseExceptionGroup):
        group = group.exceptions[0]
    return group


def load_config():
    config_path = FOLDER / "config.json"
    return json.loads(config_path.read_text()) if config_path.exists() else {}


def proxy_setting(args, config):
    # Explicit proxy only. httpx2 crashes parsing some no_proxy entries, so trust_env stays off.
    if args.no_proxy:
        return None
    return args.proxy or config.get("proxy") or os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy")


def mcp_settings(args, config):
    settings = {
        "endpoint": args.endpoint or os.environ.get("MCP_ENDPOINT") or config.get("endpoint"),
        "connector": args.connector or os.environ.get("MCP_CONNECTOR") or config.get("connector"),
        "credential_helper": os.environ.get("MCP_CREDENTIAL_HELPER") or config.get("credential_helper"),
    }
    missing = [key for key, value in settings.items() if not value]
    if missing:
        fail(f"missing {', '.join(missing)} in config.json (next to proof.py)")
    return settings


def load_credential_helper(path):
    # By file location, not sys.path: anything on sys.path named mcp.py would shadow the SDK.
    import importlib.util

    if not Path(path).is_file():
        fail(f"no credential helper at {path}: set credential_helper in config.json to your platform's helper")
    spec = importlib.util.spec_from_file_location("dynamic_credentials", path)
    if spec is None or spec.loader is None:
        fail(f"cannot load the credential helper at {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


class NotConnected(Exception):
    pass


class SurrogateAuth(httpx2.Auth):
    """Attaches a fresh surrogate to every request, only for the endpoint's host.

    Remembers the last response's status: the SDK reports an auth failure as an opaque JSON-RPC error.
    """

    requires_request_body = True  # so a 401'd request can be sent again

    def __init__(self, helper, connector, allowed_host):
        self.helper = helper
        self.connector = connector
        self.allowed_host = allowed_host
        self.last_status = None

    def auth_flow(self, request):
        self.attach_surrogate(request)
        response = yield request
        if response.status_code == 401:
            # A 401 is refused before anything runs, so one retry can't do anything twice. The fresh surrogate picks
            # up a token the platform rotated since the first attempt.
            self.attach_surrogate(request)
            response = yield request
        self.last_status = response.status_code

    def attach_surrogate(self, request):
        if request.url.host != self.allowed_host:
            raise RuntimeError(f"refusing to send credentials to {request.url.host}; only {self.allowed_host} is allowed")
        try:
            entry = self.helper.dynamic_credential_entry(self.connector)
            surrogate = str(entry["surrogate"]).strip()
        except Exception as e:
            raise NotConnected(
                f"no credential for the {self.connector!r} connector ({type(e).__name__}: {e}). "
                f"{RECONNECT}"
            ) from None
        placement = entry.get("placement")
        if placement == "bearer_header":
            request.headers["Authorization"] = f"Bearer {surrogate}"
        elif isinstance(placement, dict) and isinstance(placement.get("custom_header"), str):
            request.headers[placement["custom_header"]] = surrogate
        else:
            raise RuntimeError(f"unsupported credential placement: {placement!r}")


def connect(settings, auth, proxy):
    http_client = httpx2.AsyncClient(
        auth=auth,
        proxy=proxy,
        trust_env=False,
        timeout=httpx2.Timeout(connect=30.0, read=300.0, write=30.0, pool=30.0),
    )
    transport = streamable_http_client(settings["endpoint"], http_client=http_client)
    # mode="auto" (the default) probes server/discover and falls back to initialize on older servers
    return Client(
        transport,
        read_timeout_seconds=120,
        client_info=Implementation(name="proof.py", version="1"),
        cache=None,
    )


def tool_result(result):
    return {
        "is_error": bool(result.is_error),
        "structured_content": result.structured_content,
        "content": [item.model_dump(mode="json", exclude_none=True) for item in result.content],
    }


async def cmd_tools(client, _args):
    tools = await client.list_tools()
    return {
        "protocol_version": client.protocol_version,
        "instructions": client.session.instructions,
        "tools": [
            {
                "name": tool.name,
                "description": tool.description,
                "input_schema": tool.input_schema,
            }
            for tool in tools.tools
        ],
    }


async def cmd_call(client, args):
    result = await client.call_tool(args.tool, args.tool_args)
    return tool_result(result)


async def cmd_poll(client, args):
    # The tool's retry_after_seconds is the only "not done yet": an error or a missing payload is never done.
    deadline = anyio.current_time() + args.timeout
    while True:
        output = await cmd_call(client, args)
        content = output["structured_content"]
        if output["is_error"]:
            return output
        if content is None:
            # not fail(): exiting inside the SDK's task groups surfaces as a traceback
            return {"error": f"{args.tool} returned no structured_content, so there is no status to poll: use call"}
        wait = content.get("retry_after_seconds")
        status = content.get("status")
        if wait is None or status in args.until:
            return output
        if anyio.current_time() + wait > deadline:
            return {**output, "still_waiting": f"still {status}: run the same command again to keep waiting"}
        await anyio.sleep(wait)


async def run_mcp(args, config, proxy):
    settings = mcp_settings(args, config)
    command = {"tools": cmd_tools, "call": cmd_call, "poll": cmd_poll}[args.command]
    auth = SurrogateAuth(
        load_credential_helper(settings["credential_helper"]),
        settings["connector"],
        httpx2.URL(settings["endpoint"]).host,
    )
    try:
        async with connect(settings, auth, proxy) as client:
            return await command(client, args)
    # the SDK's task groups wrap errors in ExceptionGroups
    except* NotConnected as group:
        fail(str(first_leaf(group)))
    except* TimeoutError:
        fail("timed out waiting for the server")
    except* MCPError as group:
        if auth.last_status == 401:
            fail(f"the server rejected the credential (HTTP 401), twice: the connection is missing or expired. {RECONNECT}")
        if auth.last_status == 403:
            fail(f"the server refused the request (HTTP 403): the connection lacks a permission it needs. {RECONNECT}")
        if auth.last_status == 429:
            fail("the server is rate limiting this connection (HTTP 429): wait a minute, then run the command again")
        error = first_leaf(group).error
        fail(f"server error {error.code}: {error.message}" + (f" ({error.data})" if error.data else ""))


# Presigned URLs carry their own authorization: no credential is attached, so it can never leave for another host.
def transfer_client(proxy):
    return httpx2.Client(proxy=proxy, trust_env=False, timeout=httpx2.Timeout(120.0))


def cmd_put(args, proxy):
    path = Path(args.file)
    if not path.is_file():
        fail(f"no file at {path}")
    content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
    with transfer_client(proxy) as http:
        response = http.put(args.url, content=path.read_bytes(), headers={"Content-Type": content_type})
    if response.is_error:
        fail(f"PUT returned HTTP {response.status_code}: if the URL expired, request a fresh one")
    return {"status": response.status_code, "bytes": path.stat().st_size}


def cmd_get(args, proxy):
    with transfer_client(proxy) as http:
        response = http.get(args.url)
    if response.is_error:
        fail(f"GET returned HTTP {response.status_code}: if the URL expired, request a fresh one")
    Path(args.file).write_bytes(response.content)
    return {"status": response.status_code, "bytes": len(response.content), "file": args.file}


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--endpoint", help="override config.json endpoint (or MCP_ENDPOINT)")
    parser.add_argument("--connector", help="override config.json connector (or MCP_CONNECTOR)")
    parser.add_argument("--proxy", help="egress proxy URL (default: config.json proxy, then HTTPS_PROXY)")
    parser.add_argument("--no-proxy", action="store_true", help="connect directly")
    commands = parser.add_subparsers(dest="command", required=True)

    commands.add_parser("tools", help="handshake, then print server instructions and tools")

    call = commands.add_parser("call", help="call any tool")
    call.add_argument("tool")
    call.add_argument("--args", dest="tool_args", type=json.loads, default={}, help="tool arguments as JSON")

    poll = commands.add_parser("poll", help="call a tool again after each retry_after_seconds it returns, until done")
    poll.add_argument("tool")
    poll.add_argument("--args", dest="tool_args", type=json.loads, default={}, help="tool arguments as JSON")
    poll.add_argument("--until", type=lambda value: value.split(","), default=[], help="statuses to stop on, comma-separated")
    poll.add_argument("--timeout", type=float, default=600, help="seconds to keep polling (exit 2 if still waiting)")

    put = commands.add_parser("put", help="upload a file to a presigned URL")
    put.add_argument("url")
    put.add_argument("file")

    get = commands.add_parser("get", help="download a presigned URL to a file")
    get.add_argument("url")
    get.add_argument("file")

    return parser.parse_args()


def main():
    args = parse_args()
    config = load_config()
    proxy = proxy_setting(args, config)
    if args.command == "put":
        output = cmd_put(args, proxy)
    elif args.command == "get":
        output = cmd_get(args, proxy)
    else:
        output = anyio.run(run_mcp, args, config, proxy)
    print(json.dumps(output, indent=2), flush=True)
    if output.get("is_error") or output.get("error"):
        sys.exit(1)
    if output.get("still_waiting"):
        sys.exit(2)


if __name__ == "__main__":
    main()
```
