Metadata-Version: 2.4
Name: tunc-mcp
Version: 0.1.1
Summary: MCP client for Tunc Orb (agent memory database), Tunc Art (artifact storage and private file sharing) and Tunc Doc (documents, spreadsheets, decks).
Author-email: TUNC LLC <hello@tunc.ai>
License: MIT
Project-URL: Homepage, https://tuncorb.com
Project-URL: Repository, https://github.com/TUNC-AI/tunc-mcp-python
Keywords: mcp,model-context-protocol,agent-memory,agent-database,memory,agent,agents,multi-agent,multi-agent-orchestration,artifact,artifacts,artifact-storage,file-sharing,private-links,storage,database,records,documents,spreadsheets,slide-decks,a2a,agent-to-agent,ai-agents,llm,tunc
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# tunc-mcp

**Agent memory, artifact storage, and document editing for AI agents — over MCP.**

A small, dependency-free MCP (Model Context Protocol) client in Python for three
hosted services that AI agents and multi-agent systems actually need:

| Service | What it is | MCP endpoint |
|---|---|---|
| **Tunc Orb** | **Agent memory database** — durable records, logs and structured state shared by every agent you run | `https://mcp.tuncorb.com/mcp` |
| **Tunc Art** | **Artifact storage and private file sharing** — agent-generated files behind short private links | `https://mcp.tuncart.com/mcp` |
| **Tunc Doc** | **Documents, spreadsheets and slide decks** — import/export DOCX, XLSX, PPTX, PDF | `https://mcp.tuncdoc.com/mcp` |

All three are also reachable over **A2A** (agent-to-agent) and plain **REST**, so
the same account works whether your agent speaks MCP, A2A, or HTTP.

## Why this exists

Most agent stacks lose state the moment a context window rolls over. Writes from
two agents at once silently clobber each other. Artifacts end up as files on
someone's laptop. This gives an agent three boring, reliable primitives instead:

- **Memory that survives the conversation.** Records persist across sessions,
  across agents, across models, with revision-guarded writes.
- **Artifacts with links you can send.** Upload a file, get a short private URL
  back. No bucket configuration.
- **Documents an agent can actually produce.** Real DOCX, XLSX and PPTX, not
  markdown pretending to be a report.

### Concurrency is the interesting part

`data_update` takes `if_revision`. Two agents writing the same record do not
race: the second gets a `revision_conflict`, re-reads, and retries. That turns a
lost-update bug — the classic multi-agent failure where a plausible but wrong
number survives — into a loud retry.

That is Orb's behaviour, and it is strict. Doc is different on purpose:
`doc_write`'s `base_revision` is a **merge base, not a lock**, so a stale write
usually merges instead of failing. See [Concurrency differs by service](#concurrency-differs-by-service).

## Install

```bash
pip install tunc-mcp
```

Python 3.9 or newer. No dependencies. Get an API key at
<https://tunchub.com/account/keys/new> — you can scope it read-only.

## Use

```python
from tunc_mcp import orb, art, doc

memory = orb()          # reads TUNC_API_KEY

# Every tool takes an `operation` that picks what it does. Call list_tools()
# once and read the real schemas rather than trusting an example.
#
# data_write  operation: create | append
# data_read   operation: shelves | list | get | log | search | status
# data_update operation: replace | patch        (needs if_revision)
# data_delete operation: record | entries | log (needs if_revision)

memory.call_tool("data_write", {
    "operation": "create",
    "name": "contacts/ada",
    "about": "Primary contact, Example Ltd",
    "value": {"email": "ada@example.com", "timezone": "Europe/London"},
})

record = memory.call_tool("data_read", {"operation": "get", "name": "contacts/ada"})
revision = record["structuredContent"]["revision"]

memory.call_tool("data_update", {
    "operation": "patch",
    "name": "contacts/ada",
    "if_revision": revision,
    "patch": [{"op": "replace", "path": "/timezone", "value": "Europe/Paris"}],
})

memory.call_tool("data_delete", {"operation": "record", "name": "contacts/ada", "if_revision": revision})
```

Artifacts — `art_write` takes `operation: create` and a `name`, and the result
keys the artifact by `id`:

```python
files = art()
stored = files.call_tool("art_write", {
    "operation": "create",
    "name": "quarterly-report.pdf",
    "mime_type": "application/pdf",
    "content_base64": base64_bytes,
})
artifact_id = stored["structuredContent"]["artifact"]["id"]

files.call_tool("art_read", {"operation": "get", "artifact_id": artifact_id})
files.call_tool("art_delete", {"artifact_id": artifact_id})
```

Deleting **tombstones, it does not erase the record**. After `art_delete`, a
`get` still succeeds and returns the artifact with `status: "deleted"`,
`availability: "deleted"` and `viewer_url: null`; it disappears from `list`, and
the content URL answers `401`. So do not test for a delete by expecting `get` to
fail — check `status`, or check that the id is gone from the listing:

```python
after = files.call_tool("art_read", {"operation": "get", "artifact_id": artifact_id})
assert after["structuredContent"]["artifact"]["status"] == "deleted"
```

Documents — `doc_create` takes a `title` and a `markdown` body (`kind="deck"`
takes `html` instead, `kind="sheet"` takes `values`), and returns the document
under `result.doc.id`; every other doc tool addresses it with `doc`. The
server's schema lists only `title` as required, which is wrong — omit `markdown`
for a doc and you get `invalid_arguments`:

```python
docs = doc()
made = docs.call_tool("doc_create", {"title": "Q4 summary", "markdown": "# Q4\n\nRevenue up 12%."})
doc_id = made["structuredContent"]["result"]["doc"]["id"]

docs.call_tool("doc_read", {"doc": doc_id})
docs.call_tool("doc_delete", {"doc": doc_id})
```

Discover what any service offers:

```python
for tool in orb().list_tools():
    print(tool["name"], tool.get("inputSchema", {}).get("required"))
```

## What comes back

`call_tool()` returns the server's MCP result unchanged:

```python
{
    "content": [{"type": "text", "text": "<json string>"}],
    "structuredContent": {"...": "..."},
    "isError": False,
}
```

The same payload usually arrives **twice** — parsed as `structuredContent`, and
again serialised into `content[0].text`. Use `structuredContent`. If you only
want the text, `call_text()` unwraps it:

```python
text = memory.call_text("data_read", {"operation": "get", "name": "contacts/ada"})
```

This is the single easiest thing to get wrong: assert on
`content[0].text` expecting a dict and every check fails for reasons that look
like server bugs. Errors are reported the same way — `isError: True` with an
`error.code` inside the payload (`invalid_arguments`, `not_found`,
`revision_conflict`, `doc_conflict`), not as an exception, unless the HTTP
status itself was bad.

## Concurrency differs by service

Three services, two different safety models. Do not write one helper for both.

| Service | Write guard | Stale write |
|---|---|---|
| **Orb** `data_update` / `data_delete` | `if_revision` — compare and swap | `revision_conflict`; nothing is written |
| **Doc** `doc_write` | `base_revision` — merge base | usually **merges and succeeds**; `doc_conflict` only when the edits actually collide |

So "always pass `if_revision` and retry on conflict" is correct for Orb, and
wrong for Doc: a Doc write with a stale base is how you intentionally merge into
someone else's newer text. Read the doc, write with the revision you read, and
keep the bytes you did not mean to change.

## CLI


```bash
export TUNC_API_KEY=...

tunc-mcp services
tunc-mcp tools --service orb
tunc-mcp call data_read '{"operation": "get", "name": "contacts/ada"}' --service orb
```

## Options

```python
memory = orb(
    api_key="...",                      # or TUNC_API_KEY in the environment
    endpoint="https://mcp.tuncorb.com/mcp",  # override: staging, a proxy, a local mock
)
```

- `api_key` — defaults to `TUNC_API_KEY`. Checked when the client is constructed.
- `endpoint` — replaces the built-in URL for that service, which is how you point
  it at a test server.
- `service` — `"orb"`, `"art"` or `"doc"`, if you construct `TuncMcpClient`
  directly instead of using `orb()` / `art()` / `doc()`.

`SERVERS` is the map of default endpoints. `connect(key)` returns all three
clients at once.

## Wire it into an MCP client

Any MCP-capable host works. Point it at the endpoint and pass the key as a
bearer header. For a Python host, the usual shape is:

```python
from tunc_mcp import orb
client = orb()
tools = client.list_tools()
```

## OAuth instead of a key

The servers accept a resource-bound OAuth token as well as an API key. That
matters for Doc: **`mcp.tuncdoc.com` advertises the same scope names as Orb
(`orb.read`, `orb.write`, `orb.delete`)**, so a token without a resource binding
defaults to the Orb audience and is rejected by Doc with "not scoped for this
service". Include the resource when you request the device grant:

```
resource=https://mcp.tuncdoc.com/mcp
```

```python
TuncMcpClient(service="doc", api_key=device_access_token)
```

Revoking that token (`POST /oauth/revoke`) returns `200`, but the access token
keeps working until it expires — about 15 minutes. Revocation kills the refresh
path, not an access token that has already been issued, so do not treat a
successful revoke as proof that the credential is dead this second.

## Agent-to-agent

Every service publishes an A2A agent card, so agents that speak A2A can discover
and call them without a human in the loop:

- <https://tuncorb.com/.well-known/agent-card.json>
- <https://tuncart.com/.well-known/agent-card.json>
- <https://tuncdoc.com/.well-known/agent-card.json>

## What this package does not do

It is a client. It does not host anything, and it does not bundle an agent
runtime. If you want the workspace these services belong to — a multiplayer chat
where people and agents work together — that is a desktop and mobile app:
<https://tunchub.com>.

## Errors

Everything raises `TuncMcpError` with a `status`, a `code` and the server's
message. A `401` means the key is missing, revoked, or not scoped for that
service; the message says which.

## Tests

```bash
pip install pytest
python -m pytest -q                      # offline, no key needed
TUNC_API_KEY=tunc_... python -m pytest tests/test_live.py -q   # against the live servers
```

`tests/test_live.py` holds the contract checks that a mock cannot make — that
Orb refuses a stale write, that Art tombstones rather than erases, that Doc
needs `markdown` to create a doc, and that Doc merges a stale `base_revision`
instead of refusing it. Those are exactly the behaviours that mock servers got
wrong here, three times, so they skip themselves unless a real key is present.

## 中文

**面向 AI 智能体的记忆数据库、制品存储与文档编辑 —— 通过 MCP 接入。**

`tunc-mcp` 是一个零依赖的 Python MCP 客户端，连接三个托管服务：

| 服务 | 用途 | 接入点 |
|---|---|---|
| **Tunc Orb** | **智能体记忆数据库** —— 持久保存记录、日志与结构化状态，可在所有智能体之间共享 | `https://mcp.tuncorb.com/mcp` |
| **Tunc Art** | **制品存储与文件分享** —— 保存智能体生成的文件，返回私密短链接 | `https://mcp.tuncart.com/mcp` |
| **Tunc Doc** | **文档、表格与幻灯片** —— 可导入导出 DOCX、XLSX、PPTX、PDF | `https://mcp.tuncdoc.com/mcp` |

三个服务同时支持 **MCP**、**A2A**（智能体间通信）与 **REST**，同一个账号即可通用。

```bash
pip install tunc-mcp
```

API 密钥：<https://tunchub.com/account/keys/new>（可设为只读）。

### 并发写入

`data_update` 接受 `if_revision`。两个智能体写同一条记录时不会互相覆盖：后到的写入收到 `revision_conflict`，重新读取后重试。这把多智能体最常见的“静默丢更新”故障，变成一个可以被发现的错误。

注意两个与直觉不同的行为：**Doc** 的 `doc_write` 把 `base_revision` 当作合并基线而不是锁，过期版本通常会被合并而不是报错，只有在编辑内容真正冲突时才返回 `doc_conflict`；**Art** 的删除是标记删除，删除之后 `get` 仍然能读到该记录，但 `status` 为 `deleted`、`viewer_url` 为空、内容链接返回 `401`。

完整的多人协作工作空间（人与多个智能体共享同一实时对话）见 <https://tunchub.com>。

## License

MIT © TUNC LLC
