@speakquery/mycel 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +498 -2
  3. package/dashboard/index.html +1595 -0
  4. package/dist/a2a-client.d.ts +104 -0
  5. package/dist/a2a-client.js +108 -0
  6. package/dist/a2a-client.js.map +1 -0
  7. package/dist/a2a-server.d.ts +32 -0
  8. package/dist/a2a-server.js +218 -0
  9. package/dist/a2a-server.js.map +1 -0
  10. package/dist/adapter.d.ts +44 -0
  11. package/dist/adapter.js +61 -0
  12. package/dist/adapter.js.map +1 -0
  13. package/dist/bench.d.ts +40 -0
  14. package/dist/bench.js +208 -0
  15. package/dist/bench.js.map +1 -0
  16. package/dist/catalog.d.ts +69 -0
  17. package/dist/catalog.js +206 -0
  18. package/dist/catalog.js.map +1 -0
  19. package/dist/cli.d.ts +2 -0
  20. package/dist/cli.js +370 -0
  21. package/dist/cli.js.map +1 -0
  22. package/dist/config.d.ts +290 -0
  23. package/dist/config.js +192 -0
  24. package/dist/config.js.map +1 -0
  25. package/dist/contracts.d.ts +26 -0
  26. package/dist/contracts.js +67 -0
  27. package/dist/contracts.js.map +1 -0
  28. package/dist/core.d.ts +217 -0
  29. package/dist/core.js +536 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/http.d.ts +22 -0
  32. package/dist/http.js +264 -0
  33. package/dist/http.js.map +1 -0
  34. package/dist/importer.d.ts +37 -0
  35. package/dist/importer.js +137 -0
  36. package/dist/importer.js.map +1 -0
  37. package/dist/index.d.ts +19 -0
  38. package/dist/index.js +19 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/jobs.d.ts +112 -0
  41. package/dist/jobs.js +324 -0
  42. package/dist/jobs.js.map +1 -0
  43. package/dist/meta.d.ts +13 -0
  44. package/dist/meta.js +120 -0
  45. package/dist/meta.js.map +1 -0
  46. package/dist/models.d.ts +38 -0
  47. package/dist/models.js +75 -0
  48. package/dist/models.js.map +1 -0
  49. package/dist/oauth.d.ts +69 -0
  50. package/dist/oauth.js +160 -0
  51. package/dist/oauth.js.map +1 -0
  52. package/dist/policy.d.ts +90 -0
  53. package/dist/policy.js +205 -0
  54. package/dist/policy.js.map +1 -0
  55. package/dist/recorder.d.ts +88 -0
  56. package/dist/recorder.js +194 -0
  57. package/dist/recorder.js.map +1 -0
  58. package/dist/refs.d.ts +128 -0
  59. package/dist/refs.js +455 -0
  60. package/dist/refs.js.map +1 -0
  61. package/dist/sandbox.d.ts +30 -0
  62. package/dist/sandbox.js +176 -0
  63. package/dist/sandbox.js.map +1 -0
  64. package/dist/secrets.d.ts +20 -0
  65. package/dist/secrets.js +81 -0
  66. package/dist/secrets.js.map +1 -0
  67. package/dist/server.d.ts +13 -0
  68. package/dist/server.js +100 -0
  69. package/dist/server.js.map +1 -0
  70. package/dist/tokens.d.ts +45 -0
  71. package/dist/tokens.js +84 -0
  72. package/dist/tokens.js.map +1 -0
  73. package/dist/upstream.d.ts +110 -0
  74. package/dist/upstream.js +204 -0
  75. package/dist/upstream.js.map +1 -0
  76. package/package.json +61 -4
package/README.md CHANGED
@@ -1,3 +1,499 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <a href="https://mycel.speakquery.ai/#film"><img src="media/mycel-launch-preview.gif" alt="Mycel launch film — click to watch the full 90-second video" width="860"></a>
4
+
5
+ <sub>The film is a dramatization. Its 500 MB video example with transcript uses illustrative data (video/data.json); today the built-in video digest returns metadata and keyframe refs, no transcript. The film's final frame shows an outdated command; the correct one is <code>npx @speakquery/mycel init</code> (the package is published as @speakquery/mycel).</sub>
6
+
7
+ # Mycel
8
+
9
+ ### One layer between your agents and everything they touch.
10
+
11
+ **A drop-in MCP gateway + agent-to-agent mesh.**
12
+ Your existing MCP setup — minus the context bloat, the round-trip storms and the blind trust.
13
+
14
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-3DFFB0?style=flat-square)](LICENSE)
15
+ [![Node ≥ 20](https://img.shields.io/badge/node-%E2%89%A520-3DFFB0?style=flat-square)](package.json)
16
+ [![MCP compatible](https://img.shields.io/badge/MCP-compatible-3DFFB0?style=flat-square)](https://modelcontextprotocol.io)
17
+ [![A2A v0.3](https://img.shields.io/badge/A2A-v0.3-3DFFB0?style=flat-square)](https://a2a-protocol.org)
18
+ [![Tests](https://img.shields.io/badge/tests-47%20passing-3DFFB0?style=flat-square)](tests)
19
+
20
+ [**▶ Watch the 90-second film**](https://mycel.speakquery.ai/#film) · [Quickstart](#-quickstart) · [Benchmark](#-the-numbers) · [How it works](#-how-it-works) · [All 20 features](#-features) · [Docs](docs/)
21
+
22
+ </div>
23
+
24
+ ---
25
+
26
+ ```bash
27
+ mycel init # finds your Claude / Cursor / VS Code / Windsurf MCP servers and imports them
28
+ ```
29
+
30
+ <sub>Install first: `npm install -g @speakquery/mycel` (macOS, Linux, Windows, Node 20+). The command is `mycel`.</sub>
31
+
32
+ > **Is Mycel a new protocol?** No — and that's the point. Mycel speaks plain **MCP** to your client and plain **MCP** to your servers, so nothing has to change on either side. It also speaks **A2A** so other agents can use your tools under the same rules. Think of it as the missing middle layer both protocols assumed someone else would build. Tools work without client changes; resources and prompts parity is not yet verified.
33
+
34
+ > **Big MCP results stay local.** Your agent reads the line it needs and passes the file to the next tool by reference, instead of pushing 20,000 rows through the model. Code Mode lets it do a multi-step chore in one script.
35
+
36
+ ### Measured in a real Claude Code session (single run, n=1)
37
+
38
+ Task: "find the one rare row in a 20,000-row CSV". Both arms found the right row. Claude Code 2.1.316, model `claude-haiku-5-5`, built-in tools off.
39
+
40
+ | Condition | Direct MCP | Through Mycel |
41
+ |---|---:|---:|
42
+ | Cache off | 12 turns · 34.5 s · 124,770 input + 5,219 output tokens (CLI est. $0.0151) | **4 turns · 6.6 s · 25,915 input + 574 output (CLI est. $0.0029)** |
43
+ | Cache on | 7 turns · 22.6 s | **5 turns · 7.0 s** |
44
+
45
+ This is one run per cell, not a statistical result. To be fair about the other side:
46
+
47
+ - **Small files cost about one extra turn.** On "find a decision in a small file" (cache on) direct took 3 turns / 5.2 s and Mycel 4 turns / 6.0 s.
48
+ - **Write tasks stopped for approval** in a non-interactive client. That is by design; pre-approve writes for headless use (see [Configuration → policy](docs/configuration.md#policy)).
49
+ - In non-interactive clients (no MCP elicitation) nobody can approve inline. Pre-approve with a rule above the approving rule, e.g. `policy: [{ match: { tool: "github.add_label" }, action: allow }]` or `{ match: { server: "github", effect: write }, action: allow }`. Rules are first-match-wins.
50
+ - Protocol for running your own comparison: [docs/benchmark-protocol.md](docs/benchmark-protocol.md).
51
+
52
+ <p align="center"><img src="media/anim-counter.svg" alt="Measured results: -94% tool definitions with 8 servers, 204k to 1.2k tokens with 420 tools, 131k to 187 tokens for a 20,000-row CSV, 17 tool calls in 1 round trip" width="860"></p>
53
+
54
+ <p align="center"><b>▶ Try the interactive savings calculator and 3D view → <a href="https://mycel.speakquery.ai/#calculator">https://mycel.speakquery.ai/#calculator</a></b></p>
55
+ <p align="center"><a href="https://mycel.speakquery.ai/#why"><img src="media/demo-3d.gif" width="49%" alt="3D view: direct MCP fills the context window, Mycel keeps it thin"></a> <a href="https://mycel.speakquery.ai/#calculator"><img src="media/demo-calculator.gif" width="49%" alt="Savings calculator: move the sliders, watch the savings"></a></p>
56
+
57
+ <h1 align="center">Why use it?</h1>
58
+
59
+ <h3 align="center">Because every agent with many tools drowns in its own plumbing.</h3>
60
+
61
+ <p align="center"><img src="media/anim-context.svg" alt="Animated context window: adding servers fills the direct bar with red blocks up to 17.8k tokens; a 420-tool setup needs about 204k tokens and fills the 200k window, while Mycel stays a thin 1k slice" width="860"></p>
62
+
63
+ - 🧠 **Context bloat.** In clients that send every tool definition on every turn, that is 17.8k tokens for 8 servers and ~204k for 420 tools. Those are tool-definition tokens (~4 chars per token), reproducible offline: [examples/full-scale](examples/full-scale). Less room for your actual work, worse tool choice. Check your client: Claude Code and recent Cursor load tool descriptions on demand.
64
+ - 🚚 **Everything flows through the model.** 10,000 rows from tool A to tool B means 10,000 rows in the prompt.
65
+ - 🔁 **Round-trip storms.** A 17-step chore means up to 17 inference turns when the client makes one tool call per turn.
66
+ - 🎭 **Blind trust.** A web page can tell your agent to write to disk or send your keys; a server can silently rewrite a tool description.
67
+ - 🎬 🔑 🕳️ **No home for long jobs, no scoped delegation, no black box.** Video renders time out mid-call, sub-agents inherit every key, and nobody can see what the agent did or what it cost.
68
+
69
+ <h1 align="center">What do you gain?</h1>
70
+
71
+ <h3 align="center">Fewer round trips. Big data stays out of the prompt. Unsafe actions get stopped.</h3>
72
+
73
+ <p align="center"><img src="media/anim-roundtrips.svg" alt="Animated comparison: 17 model round trips with direct MCP versus 1 round trip when Mycel Code Mode runs the 17 calls inside its sandbox" width="860"></p>
74
+
75
+ - ⚡ **17 calls, 1 round trip.** The model writes one small script; Mycel runs it in a WebAssembly sandbox and returns only the result (about +0.4 ms on a Mac, +1 ms in CI (Ubuntu, Windows); median of 15 local calls). 17 tool calls in 1 model round trip. A client that makes one tool call per turn needs 17 turns; an efficient direct path using batch tools (read_multiple_files) needs about 3. Code Mode assumes the model writes a working script first time; not yet measured with a live model.
76
+ - 📦 **Refs instead of payloads.** A 20,000-row CSV becomes a reference plus a digest: 131k tokens → 187. The model can still ask for rows or hand the ref to another tool.
77
+ - 🛡️ **Safe by default.** Untrusted content can't trigger a write without approval, secrets never enter the model's context, and changed tool definitions are blocked.
78
+ - 👁️ **Everything is recorded.** Per-call spans, budgets, approvals and a live dashboard; sub-agents get narrowed capability tokens, never your keys.
79
+
80
+ <p align="center"><img src="media/anim-guard.svg" alt="Animated: an untrusted web page payload telling the agent to write to ~/.ssh is stopped by a Mycel shield with approval required" width="860"></p>
81
+
82
+ <h1 align="center">How much do you save?</h1>
83
+
84
+ <h3 align="center">1–2 small servers: it costs more. 8 servers (eager loading): ~94%.</h3>
85
+
86
+ <p align="center"><img src="media/chart-scaling.svg" alt="Line chart: direct MCP tool definitions grow from 1.1k to 17.8k tokens across 1 to 8 servers while Mycel stays near 1k; break-even is around 3 servers" width="860"></p>
87
+
88
+ - 📉 **8 servers: 17.8k → 1.0k tokens per turn (−94%)**, and a 30-turn session drops from 534k to ~31k. This applies where the client sends every definition each turn; it is not measured on Claude Code or Cursor, which load tools on demand.
89
+ - 🧰 **Big setups (technical):** 9 servers with Canva is 44.5k → 1.05k. The 99.4% figure is for 420 tools loaded up front; see [the technical note](#at-full-scale-420-tools-technical).
90
+ - 🔁 **Reproducible:** the −94% with 8 servers is reproducible: examples/field-test (CI runs it on Ubuntu and Windows).
91
+ - 📄 **Big results:** a 20,000-row CSV is 131k → 187 tokens.
92
+ - ⚖️ **The honest part:** with 1–2 small servers Mycel costs more context (about 58% more on a 4-tool catalog with a real tokenizer). Do not use it for that; use it for refs, Code Mode or the safety layer. Details: [Do you need Mycel?](#-do-you-need-mycel)
93
+
94
+ ## 👥 Who is it for?
95
+
96
+ Four kinds of users, each with an honest status. Only the last two have measurements behind them.
97
+
98
+ ### 🎬 1. AI video, voice-over and content creators running 5–6 agents
99
+ **Status: designed for; end-to-end not yet tested — pilot wanted.**
100
+ - **Pain:** media passed around as base64, renders that time out mid-call, every agent holding every key, a loop that quietly spends money.
101
+ - **Scenario:** servers are Higgsfield (image/video), Canva, a TTS server and storage. A script agent writes; an image agent generates, and the result is a `ref://` with a keyframe digest, not base64. The video render runs as a **job** (progress, cancel, retry) and takes the image ref as input. A per-job **budget cap** and an **approval** gate the paid calls. Each agent gets a **capability token** with only its own tools. If a provider accepts a job and the reply is lost, the job is marked `unknown` and nothing is paid twice.
102
+
103
+ ### 📣 2. AI editors and content/marketing teams
104
+ **Status: partly tested (Canva read calls through OAuth); publishing flows not yet tested.**
105
+ - **Pain:** designs, docs and brand assets across many tools, and agents that can publish or send without a human looking.
106
+ - **Scenario:** Canva, a docs server and storage. The agent finds designs with `mycel_search` and reads assets by ref. Any publish or send is an `external` effect: it needs approval (inline or `mycel approve`), and a per-day budget caps spend. The flight recorder shows what went out.
107
+
108
+ ### 🔬 3. Researchers and data/science work
109
+ **Status: measured (CSV, n=1).**
110
+ - **Pain:** big CSV/SQL results and PDFs flowing through the prompt.
111
+ - **Scenario A (measured):** find the one rare row in a 20,000-row CSV. In a real Claude Code session (single run, cache off) direct took 12 turns / 34.5 s, Mycel 4 turns / 6.6 s. The agent greps the ref and reads only the line it needs.
112
+ - **Scenario B (designed, not measured):** search arXiv, read papers by ref, hand the ref to a summarising tool.
113
+
114
+ ### 🧑‍💻 4. Developers with many MCP servers
115
+ **Status: measured (field test, 8 servers, CI).**
116
+ - **Pain:** git, filesystem, browser/Playwright, a database and docs (e.g. context7) in a client or agent framework that sends every tool definition up front.
117
+ - **Scenario:** 8 servers, 80 tools: 17.8k → 1.0k definition tokens (chars/4). "Read 15 files, decide, write" runs as one Code Mode script. An untrusted page that tries `write_file` is blocked pending approval.
118
+ - **When NOT for you:** 1–2 small servers (Mycel costs more context there), or Claude Code/Cursor if all you want is definition savings.
119
+
120
+ **Run one of these and tell us:** open an issue with your numbers (see [docs/benchmark-protocol.md](docs/benchmark-protocol.md)).
121
+
122
+ ---
123
+
124
+ ## 📊 The numbers
125
+
126
+ Measured by `mycel bench` — a reproducible in-process benchmark with 12 realistic servers (GitHub, Slack, Gmail, Calendar, Notion, Linear, Postgres, filesystem, browser, Drive, an AI media studio, Stripe test mode). Token counts use the same estimator (≈ 4 chars/token) on both sides.
127
+
128
+ | Scenario | Direct MCP | Through Mycel | Saved |
129
+ |---|---:|---:|---:|
130
+ | Tool definitions in context (167 tools) | **34.8k** tokens | **1.1k** tokens | **96.7%** |
131
+ | *"Label every stale issue"* (20 of 40) | 21 round trips · 6,071 tokens (computed, not a recorded session) | **1 round trip** · 77 tokens | **98.7%** |
132
+ | 5,000-row SQL result | 29.7k tokens | 156 tokens (digest + ref) | **99.5%** |
133
+ | 8 s 720p video (3.1 MB) | 1,068k tokens as base64 (won't fit) | 117 tokens (metadata + 3 keyframe refs) | **>99.9%** |
134
+ | Tool search, offline BM25 (20 English queries; see [search quality](#search-quality)) | — | top-1 **18/20** · top-3 **20/20** | — |
135
+
136
+ <sub>Methodology & caveats: [`src/bench.ts`](src/bench.ts). "Direct" counts only what the model must read; it ignores prompt caching, which lowers cost (not context size) for the direct case. The direct side of the 21-round-trip row is computed, not a recorded session. The offline index is English-only; see [search quality](#search-quality).</sub>
137
+
138
+ ## 💰 What you actually save — worked examples
139
+
140
+ In a client that sends every tool definition on every turn, direct MCP re-sends all of them each time; Mycel stays flat at ~1k tokens. All numbers below are measured (see [Do you need Mycel?](#-do-you-need-mycel) and the [field test](#-field-test-8-real-mcp-servers)), except the dollar line, which is an illustrative assumption.
141
+
142
+ ### 🖱️ Example 1: A client that sends every tool definition each turn: 8 servers, 30 turns
143
+
144
+ You connect 8 servers (80 tools). A client that sends all 80 definitions (**17.8k tokens**) with every turn spends **17.8k × 30 = 534k tokens** on definitions alone over 30 turns. Through Mycel the model sees ~1.0k tokens per turn: **1.0k × 30 ≈ 31k**. This is arithmetic (17.8k × 30), not a recorded session. Clients that load tools on demand spend less; see [Do you need Mycel?](#-do-you-need-mycel).
145
+
146
+ <p align="center"><img src="media/chart-conversation.svg" alt="Cumulative tokens over a 30-turn conversation with 8 servers: 534k direct versus 31k through Mycel" width="860"></p>
147
+
148
+ > 💵 *Illustrative assumption, not a measurement:* at $3 per million input tokens, before caching, that is about **$1.60 vs $0.09 per session**. Prompt caching lowers the price of the repeated definitions, but not the space they take in your context window.
149
+
150
+ ### 🧰 Example 2: All 15 servers, 420 tools
151
+
152
+ Add Canva (44 tools) and Higgsfield (241 tools) to the others and direct MCP needs **~204k tokens of definitions** (tool-definition tokens (~4 chars per token), reproducible offline: [examples/full-scale](examples/full-scale)). In a client that sends them all up front, that is more than a 200k context window **before you type the first message**. Mycel: **~1.2k**. At 9 servers with Canva (126 tools) it is already 44.5k vs 1.05k (−97.6%).
153
+
154
+ <p align="center"><img src="media/chart-fullscale.svg" alt="Horizontal bars: 8 servers 17.8k vs 1.0k, 9 servers with Canva 44.5k vs 1.05k, 15 servers with 420 tools about 204k vs 1.2k, with a 200k context window line" width="860"></p>
155
+
156
+ ### 📄 Example 3: Reading a 20,000-row CSV
157
+
158
+ Direct: the whole file flows through the model, **131k tokens**. Through Mycel the model gets a reference plus a digest (row count, columns, a sample): **187 tokens**. It can still ask for specific rows or pass the ref to another tool without ever reading the file.
159
+
160
+ ### 🔁 Example 4: A 17-step chore, 17 calls in 1 round trip
161
+
162
+ "Find stale notes and save a report" is **17 tool calls in 1 model round trip** with Code Mode: the model writes one small script and Mycel runs it. A client that makes one tool call per turn needs 17 turns; an efficient direct path using batch tools (`read_multiple_files`) needs about 3. Code Mode assumes the model writes a working script first time; not yet measured with a live model. Per-call overhead of the gateway: **about +0.4 ms on a Mac, +1 ms in CI (Ubuntu, Windows); median of 15 local calls**. And the safe default holds: an untrusted web page trying to trigger `write_file` is **blocked and needs approval**.
163
+
164
+ **Where it does *not* help:** with 1–2 small servers Mycel costs more context (see below). Don't use it for that; use it for the safety layer, refs or Code Mode.
165
+
166
+ ## 🤔 Do you need Mycel?
167
+
168
+ Honest answer: **it depends on how many MCP servers your agent uses.** Measured with 8 real open-source servers ([field test](examples/field-test)), adding them one at a time:
169
+
170
+ | MCP servers | Tools | Tool definitions, direct | Through Mycel | Context saved |
171
+ |---:|---:|---:|---:|---:|
172
+ | 1 | 3 | 1.1k tokens | 1.1k | **−4%** (costs more) |
173
+ | 2 | 4 | 1.5k | 1.5k | −3% (costs more) |
174
+ | 3 | 18 | 4.7k | 3.8k | 19% |
175
+ | **4** | **32** | **6.7k** | **0.9k** | **86%** |
176
+ | 6 | 42 | 10.6k | 1.0k | 91% |
177
+ | 8 | 80 | 17.8k | 1.0k | **94%** |
178
+
179
+ The table uses the chars/4 estimator. With a real tokenizer (o200k) on a 4-tool catalog (time + fetch), direct is 902 tokens and Mycel 1,424: **Mycel uses about 58% more context there**. With 1–2 small servers, don't use it for context savings.
180
+
181
+ Mycel's own footprint stays flat at ~1k tokens. Direct MCP grows with every server you add, and on *every* turn the model re-reads all of those definitions.
182
+
183
+ **You'll feel it if…**
184
+ - you use **4+ MCP servers**, or one big one (Playwright, GitHub, Notion: 20–90 tools each);
185
+ - your tools return **big results**: files, tables, logs, page snapshots, images, video. A 20,000-row CSV is 131k tokens direct and 187 through Mycel;
186
+ - your agent does **many small steps** (read 15 files, decide, write): Code Mode does it in 1 round trip instead of up to 17 (about 3 with batch tools);
187
+ - your agent reads **untrusted content** (web, email, tickets) *and* can write, send or delete;
188
+ - you need to **see and cap** what agents do: approvals, budgets, an audit trail, or other agents (A2A) calling your tools.
189
+
190
+ **You probably don't need it if…** you run 1–2 small servers and only make short, read-only calls. Your client is fine on its own, and Mycel adds context there instead of saving it.
191
+
192
+ **Your client matters too.** Claude Code and recent Cursor versions load MCP tool descriptions on demand (Cursor calls it "dynamic context discovery"). In those clients the definition savings are smaller and not yet measured; Mycel's value there is Code Mode, refs for big results, the safety layer and A2A. Other clients and frameworks may send definitions up front: check your client. The numbers above apply in full only where every definition goes out every turn.
193
+
194
+ ## 🔬 Field test: 8 real MCP servers
195
+
196
+ `cd examples/field-test && npm install && npm run setup && npm test` runs these checks on your own machine (macOS, Linux or Windows):
197
+
198
+ | # | Check | Result |
199
+ |---|---|---|
200
+ | S1 | Tool definitions in context (80 tools) | 17.8k → **1.0k** tokens (−94%) |
201
+ | S2 | Startup until tools are listed | about the same as direct (≈0.5–1.5 s) |
202
+ | S3 | Offline tool search, 16 natural-language queries | top-3 **15/16** (CI and local), top-1 **12/16** in the latest runs (English queries); see [search quality](#search-quality) |
203
+ | S4 | Per-call overhead (median of 15 local calls) | **about +0.4 ms** on a Mac, +1 ms in CI (Ubuntu, Windows) |
204
+ | S5 | 20,000-row CSV through `read_text_file` | 131k → **187** tokens (ref + table digest, grep-able) |
205
+ | S6 | "Find stale notes, save a report" (17 calls) | 17 calls in **1** round trip (Code Mode; not yet measured with a live model) |
206
+ | S7 | Web page (untrusted) → `write_file` | **blocked**, approval required |
207
+ | S8 | Browser automation (Playwright) | works, no needless prompts |
208
+ | S9 | Images, progress notifications | image → ref, 4/4 progress events forwarded |
209
+ | S10 | Risk classes for Playwright's 25 tools | 7 read · 13 external · 5 destructive |
210
+
211
+ ### Search quality
212
+
213
+ On the 16-query English field test, top-3 is 15/16 (CI and local) and top-1 is 12/16 in the latest runs; the older "10/16" top-1 came from an earlier run and is superseded. On an independent 32-pair EN/TR set, raw BM25 finds the right tool in the top 3 for 20/32 English and 3/32 Turkish queries. When a small model (Haiku) chooses from the results and may rewrite the query once, it is correct on 27/32 English and 25/32 Turkish. The offline index itself is English-only; models usually search in English.
214
+
215
+ **Reproducibility:** the −94% with 8 servers is reproducible: examples/field-test (CI runs it on Ubuntu and Windows).
216
+
217
+ **Plus a real remote server with OAuth:** after `mycel login canva`, Canva's 44 tools work through Mycel, and the tokens refresh automatically. With Canva added, the lab holds 126 tools: **44.5k tokens of definitions direct, 1.05k through Mycel (−97.6%)**.
218
+
219
+ ### At full scale: 420 tools (technical)
220
+
221
+ **Conditions:** 15 servers including Canva and Higgsfield (241 tools on its own), 420 tools loaded up front (eager loading). The tool definitions cost about **204k tokens direct and 1.2k through Mycel (−99.4%)**. Real tokenizers agree: cl100k 200,624 → 1,188 (99.41%), o200k 202,905 → 1,216 (99.40%). On a 135-tool catalog (no Canva/Higgsfield), o200k gives 29,129 → 1,147 (96.1%), and chars/4 overstates that one by about 19%. Claude Code and recent Cursor load tools on demand, and this is not measured there. Direct, that would fill most of a model's context window before the first message. These are tool-definition tokens (~4 chars per token), reproducible offline: [examples/full-scale](examples/full-scale). Counted the way clients send tools to the model: name, description and input schema. Canva and Higgsfield also ship output schemas; counting everything `tools/list` returns gives ~400k direct.
222
+
223
+ The field test found four real bugs before launch. All are fixed and covered by tests:
224
+ - Playwright marks even `hover` as destructive. Mycel now cross-checks that label against the tool's name (`annotations: strict` opts out).
225
+ - A big text result that came wrapped in JSON lost its table digest.
226
+ - grep on a single very long line returned the whole line.
227
+ - A few search synonyms were missing.
228
+
229
+ ## 🚀 Quickstart
230
+
231
+ Works on **macOS, Linux and Windows** (Node 20+). `ffmpeg` is optional (video/audio digests). The servers you bring decide the rest. For example, Python-based servers need [`uv`](https://docs.astral.sh/uv/).
232
+
233
+ ```bash
234
+ # Install (the command is `mycel`)
235
+ npm install -g @speakquery/mycel
236
+
237
+ # 1. Import the MCP servers you already use (secrets become {{secret:NAME}} placeholders)
238
+ mycel init
239
+
240
+ # 2. Check everything connects and see your own savings
241
+ mycel doctor
242
+ mycel bench
243
+
244
+ # 3. Remote servers with a sign-in (Canva, Notion, Linear, …): once per server
245
+ mycel login canva
246
+
247
+ # 4. Point your client at Mycel instead of N servers
248
+ ```
249
+
250
+ `mycel init` skips only the Mycel entry itself and lists each skipped entry with the reason. `mycel doctor` exits 1 when any upstream fails to start.
251
+
252
+ <table>
253
+ <tr><th>Claude Code</th><th>Claude Desktop / Cursor / Windsurf / VS Code (<code>mcpServers</code>)</th></tr>
254
+ <tr><td>
255
+
256
+ ```bash
257
+ claude mcp add mycel -- mycel serve
258
+ ```
259
+
260
+ </td><td>
261
+
262
+ ```json
263
+ { "mcpServers": { "mycel": { "command": "mycel", "args": ["serve"] } } }
264
+ ```
265
+
266
+ </td></tr>
267
+ </table>
268
+
269
+ Open **http://localhost:4747** for the live dashboard. Want the guided tour with real output? → [`examples/demo`](examples/demo).
270
+
271
+ ## 🧬 How it works
272
+
273
+ ```mermaid
274
+ flowchart TB
275
+ subgraph Clients["Any MCP client · any A2A agent"]
276
+ C1[Claude] --- C2[Cursor] --- C3[VS Code] --- C4[Local LLM] --- C5[Other agents]
277
+ end
278
+ Clients -- "MCP (stdio / HTTP) · A2A JSON-RPC" --> M
279
+ subgraph M["MYCEL"]
280
+ direction TB
281
+ MT["8 meta-tools: search · describe · call · run · ref · job · delegate · ask"]
282
+ subgraph Engine[" "]
283
+ R[Smart Router] --- CM[Code Mode sandbox] --- RS[Ref Store] --- J[Job Queue] --- MR[Model Router]
284
+ end
285
+ subgraph Trust["Trust layer"]
286
+ P[Policy firewall] --- T[Provenance / taint] --- S[Secret vault] --- PN[Manifest pinning] --- CT[Capability tokens]
287
+ end
288
+ FR["Flight recorder → dashboard · OpenTelemetry"]
289
+ MT --> Engine --> Trust --> FR
290
+ end
291
+ M -- MCP --> S1[GitHub] & S2[Video model] & S3[Database] & S4[…any server]
292
+ M -- A2A --> A1[Remote agents]
293
+ ```
294
+
295
+ The model sees **eight small meta-tools** instead of hundreds of schemas. A typical turn:
296
+
297
+ ```text
298
+ mycel_search {"query": "make a video from a prompt"}
299
+ → [{"tool":"studio.generate_video","effect":"external","async":true,"costUsd":0.4,…}]
300
+ mycel_call {"tool":"studio.generate_video","args":{"prompt":"a fox in neon rain"}}
301
+ → {"status":"job","job":{"id":"job_3f9…","status":"running","progress":42,"total":100}}
302
+ mycel_job {"action":"wait","id":"job_3f9…"}
303
+ → {"status":"succeeded","result":{"ref":"ref://9c1e…","mime":"video/mp4","size":"48.2 MB",
304
+ "digest":{"kind":"video","durationSec":8,"width":1920,"height":1080,"keyframes":["ref://…","ref://…","ref://…"]}}}
305
+ mycel_call {"tool":"studio.upscale_video","args":{"video":{"$ref":"ref://9c1e…","as":"path"}}}
306
+ ```
307
+
308
+ 48 MB of video moved between two tools. The model read ~120 tokens.
309
+
310
+ ## ✨ Features
311
+
312
+ All 20 ship in v1. Every one is opt-in beyond the defaults, and a 10-line config works.
313
+
314
+ ### Speed & context
315
+ | Feature | What it does |
316
+ |---|---|
317
+ | **1 · Smart Tool Router** | BM25 search (names ×3, server ×2, descriptions, params, synonyms) over every connected tool. Schemas load only on demand. Modes: `auto` (default — small catalogs get every tool directly plus `run`/`ref`/`job`; past ~4k tokens of definitions it switches to `meta`), `meta`, `hybrid` (meta-tools + your top-N most-used tools directly), `passthrough`. |
318
+ | **2 · Code Mode** | The model writes one async JS script; it runs in a **QuickJS WebAssembly sandbox** (no fs, no network, no Node APIs, CPU/memory/call caps). Only the return value comes back. `Promise.all` works. |
319
+ | **3 · Ref Store** | Content-addressed (`ref://<sha256>`) storage for anything big or binary, with model-sized **digests**: JSON shape + sample, table columns + stats, text outline, image/video/audio metadata, video keyframes (ffmpeg). Pass refs straight into tool args as text, JSON, base64, data URL or file path. |
320
+ | **4 · Job Queue** | Slow tools become jobs: progress, cancel, retry with backoff, **provider fallback chains**, resume after restart (idempotent jobs only — nothing runs twice by surprise). |
321
+ | **5 · Cost & Budget** | Per-tool cost/latency contracts, `dryRun` estimates, per-task / per-day / per-token spend caps. Tools without a declared cost count as $0; set `costUsd` (alias `cost`) per tool for budgets to be meaningful. |
322
+ | **15 · Model Router** | `mycel_ask` hands self-contained sub-tasks (summarise, extract, classify) to a `fast`/`balanced`/`deep` tier — any OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter…) or Anthropic. Refs in the prompt are expanded for the sub-model, not your main context. |
323
+
324
+ > **Paid jobs, honestly:** Fallback providers are tried only when the previous provider definitely rejected the call (connection refused, MCP error response, tool error). If the outcome is unknown (timeout, connection lost after the request was sent), Mycel stops, marks the job `unknown`, charges the contract `costUsd` as an estimate (`costEstimated: true`) and does not fall back, so you don't pay twice. Check the provider, then `mycel_job retry` if appropriate. Non-idempotent jobs interrupted by a restart after dispatch are marked `interrupted` and charged the same estimate. There is no exactly-once guarantee for paid providers.
325
+
326
+ ### Trust
327
+ | Feature | What it does |
328
+ |---|---|
329
+ | **6 · Tool Contracts** | Every tool gets an effect class — `read` · `write` · `external` · `destructive` — plus idempotency, cost, latency, async. Inferred from MCP annotations and names (cautiously), overridable in config. |
330
+ | **7 · Policy Firewall** | Ordered YAML rules: `allow` / `deny` / `approve` by tool glob, server, effect or taint. Safe defaults: destructive → approve; tainted + side-effect → approve. |
331
+ | **8 · Provenance & Taint** | Output from `trust: untrusted` servers is labelled and **taint follows the data** — through refs and through code-mode scripts. A script that read a hostile web page can't quietly send email. |
332
+ | **9 · Secret Vault** | The model only ever sees `{{secret:GITHUB_TOKEN}}`. Real values are injected at call time and scrubbed from every output, error and trace. |
333
+ | **10 · Manifest Pinning** | Tool definitions are hashed into `mycel.lock`. If a server silently changes a tool's description or schema (a "rug pull"), the tool is blocked until a human runs `mycel pin --accept`. |
334
+ | **14 · Capability Tokens** | Macaroon-style, attenuable, expiring delegation tokens (`myc1.…`). A sub-agent can narrow its token — fewer tools, lower effect ceiling, smaller budget, shorter expiry — and hand it on, but can **never** widen it. No secret needed to attenuate. |
335
+ | **Approvals** | Inline via MCP **elicitation** when the client supports it; otherwise an approval id the human grants with `mycel approve <id>` or one click in the dashboard. Approvals are one-shot and bound to the exact arguments. |
336
+
337
+ ### Visibility
338
+ | Feature | What it does |
339
+ |---|---|
340
+ | **11 · Flight Recorder** | Every search, call, script, job, approval and policy decision is a span: timing, tokens saved, bytes offloaded, cost, taint. JSONL on disk + **OpenTelemetry (OTLP/HTTP)** export. `mycel replay <trace>`. |
341
+ | **12 · Live Dashboard** | Local web UI: savings, live activity, trace waterfalls, approvals, jobs, servers, drift, refs. Token-protected and DNS-rebinding-safe. |
342
+
343
+ ### Mesh & integration
344
+ | Feature | What it does |
345
+ |---|---|
346
+ | **13 · A2A Bridge** | Mycel *is* an A2A agent (Agent Card at `/.well-known/agent-card.json`, `message/send`, `tasks/get`, `tasks/cancel`) **and** an A2A client (`mycel_delegate` to your peers). Same policy, budget, taint and recording for agents as for MCP clients. |
347
+ | **16 · Universal import** | `mycel init` reads Claude Desktop, Claude Code (incl. per-project), Cursor, VS Code, Windsurf and Gemini CLI configs. |
348
+ | **17 · Both transports** | Serve over stdio (desktop clients) or Streamable HTTP (`/mcp`, remote clients; single-user, not a multi-tenant boundary). Upstreams over stdio or HTTP. |
349
+ | **18 · Python client** | `pip install "git+https://github.com/SpeakQuery/mycel#subdirectory=python"` — zero dependencies. |
350
+ | **19 · Benchmark** | `mycel bench` — the numbers above, reproducible on your machine. |
351
+ | **20 · Adapter SDK** | `defineAdapter({...})` turns ~50 lines into a provider (a new video model, an internal API) that works in-process *and* as a standalone MCP server. |
352
+
353
+ ## ⚙️ Configuration
354
+
355
+ `mycel.yaml` (generated by `mycel init`):
356
+
357
+ ```yaml
358
+ servers:
359
+ github:
360
+ command: npx
361
+ args: ["-y", "@modelcontextprotocol/server-github"]
362
+ env: { GITHUB_TOKEN: "{{secret:GITHUB_TOKEN}}" }
363
+ canva:
364
+ url: https://mcp.canva.com/mcp # OAuth: run `mycel login canva` once; tokens refresh automatically
365
+ studio:
366
+ url: https://studio.example.com/mcp
367
+ headers: { Authorization: "Bearer {{secret:STUDIO_KEY}}" }
368
+ tools: # contract overrides
369
+ generate_video: { async: true, costUsd: 0.40, fallback: ["backup.generate_video"], retries: 1 }
370
+ web:
371
+ command: node
372
+ args: ["./web-server.mjs"]
373
+ trust: untrusted # its output is labelled and taints downstream calls
374
+
375
+ router: { mode: auto } # auto | meta | hybrid | passthrough
376
+ policy:
377
+ - match: { tool: "github.*delete*" }
378
+ action: deny
379
+ - match: { effect: destructive }
380
+ action: approve
381
+ - match: { tainted: true, effect: external }
382
+ action: approve
383
+ reason: Untrusted content is trying to send something out.
384
+ budget: { perTaskUsd: 5, perDayUsd: 50 }
385
+ refs: { inlineLimitBytes: 8000 }
386
+ sandbox: { timeoutMs: 30000, memoryMb: 64, maxToolCalls: 200 }
387
+ jobs: { asyncThresholdMs: 20000, concurrency: 4 }
388
+ recorder: { otlpEndpoint: http://localhost:4318 } # optional
389
+ models: # optional, enables mycel_ask
390
+ fast: { provider: openai, baseUrl: http://localhost:11434/v1, model: llama3.2 }
391
+ balanced: { provider: anthropic, model: claude-haiku-5-5, apiKey: "{{secret:ANTHROPIC_API_KEY}}" }
392
+ a2a: # optional
393
+ tokenSecret: "{{secret:MYCEL_TOKEN_SECRET}}"
394
+ peers:
395
+ researcher: { url: https://research.example.com, token: "{{secret:RESEARCHER_TOKEN}}" }
396
+ ```
397
+
398
+ Full reference: [`docs/configuration.md`](docs/configuration.md).
399
+
400
+ ## 🧪 Code Mode
401
+
402
+ ```js
403
+ // mycel_run — one round trip instead of 21
404
+ const issues = await tools.call("github.list_issues", { repo: "acme/web", state: "open" });
405
+ const stale = issues.filter(i => daysSince(i.updated_at) > 30);
406
+ await Promise.all(stale.map(i => tools.call("github.add_label", { repo: "acme/web", issue: i.number, label: "stale" })));
407
+ return { labelled: stale.length };
408
+ ```
409
+
410
+ Sandbox API: `tools.call(id, args)`, `tools.search(q)`, `refs.read(ref, {path, rows, grep, offset, length})`, `refs.put(value)`, `jobs.run(tool, args)`, `jobs.submit / wait`, `ask(prompt, {tier})`, `console.log`, `sleep`, `daysSince`, `chunk`, `pick`. Every `tools.call` goes through the same policy, budget, taint and recording as a direct call.
411
+
412
+ ## 🤝 Agent to agent
413
+
414
+ ```bash
415
+ export MYCEL_TOKEN_SECRET=$(mycel token secret)
416
+ mycel serve --http --port 4747 # MCP at /mcp, A2A at /a2a
417
+
418
+ # Give a research agent read-only GitHub access for 2 hours, max $1
419
+ TOKEN=$(mycel token mint --tools 'github.*' --max-effect read --budget 1 --ttl 2h --sub researcher)
420
+ # …which it can narrow further for its own sub-agent — but never widen
421
+ mycel token attenuate "$TOKEN" --tools 'github.list_*' --ttl 10m --sub summarizer
422
+ ```
423
+
424
+ ```bash
425
+ curl -s localhost:4747/a2a -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{
426
+ "jsonrpc":"2.0","id":1,"method":"message/send",
427
+ "params":{"message":{"kind":"message","role":"user","messageId":"1",
428
+ "parts":[{"kind":"data","data":{"tool":"github.list_issues","args":{"repo":"acme/web"}}}]}}}'
429
+ ```
430
+
431
+ A destructive request comes back as `input-required` with an approval id; after a human approves, the agent resumes the same task. See [`examples/a2a`](examples/a2a).
432
+
433
+ ## 🐍 Python
434
+
435
+ ```python
436
+ from mycel_client import Mycel, ApprovalRequired
437
+
438
+ m = Mycel("http://127.0.0.1:4747")
439
+ print(m.search("make a video"))
440
+ issues = m.call("github.list_issues", {"repo": "acme/web"})
441
+ print(m.run("return (await tools.call('github.list_issues', {})).length"))
442
+ ```
443
+
444
+ ## 🔌 Write an adapter
445
+
446
+ ```js
447
+ import { defineAdapter, file } from "mycel";
448
+
449
+ export default defineAdapter({
450
+ name: "my-video-model",
451
+ tools: [{
452
+ name: "generate_video",
453
+ description: "Generate a video from a prompt",
454
+ input: { type: "object", properties: { prompt: { type: "string" } }, required: ["prompt"] },
455
+ effect: "external", async: true, costUsd: 0.4,
456
+ async run({ prompt }, { progress }) {
457
+ const id = await startRender(prompt);
458
+ for (let p; (p = await poll(id)).status !== "done"; ) progress(p.percent, 100);
459
+ return file(await download(id), "video/mp4", "out.mp4"); // becomes a ref:// with keyframes
460
+ },
461
+ }],
462
+ }).serve(); // a standalone MCP server, too
463
+ ```
464
+
465
+ ## 🖥️ CLI
466
+
467
+ | Command | |
468
+ |---|---|
469
+ | `mycel init` | import client configs → `mycel.yaml` |
470
+ | `mycel serve [--http]` | run the gateway (stdio, or HTTP with `/mcp` + `/a2a`) |
471
+ | `mycel dashboard` | open the local dashboard |
472
+ | `mycel doctor` · `mycel bench` | check setup · measure savings |
473
+ | `mycel login <server>` | sign in to a remote MCP server that uses OAuth (Canva, Notion, Linear, …) |
474
+ | `mycel search <q>` · `mycel call <tool> [json]` · `mycel run <file>` | use tools from the terminal, same rules as agents |
475
+ | `mycel approvals` · `approve <id>` · `deny <id>` | human-in-the-loop |
476
+ | `mycel pin [--accept]` | review / accept tool-definition drift |
477
+ | `mycel token secret / mint / attenuate / inspect` | capability tokens |
478
+ | `mycel traces` · `mycel replay <id>` | flight recorder |
479
+ | `mycel refs [--gc 7d]` | ref store |
480
+
481
+ ## 🛡️ Security model — honestly
482
+
483
+ Mycel **reduces and exposes** risk; it does not "solve" prompt injection. What it guarantees: secrets never enter the model's context; destructive and tainted side-effects need a human by default; changed tool definitions are blocked; delegated agents can't exceed their token; everything is recorded. What it can't guarantee: that a trusted server is actually trustworthy, or that a model never misreads data as instructions. Code Mode runs in QuickJS/WASM with no ambient capabilities, but treat it as defence in depth, not a security boundary for hostile code. Supported deployment is single-user and local; see the "Supported deployment" section of [SECURITY.md](SECURITY.md). Report issues: [SECURITY.md](SECURITY.md).
484
+
485
+ ## 🗺️ Roadmap
486
+
487
+ - Streaming refs for realtime audio/video agents
488
+ - Embedding-based search as an optional plug-in (BM25 stays the offline default)
489
+ - A2A streaming (`message/stream`) and push notifications
490
+ - Signed tool manifests from server publishers
491
+ - Team mode: shared policy, approvals routed to Slack/Teams
492
+
493
+ ## Contributing
494
+
495
+ PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). `npm install && npm test` runs the full suite (47 tests) in a few seconds.
496
+
497
+ ## License
498
+
499
+ [Apache-2.0](LICENSE) © The Mycel Authors