Skip to main content
Glama
piko-crm-mcp

piko-crm-mcp

Official
by Prysai
README.md
<p align="center"><img src="docs/assets/banner.png" alt="piko-crm-mcp — CRM + MCP + auto-watch" width="100%"></p>

<p align="center">
<a href="https://github.com/Prysai/piko-crm-mcp/actions/workflows/test.yml"><img alt="tests" src="https://github.com/Prysai/piko-crm-mcp/actions/workflows/test.yml/badge.svg"></a>
<a href="LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue"></a>
<img alt="Python 3.10+" src="https://img.shields.io/badge/python-3.10%2B-blue">
<img alt="No runtime dependencies" src="https://img.shields.io/badge/runtime%20deps-0-brightgreen">
<a href="https://doi.org/10.5281/zenodo.24729210"><img alt="Paper DOI" src="https://zenodo.org/badge/DOI/10.5281/zenodo.24729210.svg"></a>
</p>

<p align="center"><b>Let an AI agent answer your inbox and keep your CRM up to date — without ever letting it act behind your back.</b><br>
<a href="#quick-start">Quick start</a> · <a href="#safety-model">Safety model</a> · <a href="#full-delegation">Full delegation</a> · <a href="paper/">Paper</a> · <a href="README.zh-CN.md">中文</a></p>

Three parts that close one loop:

* **CRM** — a small SQLite reference CRM: workspaces, roles, contacts with channel accounts, organizations, deals in
  stages, tasks, notes (private or marked for auto-watch).
* **MCP** — a standard Model Context Protocol server (stdio, no dependencies). Every agent connection has its own grant.
  Writes are dry-run, explained in plain words and approved by a person — or, if you opt in, run on their own with
  undo, limits and red lines.
* **Auto-watch** — a channel- and model-agnostic loop that reads new messages, looks the person up in CRM, drafts a
  reply strictly from the owner's written rules, and records the person back into CRM.

<p align="center"><img src="docs/assets/loop.png" alt="The loop: inbox → auto-watch ⇄ CRM ⇄ MCP agents, a person decides the exceptions" width="100%"></p>

It is extracted from [Piko](https://piko.prysai.com), where the same mechanism connects the Piko apps' auto-watch to a
shared CRM, and it is the reference implementation of the paper
[*Delegation Without Approval*](paper/) ([DOI 10.5281/zenodo.24729210](https://doi.org/10.5281/zenodo.24729210)).
Piko's apps, accounts and hosted service are not part of it.

## Safety model

The point of this project is what an agent **cannot** do.

| | Guarantee | Where |
| --- | --- | --- |
| Access | Each agent/device connection has its own grant (`read`/`write`, plus `watch` and `capture` for auto-watch). Effective access is the smaller of grant and role, re-checked on every call. | `gateway.py`, `crm.py` |
| Confirmed writes | A write tool never writes. It is planned, **executed for real inside a SAVEPOINT and rolled back** (so it fails now, not after approval), described field by field, stored for 10 minutes for that session only, re-checked and applied at most once after a person accepts. There is no `confirm` tool. | `gateway.py` |
| Full delegation (opt-in) | Ordinary single-record writes run without a prompt, each with a before/after snapshot; `undo-op` restores field by field and keeps your later edits. 15 writes/hour; more than 4 in 120 s freezes the session. Stage moves, large value changes, secrets and injection markers still go to a person. One daily digest. | `delegation.py` |
| Approval channel | Approval goes to the person through MCP *elicitation*. Clients without elicitation do not see write tools at all (unless you opt in to terminal approval). | `mcp_server.py` |
| Auto-watch lookup | Off until the workspace enables it *and* the connection has `watch`. Matches by account → phone → e-mail; by name only if both workspace and rule allow; ambiguous → nobody. Returns facts only, no private notes; logs no handles, numbers or names. | `watch.py` |
| Auto-watch capture | Off until the workspace enables it *and* the connection has `capture`. Only creates a contact/inquiry, fills **empty** account/phone/e-mail, adds one note. Never edits or deletes, never matches by name. Unsure cases wait for a person. Every capture is undoable; a person you deleted is never recreated. 120 an hour per connection. | `watch.py` |
| Prompt order | Fixed: safety floor → the owner's rules → fenced *data* (knowledge, CRM facts, the one incoming message). Data cannot close its block or open a rules block. Each reply sees only the newest message, no history. | `autowatch.py` |
| Secrets | Incoming messages with card numbers, ID numbers or codes go to a person unanswered. Drafts that contain them, or mention passwords/codes/card details at all, are not sent. Quotes and summaries holding them are never stored. | `safety.py`, `autowatch.py` |
| Rate limits | 60 tool calls/minute per connection; auto-watch 30 replies/hour per rule (configurable up to 120) and a minimum gap per conversation. Over the limit, messages wait. | `gateway.py`, `autowatch.py` |
| Hand-off | Per message; the next message in that conversation is answered normally. A person can stop a conversation for good. | `autowatch.py` |
| Send window | Optionally hold each reply (`--hold-seconds 180`), re-check it for secrets and for prices the knowledge and CRM facts do not contain, and let a person cancel it. | `autowatch.py` |
| Dry run | The auto-watch loop only drafts until you pass `--send`; a dry run writes nothing to CRM. | `autowatch.py` |

See [SECURITY.md](SECURITY.md) for the threat model and how to report a problem.

## Quick start

```bash
pip install git+https://github.com/<owner>/piko-crm-mcp
piko-crm demo --db ~/piko-crm-demo.db
```

`demo` creates a sample workspace with auto-watch enabled and two connections: `demo` (an agent with confirmed writes)
and `watcher` (auto-watch with lookup and capture). It prints the commands to run.

**Connect an agent over MCP** — add the printed `serve` command to your MCP client's server list
(see [`examples/mcp_client_config.json`](examples/mcp_client_config.json)), then ask: *"Which deals are open? Add a task
to call Fang Wang back on Friday."* The task is only written after you accept the approval the client shows you.

**Try auto-watch** — run the printed `watch` command. It reads [`examples/inbox.jsonl`](examples/inbox.jsonl), answers
from [`examples/rule.json`](examples/rule.json) with a knowledge-only demo responder, and prints drafts (dry run).
Add `--send` to send and record into CRM, and `--hold-seconds 180` to keep a window to take replies back.

<p align="center"><img src="docs/assets/demo.png" alt="Terminal: auto-watch drafts, a sensitive message handed to a person, then the daily digest" width="100%"></p>

Review what auto-watch recorded:

```bash
piko-crm captures --db … --workspace … --user me            # created / merged / pending
piko-crm resolve  --db … --workspace … --user me <id> merge --contact <contactID>
piko-crm undo     --db … --workspace … --user me <id>
```

## Full delegation

<p align="center"><img src="docs/assets/modes.png" alt="Confirm every write (default) versus reversible full delegation (opt-in)" width="100%"></p>

Confirmation is the default. When you trust an agent with routine work, switch *that one connection* to full delegation
— the four mechanisms of the paper's appendix A come with it:

```bash
piko-crm connect --db … --workspace … --user me --session assistant --access write --mode delegated \
                 [--max-writes-hour 15] [--burst-max 4] [--burst-window 120] [--freeze 900] \
                 [--deal-delta-pct 20] [--deal-delta-abs 1000]
piko-crm digest  --db … --workspace … --user me --since 24h      # once a day: what ran, what waits for you
piko-crm undo-op --db … --workspace … --user me <opID>            # restores field by field; your later edits stay
piko-crm confirm --db … --workspace … --user me --session assistant <operationID>   # approve a held red-line write
```

Over MCP the delegated connection simply sees its write tools work; a red-line write comes back as `pending` (or, if the
client supports elicitation, is put in front of you right away). `piko-crm disconnect` stops delegation at once and
cancels everything waiting.

### Bring your own channel and model

The loop is two small interfaces:

```python
from piko_crm_mcp.autowatch import Adapter, AutoWatch, CrmLink, Incoming, Responder, Rule

class MyInbox(Adapter):
    def poll(self): ...                     # → [Incoming(conversation, channel, messages, handle, name)]
    def send(self, conversation, text): ... # → True only when the reply is verified as sent

class MyModel(Responder):
    def respond(self, prompt): ...          # prompt["system"], prompt["text"] → {"reply", "handoff", "crm"}
```

Or keep it out of process: `--responder "your-command"` runs any program with the prompt as JSON on stdin and reads
the draft JSON from stdout, so this package depends on no model provider.

## MCP tools

| Tool | Kind | Shown when |
| --- | --- | --- |
| `crm.search`, `crm.get`, `crm.tasks`, `crm.pipeline` | read | the role may view that module |
| `crm.create_contact`, `crm.update_contact`, `crm.create_organization`, `crm.add_note`, `crm.add_task`, `crm.update_task`, `crm.create_deal`, `crm.update_deal`, `crm.move_deal` | write | write grant and role allow it; confirmed by a person, or delegated with undo |
| `crm.watch_lookup` | read | `watch` grant and workspace `watchAccess` |
| `crm.watch_capture` | narrow direct write | `capture` grant and workspace `watchCapture` |

Results are compact (≤ 50 rows with paging, long text cut, ids mapped to names the caller may see). Approval texts
come in English, Simplified and Traditional Chinese.

## Using the library directly

```python
from piko_crm_mcp import Crm, Gateway, Store

crm = Crm(Store("crm.db")); gw = Gateway(crm); me = {"id": "alice"}
op = gw.prepare(me, "laptop", space, "crm.move_deal", {"id": deal_id, "stage": "Proposal"}, lang="zh-Hans")
print(op["review"])     # 把商机「Gift boxes」从「New」移到「Proposal」
gw.confirm(me, "laptop", space, op["operationID"])     # only after a person says yes
```

Full delegation from Python: `Delegation(gw).execute(...)`, `.undo_op(...)`, `.digest(...)`.

To guard your own data store, keep `gateway.py` / `watch.py` / `delegation.py` and implement the `Crm` methods they call so that writes
accept a caller-owned transaction.

## Development

```bash
python -m venv .venv && .venv/bin/pip install -e '.[test]'
.venv/bin/pytest -q
```

Python 3.10+, no runtime dependencies. The MCP server negotiates protocol versions `2025-11-25`, `2025-06-18` and
`2025-03-26` and has been exercised with the official MCP Python client, including elicitation.

**Not included** (present in the production system this comes from): encryption of record bodies at rest, keyed
hashing of phone numbers and handles, custom permission groups, invitations, imports, dashboards, and the channel
readers that drive real messaging sites. Record bodies in the reference store are plain JSON: protect the database
file accordingly.

## Research

This repository implements **[Delegation Without Approval](paper/)** (Piko Research 2026-03,
[DOI 10.5281/zenodo.24729210](https://doi.org/10.5281/zenodo.24729210)): the paper's experiments ran against `v0.2.0`,
and its appendix A is implemented from `v0.3.0`. The paper builds on
[PESA](https://piko.prysai.com/research/pesa). To cite either the software or the paper, use GitHub's
*Cite this repository* button ([`CITATION.cff`](CITATION.cff)).

## Roadmap

- Encrypted record bodies and keyed hashing of handles and numbers, as in production.
- Channel adapters maintained as separate packages, so the core stays dependency-free.
- A small web view for the daily digest and pending decisions.
- Packaging on PyPI.

Ideas and pull requests are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).

## License and trademarks

Code: [Apache License 2.0](LICENSE). The names "Piko" and "Prysai" and the Piko logo are not licensed under it; you
may say your project is based on piko-crm-mcp, but please do not present a fork as Piko.

[中文说明](README.zh-CN.md)