From b4b14c8a1af60b736d17cf1faf54fe7319129e8e Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:50:36 +0000 Subject: [PATCH] mcp: approve a tool for the rest of a session with one tap (#8180) * plan: mcp-activity * plan: mcp-activity list format * plan: mcp-activity answers and live step lines * mcp: a silent line per step of Claude's work, completed at its end * plan: mcp-activity as implemented * mcp: finalize step lines within a day and load only the hook's modules * plan: mcp-activity review decisions as implemented * plan: mcp-allow-tool * mcp: approve a tool for the rest of a session with one tap * plan: mcp-allow-tool as implemented * mcp: docs of the approval of a tool for the rest of a session * mcp: record the checks of the PreToolUse hook with Claude Code * plan: mcp-allow-tool citations of the new code * mcp: keep the approvals of tools while the session's process re-attaches * plan: mcp-allow-tool review round 1 * mcp: end the approvals of tools when the session's group is lost * mcp: tool approvals end when the session's group is lost, docs and tests * mcp: tool approvals follow the process that opened the session last A process is identified by its ID and its start time, read from /proc/PID/stat on Linux and from ps on macOS. A registration from a process with the same ID and another start time ends the approvals. /attach has the session server's parent process ID. While two processes have the session attached, only the attachments of the process of the last /session get the approved tools; the others get an empty list. Tests cover the end of the approvals at a load of a lost group. * plan: mcp-allow-tool decisions 36 and 37, the group's loss in the rules and the design * mcp: a process whose start time is unknown counts as another process A registration of the session's process ends the tool approvals when its start time can't be read, on systems other than Linux and macOS and after a failed read. The start time is read only for a process ID that is a positive integer; on macOS, /bin/ps runs with a 2 s timeout. --- packages/simplex-chat-mcp/README.md | 3 +- packages/simplex-chat-mcp/REFERENCE.md | 19 +- packages/simplex-chat-mcp/ROADMAP.md | 1 - packages/simplex-chat-mcp/TESTING.md | 8 +- packages/simplex-chat-mcp/hooks/hooks.json | 2 +- packages/simplex-chat-mcp/spec/README.md | 4 +- packages/simplex-chat-mcp/spec/api.md | 19 +- .../simplex-chat-mcp/spec/architecture.md | 75 +++- packages/simplex-chat-mcp/spec/flows.md | 64 ++- packages/simplex-chat-mcp/src/actions.ts | 1 + packages/simplex-chat-mcp/src/control.ts | 55 ++- packages/simplex-chat-mcp/src/hub.ts | 24 +- packages/simplex-chat-mcp/src/protocol.ts | 8 + packages/simplex-chat-mcp/src/service.ts | 34 +- packages/simplex-chat-mcp/src/session.ts | 21 +- .../simplex-chat-mcp/test/e2e/launch.test.ts | 2 +- .../simplex-chat-mcp/test/e2e/service.test.ts | 28 +- .../simplex-chat-mcp/test/unit/cards.test.ts | 11 + .../simplex-chat-mcp/test/unit/plugin.test.ts | 4 +- .../test/unit/service.test.ts | 101 ++++- .../test/unit/session.test.ts | 24 +- .../test/unit/sessions.test.ts | 158 +++++++- plans/2026-11-13-mcp-allow-tool.md | 382 ++++++++++++++++++ 23 files changed, 981 insertions(+), 67 deletions(-) create mode 100644 plans/2026-11-13-mcp-allow-tool.md diff --git a/packages/simplex-chat-mcp/README.md b/packages/simplex-chat-mcp/README.md index 184ef43a1e..552e61abfe 100644 --- a/packages/simplex-chat-mcp/README.md +++ b/packages/simplex-chat-mcp/README.md @@ -35,12 +35,13 @@ You need Node.js 22 or later, Claude Code, and the [SimpleX Chat app](https://si 3. Each Claude Code session gets its own group, such as "1 · my-project". Join it from the invitation in "Claude Control". -4. Send prompts in the session's group, and Claude answers there. Reply to a message to show Claude which one you mean. Claude also gets your reactions, as emoji replies. Prompts you type in the terminal appear there too, and Claude Code's own prompts, such as a finished background task, appear as one line each. Each step of Claude's work, such as running the tests, appears as one line, completed with its outcome when the step ends. Before Claude acts in other chats or uses a tool such as Bash, it asks in the group, and one tap approves. +4. Send prompts in the session's group, and Claude answers there. Reply to a message to show Claude which one you mean. Claude also gets your reactions, as emoji replies. Prompts you type in the terminal appear there too, and Claude Code's own prompts, such as a finished background task, appear as one line each. Each step of Claude's work, such as running the tests, appears as one line, completed with its outcome when the step ends. Before Claude acts in other chats or uses a tool such as Bash, it asks in the group, and one tap approves. Another tap approves the tool for the rest of the session. ## Safety - Anyone in "Claude Control" can join your sessions as an admin, so only invite people you trust. - In a session, admins and owners can prompt Claude and approve what it does. Other members can only prompt, and observers can only read. +- A tool approved for the session runs without asking until the session ends or `/revoke`. Claude Code still asks where its own rules require it, such as before a change to `.git` or `.bashrc`. - Claude Code doesn't run `!` or `/` commands sent in the group. - Claude sends files to the group only if the group allows them. - Claude has no SimpleX address, so nobody can contact it first. diff --git a/packages/simplex-chat-mcp/REFERENCE.md b/packages/simplex-chat-mcp/REFERENCE.md index 27b649fe0d..86e7bd5682 100644 --- a/packages/simplex-chat-mcp/REFERENCE.md +++ b/packages/simplex-chat-mcp/REFERENCE.md @@ -492,11 +492,12 @@ The plugin adds: | Part | What it does | |---|---| -| MCP server `simplex` | Runs `simplex-mcp session` for each session. It provides the tools, such as `mcp__plugin_simplex_simplex__connect`, and the channel. | +| MCP server `simplex` | Runs `simplex-mcp session` for each session. It provides the tools, such as `mcp__plugin_simplex_simplex__connect`, and the channel. Its tool `pre_tool_use` answers the PreToolUse hook of every tool, and Claude never needs to call it. | | SessionStart hook | Checks the Node.js version and starts the service. It opens the session and its group, and shows the Main group link while the Main group has no owner. | | PreToolUse hook of the plugin's tools | Lets the plugin's tools run without a Claude Code prompt, because you approve them in the SimpleX app. | | UserPromptSubmit, Stop and PostModelSwitch hooks | Post your terminal prompts and Claude's answers in the session's group, and keep the model and effort in its description. They run in the background. | | PreToolUse, PostToolUse and PostToolUseFailure hooks of every tool | Post a line for each step of Claude's work when it starts, and complete it when it ends. They run in the background. | +| PreToolUse hook of every tool, of type `mcp_tool` | Calls the tool `pre_tool_use` of the session's MCP server, which allows a tool approved for the rest of the session, see [Tool use](#tool-use). It waits up to 5 seconds. | The server and hooks run `node ${CLAUDE_PLUGIN_ROOT}/dist/cli.js`. The PreToolUse hook of the plugin's tools runs `node ${CLAUDE_PLUGIN_ROOT}/plugin/allow.js` instead. The package, a 4 MB download, bundles its dependencies and has no lockfile, so Claude Code installs nothing after unpacking it. Node.js loads the modules from the plugin's folder, so a project's `node_modules` can't replace them. The first session start downloads the SimpleX core library. Claude Code waits up to 600 seconds for the SessionStart hook. @@ -596,7 +597,7 @@ VERSION is the plugin's version, as in `npx -y @simplex-chat/mcp@0.3.0 link`. Th - When someone joins or their role changes, Claude posts their rights. For an admin the post is `Bob is an admin and can send prompts to Claude and the group's commands, and approve tool use. You can change role to observer to stop it: /'observer #G ID'`, with the group's and the member's IDs. For a moderator, member or author it is `NAME is a ROLE and can send prompts to Claude; the group's commands and approvals need the role admin or owner.`, followed by the same command. The posts for an owner and for an observer have no command: `NAME is an owner and can send prompts to Claude and the group's commands, and approve tool use.` and `NAME is an observer and can't send messages.` Claude posts nothing for `User`. - `/observer #G ID` makes that member an observer, and Claude replies `NAME is an observer and can't send messages.` Admins and owners can use it on a member whose role isn't above their own. Standing approvals that the observer gave, of all messages to a chat or all files from it, stop counting while they aren't an admin or owner, and count again if they become one. For a member who was invited and hasn't joined yet, Claude replies `No member ID in this group.` That member joins with the role of the invitation, which can be changed after the join. - The group's description is `The Claude Code session N. Members send it prompts; admins and owners also send the group's commands and approve tool use.`, set when the group is created. Its short description shows the model and effort, see [Model and effort](#model-and-effort). -- The group has the commands of the agent control chat of `serve` (see [What the owner sees](#what-the-owner-sees)), without a session prefix, such as `/approve 7`, `/receive @3 9` and `/leave #2`. It also has `/give CHAT N` and `/observer #G ID`. +- The group has the commands of the agent control chat of `serve` (see [What the owner sees](#what-the-owner-sees)), without a session prefix, such as `/approve 7`, `/receive @3 9` and `/leave #2`. It also has `/give CHAT N`, `/observer #G ID`, and `/approve N all` and `/revoke TOOL` for tools, see [Tool use](#tool-use). - A chat belongs to the session that connected it, even when the other side accepts after `connect` returned. The tools of other sessions don't show it. Their `connect` to its address returns `The chat of LINK belongs to another session; an admin or owner of that session's group can give it to this session with /give.` For example, `/give @3 2` in the group of the session that owns chat @3 gives it to session 2. - `/list` and `/revoke` also work in the group of a closed session. A `/revoke` sent while the service is stopped applies when the service starts again. - `claude --resume` and `claude --continue` reopen a session with its group and chats. `/clear` keeps the session's group, because the service links the new session IDs of a Claude Code process to that process's session. A fork made with `claude --resume ID --fork-session` continues in the group of the resumed session. After `/resume` of another session inside a running one, prompts and answers go to the running session's group. A later `claude --resume` of that other session reopens its own group and chats. @@ -665,11 +666,22 @@ With the channel, Claude Code's permission prompts, such as the one before a Bas ``` Claude: I want to use `Bash`: `List files` `ls -la` - /approve 5 or /reject 5 + /approve 5, /approve 5 all or /reject 5 ``` `/approve 5` allows the tool use, and `/reject 5` denies it. The dialog in the terminal stays open, and the first answer, in the terminal or in the group, applies. A card that is still pending gets `Ended.` when its turn ends, when a prompt starts the next turn, or when the session ends. A prompt that Claude Code adds to the running turn leaves the card pending. The preview of the tool's input is shortened to fit the card. +`/approve 5 all` allows the tool use and approves its tool for the rest of the session. Claude replies `` Approved `Bash` for the rest of this session by Alice. /revoke Bash ``. + +- Later uses of the tool run without a card and without the dialog in the terminal. Each use in the main conversation still has its line in the group. +- Claude Code still asks where its own rules require it: for a matching ask rule, a write to a protected path such as `.git`, `.claude` or `.bashrc`, in plan mode, and when the classifier of auto mode asks. Such a use gets a card with the line `` `Bash` is approved for this session, and Claude Code still asks for this use. ``, and no `all` command. With Claude Code before 2.1.299, an approved tool also runs writes in plan mode. +- The approval covers the uses of subagents too. Other pending cards of the tool stay pending. +- It counts while the member who gave it is an admin or owner of the group, and counts again if they become one again. +- `/list` shows it after the chats, as `` `Bash` approved for this session by Alice ``. `/revoke Bash` ends it with `` Uses of `Bash` need approval again. `` +- It holds for the Claude Code process of the session, also after that process attaches to the service again. It is dropped when another Claude Code process opens the session, when the session closes, and when the service restarts. The service tells processes apart by their ID and their start time, read on Linux and macOS. On other systems, and when the start time can't be read, the approval also ends when the same process opens the session again, as after a failed call. While two Claude Code processes have the session open, only the one that opened it last gets the approvals. It also ends when the session's group is lost: when the group is deleted, or Claude is removed from it or is no longer its owner. The terminal shows nothing at the approval, and Claude Code's `/permissions` doesn't list it, because the plugin keeps it. +- `/approve N all` of another kind of action gets `Action N is not a tool use.` +- While the plugin's MCP server is not connected, as when it is disabled in `/mcp`, left out by `--strict-mcp-config` or failed to start, Claude Code reports the PreToolUse hook error `MCP server 'plugin:simplex:simplex' not connected` at each tool use, and the tool use goes on as without the plugin. + ### Model and effort The short description of a session's group shows `MODEL · effort LEVEL`. The model is updated at the session start when Claude Code passes it, at each model change, and at the end of each turn from the model of the answer in the session's transcript. So the model shows from the first answer, also in a resumed session. The effort level is updated at the end of each turn. Changes made in the terminal, or from the Claude app by Remote Control, show the same way. @@ -732,6 +744,7 @@ The folders, and the files the service writes, are readable only by the user, ex - Claude Code runs no command from a message of a session's group, even one that starts with `!`. Claude gets the text, and its tool use follows Claude Code's permissions. - Only you get the Main group link. The session start shows it, and `link` prints it in a terminal. - A session runs in mode `host` only after an admin or owner approves it in the session's group. +- A tool approved in the session's group runs without the terminal's dialog, and Claude Code's own rules still apply to it. Only an admin or owner approves it, for the rest of the session. - Claude's files reach the group only while its preference "Files and media" allows them. Owners set it, and SimpleX enforces it. A post that a preference refuses is replaced by Claude's text that names the preference. - Any program running as you on this computer can replace the Main group and its owners at once, without their approval, with `reset-owners` or a request to the service. - The plugin refuses to send private keys and the files of its data folder, except the files under `files/` of the session's own folder. diff --git a/packages/simplex-chat-mcp/ROADMAP.md b/packages/simplex-chat-mcp/ROADMAP.md index 14570adf0f..2d054bb995 100644 --- a/packages/simplex-chat-mcp/ROADMAP.md +++ b/packages/simplex-chat-mcp/ROADMAP.md @@ -19,7 +19,6 @@ What comes next for Claude Code in SimpleX Chat. - See what Claude is doing while it works, with its code changes as diffs. - The model, effort and usage of each session show in its description, updated as they change. - See when a session's context is summarised. -- Allow a tool for the rest of a session with one tap. - Each session is a topic inside one group, not a group of its own. - Claude can offer choices and other small interactive widgets in the chat. - Start a new session from the desktop app, in a folder you choose. diff --git a/packages/simplex-chat-mcp/TESTING.md b/packages/simplex-chat-mcp/TESTING.md index c9ac9faf4c..7c658b2094 100644 --- a/packages/simplex-chat-mcp/TESTING.md +++ b/packages/simplex-chat-mcp/TESTING.md @@ -153,7 +153,7 @@ The MCP server and the SessionStart, UserPromptSubmit, Stop, PostModelSwitch, Po - the hooks; - the plugin files. - In these tests, the Stop hook reads the model of its answer from the end of a sparse 3 GiB transcript. It finds the model even when the answer's entry is written after the hook started. The UserPromptSubmit hook marks a prompt as typed only when its record has the origin `human`. Task notifications, messages of other sessions and channel prompts are not marked. A typed prompt is marked also when the transcript is created with its entry 30 reads after the hook started, as after a user's own prompt hook of 3 s. The hook sends the one-line note of each kind of Claude Code's own prompt, a teammate's message included, also when idle notifications precede it in its prompt, and none for a typed or a channel prompt or idle notifications only. A note stays on one line when the sender's name has a line break or a control character. A prompt that reaches a running turn is found by its queued command or its own later entry, and it is marked mid-turn, also when the turn's first entry is out of the tail and only its tool results are in it. Its record is taken by its text, past a meta entry with the same prompt ID; a prompt with the text of the turn's own prompt waits while it is queued. A typed prompt still queued after the reads is typed and mid-turn. The hook sends the note of Claude Code's own prompt also when a later prompt with its text is still queued after the reads, as a repeated monitor event. The hub posts the note as Claude, without a quote. A mid-turn prompt ends no tool-use card and keeps the turn's quote; an owner's prompt added to the turn adds a turn record, and the answer quotes it. A member's emoji reaction reaches the session as the emoji after the quote line of the reacted message, with that message's ID as `item` and `replyTo.item`. A reacted image or video without a caption is quoted with its type and file name, and its file is not received. One of the apps' eight emoji reaches the session. Another reaction, such as U+FE0F alone, `❤️` with U+FE0F, a newer emoji, a text of two lines or another type, reaches no session and gets the reply `This reaction is not supported.` The reply is posted once for each member and reacted message, also when the member removes the reaction and adds it again, and never for a reaction to the reply. The reactions of an observer and of `User`, removed reactions and reactions in the Main group, with one of the eight emoji or another value, reach no session and get no reply. A reaction to a pending tool-use card leaves the card pending. The answer of a reaction's turn quotes the reacted message, Claude's own answer included, and two equal reactions to one message are quoted in their own turns. The tool hooks send a step at the start of each tool use of the main conversation, with its text from the tool's input and paths relative to the session's folder, and at its end with ✅, ❌ or ⏹️ and the duration, or with `(in background)` for a launch in the background; Grep and Glob show the pattern, then the path; a tool use of a subagent or of this plugin, or without its ID or tool, sends nothing. The hub posts the start of a step as a silent live line, updates it at the step's end with live off, also while the start's send is in flight, and posts an end that arrives before its start as a silent line, and nothing for that start. Steps without an end are completed with their own text at an answer, at a prompt that starts a turn, at the last detach and at the hub's stop, not at a prompt added to the running turn, and the hub posts nothing for their later ends. A line still live 23 hours after its start is completed with its text, and the later end is posted as a new silent line. When the wall clock moves 23 hours on while the timers stand still, as in a sleep, the line is completed at the next check of the minute or at its step's end. The hub's stop waits for the updates that the last detach started. A refused step gets one refusal post, `Claude's note was not posted: ...`, as a refused note does; a failed send or update is logged, and nothing more is posted. A note and the parts of an answer but the last are silent, and the last part of an answer is important. The records follow sessions recorded with Claude Code 2.1.322 on 2026-11-12. The hooks, the session server and the service are tested with the environments of two `claude -p` runs, recorded with Claude Code 2.1.319 in `test/unit/claude-p-runs.jsonl`. One run has the entrypoint `claude-vscode` of a VS Code session, and the other is a plain `claude -p` run. The session server must answer `server/discover` with `Method not found` and negotiate the revision 2025-11-25. Claude Code 2.1.319 registers no channel for a server in the modern MCP era, 2026-07-28, so this test fails after an SDK upgrade that turns that era on. + In these tests, the Stop hook reads the model of its answer from the end of a sparse 3 GiB transcript. It finds the model even when the answer's entry is written after the hook started. The UserPromptSubmit hook marks a prompt as typed only when its record has the origin `human`. Task notifications, messages of other sessions and channel prompts are not marked. A typed prompt is marked also when the transcript is created with its entry 30 reads after the hook started, as after a user's own prompt hook of 3 s. The hook sends the one-line note of each kind of Claude Code's own prompt, a teammate's message included, also when idle notifications precede it in its prompt, and none for a typed or a channel prompt or idle notifications only. A note stays on one line when the sender's name has a line break or a control character. A prompt that reaches a running turn is found by its queued command or its own later entry, and it is marked mid-turn, also when the turn's first entry is out of the tail and only its tool results are in it. Its record is taken by its text, past a meta entry with the same prompt ID; a prompt with the text of the turn's own prompt waits while it is queued. A typed prompt still queued after the reads is typed and mid-turn. The hook sends the note of Claude Code's own prompt also when a later prompt with its text is still queued after the reads, as a repeated monitor event. The hub posts the note as Claude, without a quote. A mid-turn prompt ends no tool-use card and keeps the turn's quote; an owner's prompt added to the turn adds a turn record, and the answer quotes it. A member's emoji reaction reaches the session as the emoji after the quote line of the reacted message, with that message's ID as `item` and `replyTo.item`. A reacted image or video without a caption is quoted with its type and file name, and its file is not received. One of the apps' eight emoji reaches the session. Another reaction, such as U+FE0F alone, `❤️` with U+FE0F, a newer emoji, a text of two lines or another type, reaches no session and gets the reply `This reaction is not supported.` The reply is posted once for each member and reacted message, also when the member removes the reaction and adds it again, and never for a reaction to the reply. The reactions of an observer and of `User`, removed reactions and reactions in the Main group, with one of the eight emoji or another value, reach no session and get no reply. A reaction to a pending tool-use card leaves the card pending. The answer of a reaction's turn quotes the reacted message, Claude's own answer included, and two equal reactions to one message are quoted in their own turns. The tool hooks send a step at the start of each tool use of the main conversation, with its text from the tool's input and paths relative to the session's folder, and at its end with ✅, ❌ or ⏹️ and the duration, or with `(in background)` for a launch in the background; Grep and Glob show the pattern, then the path; a tool use of a subagent or of this plugin, or without its ID or tool, sends nothing. The hub posts the start of a step as a silent live line, updates it at the step's end with live off, also while the start's send is in flight, and posts an end that arrives before its start as a silent line, and nothing for that start. Steps without an end are completed with their own text at an answer, at a prompt that starts a turn, at the last detach and at the hub's stop, not at a prompt added to the running turn, and the hub posts nothing for their later ends. A line still live 23 hours after its start is completed with its text, and the later end is posted as a new silent line. When the wall clock moves 23 hours on while the timers stand still, as in a sleep, the line is completed at the next check of the minute or at its step's end. The hub's stop waits for the updates that the last detach started. A refused step gets one refusal post, `Claude's note was not posted: ...`, as a refused note does; a failed send or update is logged, and nothing more is posted. A note and the parts of an answer but the last are silent, and the last part of an answer is important. `/approve N all` on a tool-use card approves the use and its tool for the rest of the session, replies with `/revoke TOOL`, and sends the approved tools to the session; a later card of that tool says that Claude Code still asks for it and offers no `all`. An approved tool counts only while its approver is an admin or owner, after a role change and after `/observer`, and no more after the approver leaves or is removed. `/revoke TOOL` ends the approval, `/list` shows the approved tools after the chats, and `/approve N all` of another kind of action is refused. The approvals are kept across a detach, and each new attachment gets them. The service keeps them when the session's process registers and attaches again, and ends them when another process registers the session and when the session closes. A process with the PID of an ended process of the session and another start time counts as another process, and so does each registration of a process whose start time is unknown. The start time of a running process reads the same twice and differs from that of a later child; a process that does not run and an ID that is not a positive integer have none. While two processes have the session attached, only the attachments of the process that registered it last get the approved tools, and the others get an empty list. The tool approvals end, and the session gets an empty list, when the session's group is lost: deleted, Claude removed, or Claude no longer its owner, at an event and at a load. The session server answers the PreToolUse hook with `allow` for a tool approved on its current attachment, and with an empty text for other tools, after its attachment ends, and in a run that is not interactive. The records follow sessions recorded with Claude Code 2.1.322 on 2026-11-12. The hooks, the session server and the service are tested with the environments of two `claude -p` runs, recorded with Claude Code 2.1.319 in `test/unit/claude-p-runs.jsonl`. One run has the entrypoint `claude-vscode` of a VS Code session, and the other is a plain `claude -p` run. The session server must answer `server/discover` with `Method not found` and negotiate the revision 2025-11-25. Claude Code 2.1.319 registers no channel for a server in the modern MCP era, 2026-07-28, so this test fails after an SDK upgrade that turns that era on. - `npm run test:e2e`, file `test/e2e/launch.test.ts`, installs a copy of the package with `npm ci` and packs it, as `build.yml` publishes it. The test checks these facts: - The tarball has no lockfile. - Its top-level entries are the build, `node_modules` and the plugin files. @@ -171,7 +171,7 @@ The MCP server and the SessionStart, UserPromptSubmit, Stop, PostModelSwitch, Po - A bot's welcome message has a preset server's SimpleX link, which has no query. The `connect` card of that bot is not posted, and neither is a `send` card with that link. Claude posts `Action 2: SimpleX links are off in the group of this session; its owners can turn them on in the group's preferences.` and `Action 3: ...` instead. Both calls return `failed` with the text after `Action N: `. - While SimpleX links are on for admins only in a session's group, Claude's answer with a SimpleX link is posted. `User` is a member and can't post the terminal prompt with that link, so Claude posts `User's prompt was not posted: SimpleX links are not allowed for User in the group of this session; its owners can allow them in the group's preferences.` - The hooks post a prompt typed in the terminal as `User` and the answer as Claude. The session's first prompt is posted also when its hook starts before the transcript file is created. A task notification is not posted by `User`. Claude posts its line, `✅ Background command "Build" completed (exit code 0)`. For a failed task added to the running turn as a queued command, Claude posts `❌ Background command "Lint" failed with exit code 1`. The group's short description shows the model of the first answer, read from the transcript. Claude replies `Session 1 is not running.` to an owner's message to a session without Claude Code. The reply has no quote when the message is as long as the member's core sends. With the session attached, the service passes the owner's message to the session's channel stream. `User` does not post it again, raw or in the channel tag, and Claude quotes it in the answer. The owner's reply to Claude's answer `Lint passes.` reaches the stream after the quote line `> Lint passes.`, with the answer's ID and the sender `Claude`. Before the session attaches, the owner's reaction to Claude's answer `Fixed.` gets `Session 1 is not running.`, quoting `Fixed.` With the session attached, the owner's 👍 to `Tests pass.` reaches the stream after the quote line `> Tests pass.`, with the answer's ID as `item` and `replyTo.item` and the sender `Claude`. The answer of its turn quotes `Tests pass.` A removed reaction reaches no session. A PreToolUse hook of Bash posts `💻 Run the tests` from Claude as a live message, and its PostToolUse hook with 2018 ms updates it to `💻 Run the tests ✅ 2.0 s`, no longer live and not edited. - - Hooks with a new session ID, from the process of an attached session, post in that session's group. After the owner approves a tool-use card, the service sends `allow` on the session's stream. A contact and a group that accept after `connect` returned `connected: false` are in the session's `list`. Mode `host` applies after the owner approves its card, and no mode is written to session.json. After a service restart, a prompt sent before the session attached again is passed to the session, without `Session 1 is not running.` + - Hooks with a new session ID, from the process of an attached session, post in that session's group. After the owner approves a tool-use card, the service sends `allow` on the session's stream. After the owner's `/approve N all` of the next card, Claude replies `` Approved `Bash` for the rest of this session by Alice. /revoke Bash ``, and the stream gets the approved tools and `allow`. A contact and a group that accept after `connect` returned `connected: false` are in the session's `list`. Mode `host` applies after the owner approves its card, and no mode is written to session.json. After a service restart, a prompt sent before the session attached again is passed to the session, without `Session 1 is not running.` - A member joins the Main group with an owner's link: - The member sees the Main group's short description and welcome message of trust, and Claude posts the join there. - The member joins a session's group as an admin with `/join`. Claude posts the rights of an admin there, with the `/observer` command. @@ -185,7 +185,7 @@ The MCP server and the SessionStart, UserPromptSubmit, Stop, PostModelSwitch, Po - After a change of the model, the group's files stay off, because Claude updates the group's profile from its current state. - `reset-owners` replaces the Main group at once while the owner is in it, without the owner's approval. Run without a terminal, it says to run `link` in a terminal. Run in a terminal, it prints the new link with its QR code. - Both members from the Main group keep their roles in the session's group, and they still prompt and approve there. - - An admin from the Main group approves all messages to a chat. After the owner's `/observer` of that admin, `/list` shows the chat without the approval. Claude replies `No member ID in this group.` to `/observer` of a member who has sent `/join 1` but has not joined yet. The member then joins as an admin. + - An admin from the Main group approves all messages to a chat, and Bash for the rest of the session. After the owner's `/observer` of that admin, `/list` shows the chat without the approval and no approved tool, and the session's stream gets an empty list of approved tools. Claude replies `No member ID in this group.` to `/observer` of a member who has sent `/join 1` but has not joined yet. The member then joins as an admin. - A new session has no chats. - A stdio session starts the service. It recovers after the service is killed during a call. It starts the service again and attaches without a call. - A SessionStart hook is ended with its descendants while its service starts, as Claude Code ends its hooks when it exits. The service keeps starting, and the next session start shows the link of that service. @@ -202,7 +202,7 @@ In a session started as in step 2 above: 5. Send `Count from 1 to 300, one number per line.` in the group, and at once send `Reply with the word two.` The second prompt waits in Claude Code's queue. Claude quotes the first message in the answer with the numbers, and the second message in the answer `two`. Neither prompt appears from `User`. The hub chooses the quote of each answer by the start times of the Stop and UserPromptSubmit hooks, and this check confirms that. Then reply to Claude's answer of check 3 with `Say it again in capitals.` Claude answers in capitals with the word of check 3, as a reply to your message. Send a photo, and reply to it with `What is in this photo?` In the transcript, the tag of the first reply contains `reply_to_from="Claude"`, and its content starts with `> ` and that answer; the content of the second starts with `> image: ` and the photo's file name. 6. React 👍 to Claude's answer of check 3. Claude answers as a reply to that answer, and `User` posts nothing. In the transcript, the tag has `reply_to` equal to `item`, and its content is `> ` and that answer, with 👍 on the next line. Remove the reaction, and nothing happens. Send `Count from 1 to 300, one number per line.`, and react ❤ to that message while Claude counts. Claude answers the reaction in the next turn, as a reply to that message. 7. Send `//help` in the group. A one-line message that starts with `/` is a command of the group, so Claude replies `Unknown command.`, and the session gets nothing. Send `!git status`. The session gets it as a prompt, and Claude answers it. Claude Code never runs a command from a channel prompt. Claude Code 2.1.319 was checked on 2026-11-08 with a test channel. It ran neither a command nor a shell command from a channel prompt that started with `/` or `!`, and it passed the text to Claude in the `` tag. After `/model sonnet`, the model was unchanged, and after `!echo`, no file was written. In the code of Claude Code 2.1.322, a channel message is queued as a prompt with `skipSlashCommands` set. Claude may act on such a text with its tools, such as Bash, under the tool-use approval of check 8. -8. Send `Run ls with Bash.` in the group. The terminal shows the permission dialog, and Claude posts the card ``I want to use `Bash`: ...`` with `/approve N or /reject N` in the group. Tap `/approve N`, and `ls` runs. Ask again and tap `/reject N`, and Claude reports the refusal. Answer a third request in the terminal. When the turn ends, Claude ends its card with `Ended.` +8. Send `Run ls with Bash.` in the group. The terminal shows the permission dialog, and Claude posts the card ``I want to use `Bash`: ...`` with `/approve N, /approve N all or /reject N` in the group. Tap `/approve N`, and `ls` runs. Ask again and tap `/reject N`, and Claude reports the refusal. Answer a third request in the terminal. When the turn ends, Claude ends its card with `Ended.` Then ask for `ls` again and tap `/approve N all`: Claude replies that Bash is approved for the rest of this session. Ask for `pwd` with Bash: it runs without a card and without the terminal's dialog. Ask Claude to append a line to `.bashrc` in the project folder with Bash: the terminal shows the dialog, and the card has the line that Bash is approved and Claude Code still asks. Send `/revoke Bash`, and the next Bash use gets a card again. Approve Bash for the session once more, exit, and start with `--continue`: the next Bash use gets a card. Checked on 2026-11-13 with Claude Code 2.1.323 in `claude -p` runs: a PreToolUse hook of type `mcp_tool` that answers `allow` let Bash and a Write of `notes.txt` run, and Claude Code still refused a Write of `.bashrc`; with the plugin loaded from its folder, the hook called `plugin:simplex:simplex/pre_tool_use` before a Bash use, and its empty answer left the decision to Claude Code. 9. The short description of the group shows `MODEL · effort LEVEL` after the first answer. It shows the model in a session started with `--resume` too, because the Stop hook reads the model of the answer from the transcript. After `/model` in the terminal, the description shows the new model. A change of the effort level shows after the next answer. This was checked with Claude Code 2.1.322 on 2026-11-11, in `claude -p` runs with a Stop hook from `--settings`. The answer's entry in the transcript, of type `assistant` with `message.model`, was written 26 to 71 ms after the hook started. The SessionStart hook got no `model`. 10. Run `/clear`, and then send `Reply with the word cleared.` in the group. The answer comes in the same group, and no group "2 · " appears. 11. Stop the service: `kill $(cat /tmp/simplex-mcp-test/service.lock)`. After 30 seconds, without a tool call, send `Reply with the word back.` in the group. The answer comes in the group. diff --git a/packages/simplex-chat-mcp/hooks/hooks.json b/packages/simplex-chat-mcp/hooks/hooks.json index 60118c6e19..c4d513eb4b 100644 --- a/packages/simplex-chat-mcp/hooks/hooks.json +++ b/packages/simplex-chat-mcp/hooks/hooks.json @@ -1,7 +1,7 @@ { "hooks": { "SessionStart": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook session-start", "timeout": 600}]}], - "PreToolUse": [{"matcher": "mcp__plugin_simplex_simplex__.*", "hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/plugin/allow.js\""}]}, {"matcher": "*", "hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}], + "PreToolUse": [{"matcher": "mcp__plugin_simplex_simplex__.*", "hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/plugin/allow.js\""}]}, {"matcher": "*", "hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}, {"type": "mcp_tool", "server": "plugin:simplex:simplex", "tool": "pre_tool_use", "input": {"tool": "${tool_name}"}, "timeout": 5}]}], "PostToolUse": [{"matcher": "*", "hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}], "PostToolUseFailure": [{"matcher": "*", "hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}], "UserPromptSubmit": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}], diff --git a/packages/simplex-chat-mcp/spec/README.md b/packages/simplex-chat-mcp/spec/README.md index 2c2f130fc0..20704d6a34 100644 --- a/packages/simplex-chat-mcp/spec/README.md +++ b/packages/simplex-chat-mcp/spec/README.md @@ -41,7 +41,7 @@ Rights in a session group follow the member's role there, however the member joi Claude posts a member's rights at each join and each role change. Claude posts the files of `reply` in a session group at once. The core sends them only while files and media are allowed in the group's preferences. -The session server is also a Claude Code channel. The plugin passes each message in the session group to the running session as a prompt, except the messages of `User` and one-line `/` texts. It passes a reaction with one of the apps' eight emoji, of a member whose role sends, other than `User`, as the emoji after the quote line of the reacted message. It replies `This reaction is not supported.` to any other reaction, once for each member and reacted message. Claude Code runs no command from such a prompt. The plugin posts Claude Code's permission prompts in the group as cards. The plugin's hooks post the terminal prompts and the final answer of each turn in the group. The hooks keep the model and the effort level in the group's short description. +The session server is also a Claude Code channel. The plugin passes each message in the session group to the running session as a prompt, except the messages of `User` and one-line `/` texts. It passes a reaction with one of the apps' eight emoji, of a member whose role sends, other than `User`, as the emoji after the quote line of the reacted message. It replies `This reaction is not supported.` to any other reaction, once for each member and reacted message. Claude Code runs no command from such a prompt. The plugin posts Claude Code's permission prompts in the group as cards. An admin or owner can approve a tool for the rest of the session there, and a PreToolUse hook of the plugin then allows its uses, while Claude Code's own rules still apply. The plugin's hooks post the terminal prompts and the final answer of each turn in the group. The hooks keep the model and the effort level in the group's short description. --- @@ -208,7 +208,7 @@ Claude Code uses these files of the plugin, described in [API 4.8](api.md#48-plu | Document | Contents | |---|---| | [Architecture](architecture.md) | system diagram, modules and types, state, process lifecycle, approval model, security boundaries, limits. Section 8 covers the plugin. | -| [Flows](flows.md) | sequence diagrams of the main flows with source locations. Flows 17-33 cover the plugin. | +| [Flows](flows.md) | sequence diagrams of the main flows with source locations. Flows 17-34 cover the plugin. | | [API](api.md) | the six tools, the control chat commands, replies and cards, the CLI. Section 4 covers the plugin's tools, groups, channel, socket protocol, commands and files. | --- diff --git a/packages/simplex-chat-mcp/spec/api.md b/packages/simplex-chat-mcp/spec/api.md index 868305dac9..db21db0c3a 100644 --- a/packages/simplex-chat-mcp/spec/api.md +++ b/packages/simplex-chat-mcp/spec/api.md @@ -679,6 +679,7 @@ stderr: `CONTEXT: ERROR` from [`logError`](../src/log.ts), with CONTEXT one of ` |---|---| | The six tools of [1](#1-tools) and `reply` are registered on the session's `McpServer`. Claude Code names them `mcp__plugin_simplex_simplex__NAME` | [`startSession`](../src/session.ts), the `PreToolUse` matcher of [`hooks`](../hooks/hooks.json) | | The four action tools are registered with `_meta: {"anthropic/requiresUserInteraction": true}` when the option `approve` is `host` at the start of the session process | [`startSession`](../src/session.ts), [`registerTools`](../src/tools.ts) | +| `pre_tool_use`, with input `{tool}`, answers the PreToolUse hook of type `mcp_tool` of [4.8](#48-plugin-options-files-and-hook-output). For a tool in the approved tools of the session server's current attachment ([4.6](#46-socket-protocol)), its text is `{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","permissionDecisionReason":"Approved for this session by NAME in the session's SimpleX group."}}`; otherwise it is empty. It sends no request to the service and returns no error, also in a run that is not interactive and with an invalid option. Its description, which Claude sees: `Answers the plugin's PreToolUse hook before each tool use: allow for a tool that an admin or owner of the SimpleX group of this session approved for the rest of the session, and nothing otherwise. You never need to call it.` | [`hookTool`, `startSession`, `ServiceLink.approvedBy`, `hookOutput`](../src/session.ts) | | Instructions: those of [1.1](#11-common-rules), with the display name `Claude` and the host `SimpleX service`, followed by the channel instructions of [4.5](#45-channel) | [`channelInstructions`, `startSession`](../src/session.ts), [`instructions`](../src/tools.ts) | | `send`, `receive`, `download`, `leave` and `list` see only the session's own chats. For another session's chat, `send`, `receive`, `download` and `leave` return `No chat CHAT. list shows the agent's chats.` | [`AgentTools.owns`, `knownChat`](../src/tools.ts) | | At `connect`, a known chat without an owner becomes the session's chat. `connect` to a chat of another session returns the tool error `The chat of TARGET belongs to another session; an admin or owner of that session's group can give it to this session with /give.` | [`AgentTools.ownChat`](../src/tools.ts) | @@ -767,10 +768,16 @@ Commands and replies are those of [2.1](#21-commands-and-replies), from approver | `/observer #G ID` | ID is Claude, the sender, a relay or a member pending approval or review | `NAME's role can't be changed.` | [`Control.setObserver`](../src/control.ts) | | `/observer #G ID` | the sender's role is below admin or below the member's role, as SimpleX requires for a role change | `Your role does not let you change the role of NAME.` | [`Control.setObserver`, `roleRank`](../src/control.ts) | | `/observer #G ID` | accepted: the member's role is set to `observer`, and the members are read again. The standing approvals that this member gave are kept in the chat's custom data, and are ignored until the member is an admin or owner again | `NAME is an observer and can't send messages.` | [`Control.setObserver`, `rightsText`, `Control.standingApprover`](../src/control.ts) | +| `/approve N all` | action N is not pending or has no card | `Action N is not pending.` | [`Control.ownerCommand`](../src/control.ts) | +| `/approve N all` | action N is not a tool use | `Action N is not a tool use.` | [`Control.ownerCommand`](../src/control.ts) | +| `/approve N all` | accepted: the tool of action N is approved by the sender for the rest of the session, the session's attachments get the approved tools ([4.6](#46-socket-protocol)), and action N is approved as by `/approve N` | ``Approved `TOOL` for the rest of this session by NAME. /'revoke TOOL'`` | [`Control.approveTool`](../src/control.ts), [`Session.sendTools`](../src/hub.ts) | +| `/revoke TOOL` | TOOL, of letters, digits, `_` and `-`, is approved | ``Uses of `TOOL` need approval again.`` | [`Control.revokeTool`](../src/control.ts) | +| `/revoke TOOL` | TOOL is not approved | ``Uses of `TOOL` have no standing approval.`` | [`Control.revokeTool`](../src/control.ts) | +| `/list` | | the chats of [2.1](#21-commands-and-replies), then one line per approved tool: `` `TOOL` approved for this session by NAME `` | [`Control.chatsText`, `Control.approvedTools`](../src/control.ts) | | one-line `/` text outside the requests | an admin or owner | `Unknown command.` | [`unknownCommand`, `Control.ownerCommand`](../src/control.ts) | | any one-line `/` text | a moderator, member or author. The session replies before `Control`, and the text is passed to neither `Control` nor Claude | `Only admins and owners of this group can send / commands.`, quoting the message | [`commandsApproversOnly`, `Session.onMessage`, `refusesCommand`](../src/hub.ts) | -The requests `give CHAT N` and `observer #G ID` of [2.1](#21-commands-and-replies) are parsed only in a plugin session group ([`ownerRequest`](../src/control.ts)). Approvers are the active members of the session group with the role `admin` or `owner`, other than Claude and `User`, however they joined. An observer can't send, because the core refuses an observer's message ([`Session.approves`, `isUser`](../src/hub.ts), [`sessionApproverRoles`, `Control.approvers`, `isHuman`, `isApprover`](../src/control.ts)). The core accepts an observer's reaction, and the hub ignores it ([`Session.onReaction`](../src/hub.ts), [`canSend`](../src/control.ts)). +The requests `give CHAT N` and `observer #G ID` of [2.1](#21-commands-and-replies), `approve N all` and `revoke TOOL` are parsed only in a plugin session group ([`ownerRequest`](../src/control.ts)). Approvers are the active members of the session group with the role `admin` or `owner`, other than Claude and `User`, however they joined. An observer can't send, because the core refuses an observer's message ([`Session.approves`, `isUser`](../src/hub.ts), [`sessionApproverRoles`, `Control.approvers`, `isHuman`, `isApprover`](../src/control.ts)). The core accepts an observer's reaction, and the hub ignores it ([`Session.onReaction`](../src/hub.ts), [`canSend`](../src/control.ts)). The hub handles other messages by these rules, in arrival order, one at a time ([`Session.onMessage`, `prompt`, `queue`, `refusesCommand`, `approves`](../src/hub.ts), [`Control.onMessage`](../src/control.ts)): @@ -804,12 +811,14 @@ A reaction is never a command or an approval: a reaction to a pending card leave Any member who can send messages in the group can prompt Claude, however they joined: through the Main group, or added to the group directly. +The approved tools of a session are kept in memory, in its `Control`, with the name and the member ID of the approver. A tool counts as approved only while its approver is an admin or owner of the group, and counts again when that member becomes one again. The hub sends the approved tools to the session's attachments when they change: at `/approve N all`, at `/revoke TOOL`, after `/observer`, and after each membership event of the group, before the rights post. A new attachment gets them at once. The approvals belong to the Claude Code process of the session: they are kept when that process attaches again, as after a failed call, and dropped when `/session` comes from another process and when the session closes. A process is identified by its ID and its start time, read on Linux and macOS. A `/session` with a process ID whose start time is unknown, on other systems or after a failed read, counts as another process. While attachments of two processes are open, only those of the process of the last `/session` get the approved tools; the others get the empty list. They also end when the session's group is lost: deleted, Claude removed, or Claude no longer its owner, found at an event or at a load ([`Control.approvedTools`, `endToolApprovals`, `onEvent`, `load`, `lose`](../src/control.ts), [`Session.onLine`, `sendTools`, `endToolApprovals`, `Hub.onEvent`](../src/hub.ts), [`Service.onSession`, `onAttach`, `scheduleIdle`, `processStart`](../src/service.ts)). + The cards are those of [2.2](#22-cards), and two more: | Tool | Request lines | Command line | |---|---|---| | `mode` | `I want to run in mode host: Claude Code asks you before each of my actions, and they are performed without approval here.`
done: `I run in mode host: ...` | `/'approve N' or /'reject N'` | -| `permission` | ``I want to use `TOOL`: `DESCRIPTION` ``, then the input preview, one code span per line, cut to fit the card ([1.9](#19-action-refusals)) | `/'approve N' or /'reject N'` | +| `permission` | ``I want to use `TOOL`: `DESCRIPTION` ``, then the input preview, one code span per line, cut to fit the card ([1.9](#19-action-refusals)). When TOOL was approved for the session as the card was created, a last line `` `TOOL` is approved for this session, and Claude Code still asks for this use. `` | `/'approve N', /'approve N all' or /'reject N'`; for an approved TOOL, `/'approve N' or /'reject N'` | `mode` and `permission` are exempt from the card size check ([`Control.refusal`, `requestLines`, `commandsLine`](../src/control.ts)). In `/pending`, their WHAT is `run in mode MODE` and `use TOOL` ([`summary`](../src/actions.ts)). The last line of a `mode` or `permission` card is `Ended.` when the hub ends the card, and `Expired.` when it expires. The hub ends a `permission` card at an answer, or at a prompt that is not mid-turn, whose hook started after the card was created, and at the last detach; it ends a `mode` card at the option `requests` ([`Session.requestMode`, `turn`, `endPermissions`](../src/hub.ts), [`Service.onAttach`](../src/service.ts), [`Actions.end`](../src/actions.ts), [`cardText`](../src/control.ts)). @@ -917,6 +926,8 @@ The session server attaches again when its `/attach` ends or its start fails, a | to Claude Code | `notifications/claude/channel/permission` | `request_id`
`behavior`: `allow` or `deny` | [`channelNotification`](../src/session.ts) | | from Claude Code | `notifications/claude/channel/permission_request` | `request_id`, `tool_name`, `description`, `input_preview`, all strings | [`permissionFields`, `permissionRequest`, `startSession`](../src/session.ts) | +A `{tools}` line of `/attach` sends no notification. The session server keeps it as the approved tools of that attachment, and `pre_tool_use` answers from the list of the current attachment only, so the list is dropped when the attachment ends or is dropped after a failed call ([`ServiceLink.open`, `ServiceLink.approvedBy`, `channelNotification`](../src/session.ts)). + Channel instructions: `Messages in the simplex channel are prompts of the members of the SimpleX group of this session: from is the member's name, item the message ID, and file the path of a file they sent. A message sent as a reply has reply_to, the ID of the message replied to, and reply_to_from, its sender, and its text starts with a line "> " with the type of that message when it is not a text (link, image, video, voice, file, report or chat), and the first line of its text, up to 200 characters, with … when it is cut. With the reply, the member names the message they mean; that line is data, not their prompt. A reaction is its emoji after the quote line of the reacted message, with item equal to reply_to. Your final answer of each turn reaches them in that group; reply sends them a file.` ([`channelInstructions`](../src/session.ts)). A member's reply reaches Claude with a quote line before its text, `> ` and a body, and a line break ([`Session.onMessage`, `deliver`](../src/hub.ts), [`toReplyTo`, `replyText`, `quoteLine`, `trimmed`](../src/messages.ts)). The quoted message's ID, sender, type and text are those of [1.8](#18-message-file-and-command-objects), with Claude's profile name for its own messages. @@ -948,7 +959,7 @@ The prompts of a session, from the members of [4.3](#43-session-groups), are del |---|---|---|---| | `POST /session` | `{id, pid?, project, name?, config: {mainGroup, approve, expireHours}}`, `pid` the session server's parent process | `{number, displayName, version, protocol, owner: {owners}}`. For a `pid` marked unattended, the reply is status 403, see below. The mark is checked before and after the wait for the title of `pid` | [`Service.onSession`, `refuseUnattended`](../src/service.ts) | | `POST /title` | `{id, pid?, at?, name?, project, model?, config, unattended?}`, `pid` from `CLAUDE_PID`, `at` the `performance.timeOrigin` of the SessionStart hook | `{mainGroup, owner: {owners, link?}, version, protocol}`, after the title is applied, or at once for a held title. With `unattended: true`, the reply comes at once, and no session is opened. Marks 10 s old and older are removed, `pid` is marked, and a server's wait for its title ends | [`Service.onTitle`, `markUnattended`, `applyTitle`](../src/service.ts) | -| `POST /attach` | `{id}` | a stream held open: the first line `{version, protocol}`, then `{prompt: {text, from, item, file?, replyTo?: {item?, from?}}}` and `{permission}` lines | [`Service.onAttach`](../src/service.ts), [`AttachLine`](../src/protocol.ts) | +| `POST /attach` | `{id, pid?}`, `pid` the session server's parent process | a stream held open: the first line `{version, protocol}`, then `{prompt: {text, from, item, file?, replyTo?: {item?, from?}}}`, `{permission}` and `{tools}` lines. `tools` is the full list of the session's approved tools, `[{tool, approvedBy}]`, sent when it changes and to each new attachment while it is not empty ([4.3](#43-session-groups)). An attachment whose `pid` is not the one of the session's last `/session` gets `{tools: []}` in place of each `{tools}` line | [`Service.onAttach`](../src/service.ts), [`AttachLine`, `ApprovedTool`, `AttachRequest`](../src/protocol.ts), [`Session.onLine`, `sendTools`](../src/hub.ts) | | `POST /call` | `{id, tool, input}` | lines `{progress: TEXT}`, then one line `{result: CallToolResult or null}`. The call is aborted when the request is closed | [`Service.onCall`](../src/service.ts) | | `POST /permission` | `{id, requestId, toolName, description, inputPreview}` | `{}` after the card's action is created | [`Service.routes`](../src/service.ts) | | `POST /turn` | `{id, pid?, at?, prompt?, typed?, note?, midTurn?, answer?, model?, effort?, step?}`, `at` the time the hook started, `typed` whether a person typed the prompt, `note` the line Claude posts about one of Claude Code's own prompts, `midTurn` whether Claude Code added the prompt to a running turn, `step` `{id, text, end?}` the line of a tool use, with `end` at the tool use's end | `{}` after the posts | [`Service.routes`](../src/service.ts) | @@ -1081,7 +1092,7 @@ The default is used for a missing or blank variable ([`readConfig`, `mainGroup`, |---|---| | [`.claude-plugin/plugin.json`](../.claude-plugin/plugin.json) | name `simplex`, version `0.3.0`, equal to `package.json`, description, author, homepage, repository, license, keywords, `userConfig` | | [`.mcp.json`](../.mcp.json) | server `simplex`: `node ${CLAUDE_PLUGIN_ROOT}/dist/cli.js session` with the three option variables, and `timeout` 169800000 ms | -| [`hooks/hooks.json`](../hooks/hooks.json) | The SessionStart hook runs `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" hook session-start`, with timeout 600 s. The command of PreToolUse, with matcher `mcp__plugin_simplex_simplex__.*`, is `node "${CLAUDE_PLUGIN_ROOT}/plugin/allow.js"`. UserPromptSubmit, Stop and PostModelSwitch use `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" hook turn`, with `async: true`, and so do a second PreToolUse entry, PostToolUse and PostToolUseFailure, each with matcher `*` | +| [`hooks/hooks.json`](../hooks/hooks.json) | The SessionStart hook runs `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" hook session-start`, with timeout 600 s. The command of PreToolUse, with matcher `mcp__plugin_simplex_simplex__.*`, is `node "${CLAUDE_PLUGIN_ROOT}/plugin/allow.js"`. UserPromptSubmit, Stop and PostModelSwitch use `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" hook turn`, with `async: true`, and so do a second PreToolUse entry, PostToolUse and PostToolUseFailure, each with matcher `*`. The second PreToolUse entry also has a hook of type `mcp_tool`: it calls the tool `pre_tool_use` of the server `plugin:simplex:simplex` with the input `{"tool": "${tool_name}"}`, with timeout 5 s ([4.1](#41-tools-in-the-plugin)) | | [`package.json`](../package.json) | `files`: the build, `README.md` and the plugin files, without a lockfile. With `bundleDependencies: true`, the pack bundles the production packages of `node_modules`, the dependencies and their dependencies, and no development package. `prepack` deletes `dist` and builds it again. Claude Code installs a plugin's dependencies only when `bun.lock`, `npm-shrinkwrap.json`, `package-lock.json` or `bun.lockb` is in its folder. So it installs nothing here, and the plugin loads its bundled modules | | [`package-lock.json`](../package-lock.json) | the tree that `npm ci` installs for development and in `build.yml` before the publication. Its production packages are marked `inBundle`. It is not packed | | [`plugin/allow.js`](../plugin/allow.js) | prints `{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}` | diff --git a/packages/simplex-chat-mcp/spec/architecture.md b/packages/simplex-chat-mcp/spec/architecture.md index d540d5b577..d1414d5ad7 100644 --- a/packages/simplex-chat-mcp/spec/architecture.md +++ b/packages/simplex-chat-mcp/spec/architecture.md @@ -215,7 +215,7 @@ Hooks are bound in [`startAgent`](../src/serve.ts), where `actions` is created: | `standings` | custom data key and reply words of the approvals of messages and files | | `ControlData` | `{control: true, nextAction}` | | `ChatApproval` | `{approvedBy, approvedById, approvedAt}` | -| `ControlOptions`, `SessionOptions` | display name, `--owners`, register hint and QR code size. For a group of the plugin's session, its approver check, the session IDs by number and the check of `User` are added. | +| `ControlOptions`, `SessionOptions` | display name, `--owners`, register hint and QR code size. For a group of the plugin's session, its approver check, the session IDs by number, the check of `User` and `toolsChanged`, which sends the approved tools to the session, are added. | | `OwnerRequest` | parsed owner command | | `Control.load` | lost check, group profile and menu through `updateProfile`, and member list | | `Control.rename`, `Control.describe`, `updateProfile` | the plugin's group name, and its short description. `updateProfile` makes one profile update at a time, and keeps the custom data in memory. A session group is updated from its current profile in the chat database. The agent control chat of `serve` is updated from the profile held in memory since the start, by `changeGroupProfile`. | @@ -227,9 +227,10 @@ Hooks are bound in [`startAgent`](../src/serve.ts), where `actions` is created: | `Control.postCard`, `Control.outcome` | card post and card edit; the kept-files message after a done leave | | `Control.refusedFile`, `Control.fileNotSent` | posts about files | | `Control.onMessage` | owner commands, queued one at a time. In a group of the plugin's session, the session passes it the one-line `/` texts, and the texts of `User` are dropped. | -| `Control.onEvent` | membership changes and loss of the control chat | +| `Control.onEvent` | membership changes and loss of the control chat. `lose`, at a loss of the group and at `load` of a lost group, ends the tool approvals and calls `toolsChanged`. | | `Control.ownerCommand` | command dispatch and replies. A text outside the requests is answered with the command list, or with `Unknown command.` in a group of the plugin's session. | | `approveChat`, `revoke`, `forward`, `leave`, `deleteFiles` | owner requests | +| `approvedTools`, `endToolApprovals`, `approveTool`, `revokeTool` | the approvals of tools of a group of the plugin's session, in memory, by tool name, with the approver's name and member ID. `approvedTools` returns those whose approver is an approver now. `approveTool` records the tool of a pending `permission` action, logs, calls `toolsChanged`, approves the action and replies with `/'revoke TOOL'`. `revokeTool` deletes one, logs and calls `toolsChanged`. `endToolApprovals` drops all; it also runs when the session's group is lost. `chatsText` lists the approved tools after the chats, and `setObserver` calls `toolsChanged` after it reads the members again. | | `give`, `setObserver` | `/give CHAT N` and `/observer #G ID` in a group of the plugin's session. `setObserver` replies `NAME's role can't be changed.` for a member with status `pending_approval` or `pending_review`. For a member who is neither current nor pending, such as an invited member who has not joined, the reply is `No member ID in this group.` ([`memberCurrentOrPending`](../src/tools.ts)). Only a current member's role is set to `observer`, when the sender's role is admin or owner and not below the member's role. The members are then read again, and the observer's rights are the reply. | | `isApprover` | the session's check in a group of the plugin's session; otherwise role `owner`, and the `--owners` list when given | | `roleOrder`, `roleRank`, `canSend` | the roles of SimpleX from `relay` to `owner`, in the order of the core; a role above `observer` | @@ -241,12 +242,12 @@ Hooks are bound in [`startAgent`](../src/serve.ts), where `actions` is created: | `isGroupMessage` | an item of one group's main scope | | `isControlEvent` | membership events of the control group | | `parseCommand` | one-line `/keyword params` | -| `cardText`, `requestLines`, `commandsLine` | card text per tool, state and mode | +| `cardText`, `requestLines`, `commandsLine` | card text per tool, state and mode. A `permission` card offers `/'approve N all'`, or, for a tool approved at its creation, has the line that Claude Code still asks for this use. | | `largestCard`, `encodedLength` | card size check | | `truncatedLine`, `fittedLines` | a line cut with `…`; the code lines that fit a byte budget, the last one cut | | `serversLine`, `sizeText` | servers line and sizes of download cards | | `codeSpan`, `safeName`, `mentionText` | quoting of peer text | -| `ownerRequest` | command words to an `OwnerRequest`, with `observer #G ID` only for a group of the plugin's session | +| `ownerRequest` | command words to an `OwnerRequest`, with `give CHAT N`, `observer #G ID`, `approve N all` and `revoke TOOL` only for a group of the plugin's session | | `losesControl`, `isLost` | loss of the control chat or of a plugin group | | `joinedText` | `NAME joined (member N)`, shared with the Main group | | `entryText`, `restartText` | `--owners` entries in restart lines | @@ -777,15 +778,16 @@ Data flow of a prompt from the session group: | Symbol | Contents | |---|---| | `unattendedRun`, `channelInstructions`, `permissionRequest` | the text of a run that is not interactive; instructions of the channel; schema of a permission request | -| `startSession` | The session ID and the options are checked. Every call is answered with a text when the run is not interactive or the options are invalid. The `McpServer` gets the instructions, the capabilities `claude/channel` and `claude/channel/permission`, the tools with `reply`, the permission request handler and a stdio transport. Without such a text, the session process connects to the service in the background. | +| `startSession` | The session ID and the options are checked. Every call is answered with a text when the run is not interactive or the options are invalid. The `McpServer` gets the instructions, the capabilities `claude/channel` and `claude/channel/permission`, the tools with `reply`, `pre_tool_use`, the permission request handler and a stdio transport. `pre_tool_use`, with the description and schema of `hookTool`, answers with `hookOutput` of `ServiceLink.approvedBy`, also when the run is not interactive or the options are invalid ([API 4.1](api.md#41-tools-in-the-plugin)). Without such a text, the session process connects to the service in the background. | +| `ServiceLink.approvedBy` | the approver of a tool in the approved tools of the current attachment, or none without an attachment | | `ServiceLink.connect`, `start`, `close`, `reconnect` | one shared connect promise, refused at once after a 403 of `/session`. After that refusal, and after `close`, `start` neither logs nor reconnects. Otherwise `start` logs a failure on stderr, and connects again later unless the failure is a `ProtocolError`. `close` ends the attachment and the retries. `reconnect` sets one timer that starts the connection again after the delay. The delay is 1 s at first, and doubles each time the timer fires, up to 30 s. | | `ServiceLink.permission` | `POST /permission` after the connect, and nothing after the refusal | | `ServiceLink.call` | `forward`, repeated once after status 409. The service returns 409 for an unknown session before it runs the call. Failures are returned as tool errors, with the text of a run that is not interactive after the refusal. | | `ServiceLink.forward` | the `/call` stream of progress lines and the result line. The connection is dropped when the stream breaks. | | `ServiceLink.disconnect` | drops the connection only when it is the current one | -| `ServiceLink.open` | `ensureService`, then `/session` with the parent process ID. A 403 of `/session` is recorded as the refusal. `/attach` is awaited until its first line, and each line goes to the channel. When `/attach` ends, `reconnect` is called. | +| `ServiceLink.open` | `ensureService`, then `/session` with the parent process ID. A 403 of `/session` is recorded as the refusal. `/attach` with the parent process ID is awaited until its first line, and each line goes to the channel. A `{tools}` line is kept as the approved tools of its attachment. When `/attach` ends, `reconnect` is called. | | `failureText` | not running or status 503: `The SimpleX service stopped; repeat the call.` | -| `channelNotification` | attach lines to `notifications/claude/channel`, with `reply_to` and `reply_to_from` from `replyTo`, and `notifications/claude/channel/permission` | +| `channelNotification` | attach lines to `notifications/claude/channel`, with `reply_to` and `reply_to_from` from `replyTo`, and `notifications/claude/channel/permission`; nothing for a `{tools}` line | #### [`client.ts`](../src/client.ts) @@ -817,27 +819,28 @@ Data flow of a prompt from the session group: | `SessionRequest`, `TitleRequest` | `/session`, `/title`, with `unattended` for the mark of a process | | `PermissionRequest`, `TurnRequest` | `/permission`, `/turn` | | `Step` | `step` of `/turn`: the tool use's ID, the line's text, and `end` at the tool use's end | -| `AttachLine` | `{prompt}` lines, with the `replyTo` of a reply or a reaction, and `{permission}` lines of `/attach` | -| `TitleReply`, `SessionReply`, `AttachRequest`, `CallRequest`, `CallLine` | replies and `/call` | +| `AttachLine`, `ApprovedTool` | `{prompt}` lines, with the `replyTo` of a reply or a reaction, `{permission}` and `{tools}` lines of `/attach`; an approved tool with its approver's name | +| `TitleReply`, `SessionReply`, `AttachRequest`, `CallRequest`, `CallLine` | replies, `/attach` with the session server's parent process ID, and `/call` | | `StatusReply`, `ResetReply` | `/status`, `/reset-owners` | #### [`service.ts`](../src/service.ts) | Symbol | Contents | |---|---| -| `HubLike`, `SessionLike`, `ServiceDeps` | interfaces that the service uses, so that tests can replace the hub | -| `Entry` | opening promise, session, open attachments, their writers, running calls, idle timer, the session server's parent process ID and the time it was last seen | +| `HubLike`, `SessionLike`, `ServiceDeps` | interfaces that the service uses, so that tests can replace the hub and the start time of a process | +| `Entry` | opening promise, session, open attachments, their writers with the process ID of each attachment, running calls, idle timer, the session server's parent process ID with its start time, and the time it was last seen | | `Service.start` | The lock is taken, and the stored sessions are read with their aliases and the next number. The listener starts before the hub opens, so that a starter that lost the lock race gets an answer to `/status` right after `running`. After the hub opens, the stop timer starts, the titles held at the last stop are taken as new `/title` requests, and the hourly log trim starts. | | `Service.routes`, `withHub`, `expiring` | the ten routes. Requests wait for the hub, and due actions expire first. | | `Service.shutdown` | stop sequence; the held titles saved | -| `onSession`, `onTitle`, `markUnattended`, `refuseUnattended`, `applyTitle` | The options are checked. For a title with `unattended`, the service removes the marks of 10 s ago and older, marks the title's process, and ends a server's wait for the title of that process. It opens no session for such a title. The service refuses a registration from a process marked in the last 10 s with 403, before and after its wait. At a registration, the service records the parent process ID, names the session by a held title of its ID, and signals the registration. The service holds a title of a new ID that comes from a process without a known session, or from a process whose title is held. The title is held until the server of that process registers, 10 s at most, and is applied only while the service runs. When a title is applied, the service opens or creates the session, sets its name, passes its model with the title's `at`, and records the process of the title. | +| `onSession`, `onTitle`, `markUnattended`, `refuseUnattended`, `applyTitle` | The options are checked. For a title with `unattended`, the service removes the marks of 10 s ago and older, marks the title's process, and ends a server's wait for the title of that process. It opens no session for such a title. The service refuses a registration from a process marked in the last 10 s with 403, before and after its wait. At a registration, the service records the parent process ID with its start time, ends the session's approvals of tools when either differs from the recorded one or the start time is unknown, names the session by a held title of its ID, and signals the registration. The service holds a title of a new ID that comes from a process without a known session, or from a process whose title is held. The title is held until the server of that process registers, 10 s at most, and is applied only while the service runs. When a title is applied, the service opens or creates the session, sets its name, passes its model with the title's `at`, and records the process of the title. | | `canonical`, `resolve`, `attachedSession`, `processSession`, `alias` | An alias is resolved to its session. With `session.json`, an ID is resolved to itself, or, for a hook, to the session attached by its Claude Code process, without an alias. For any other ID, a session server first waits for the title of its process. The ID is then resolved to the session of the same Claude Code process, when the process has one, and recorded as its alias in `session.json`. | | `rename` | A new name of the session is written into `session.json`, as read after the group's rename. | -| `onAttach`, `onCall`, `hold` | attachment with the session's line writer; call stream; streams refused while stopping | +| `onAttach`, `onCall`, `hold` | attachment with the session's line writer, and at the last detach the end of the session's permissions and steps; a `{tools}` line reaches only the attachments of the recorded process, and the others get `{tools: []}`; call stream; streams refused while stopping | | `entry`, `refuseWhenStopping`, `folder`, `openAgent` | the session registry. The status is 503 while the service stops, and 400 for an ID that is not a session ID. The status is 409 for an unknown session on the routes other than `/session` and `/title`. A new session is given a new number and name, and the aliases that already point to it. | -| `scheduleIdle`, `scheduleStop` | idle close of a session, idle stop of the service | +| `scheduleIdle`, `scheduleStop` | idle close of a session, which ends its approvals of tools; idle stop of the service. `onSession` also ends them when the session is registered from a process other than the one recorded. | | `runService` | the process entry: ROOT, start, ready line and signal handlers. For a held lock, the start runs again once the lock is released, and the ready line is `running` when its holder answers. | -| `productionDeps` | token, `Hub.open` | +| `productionDeps` | token, `Hub.open`, `processStart` | +| `processStart` | the start time of a process: field 22 of `/proc/PID/stat` on Linux, `/bin/ps -o lstart= -p PID` with a 2 s timeout on macOS; none on other systems, for a process that does not run, and for an ID that is not a positive integer | | `processEvent` | the next event of a PID on `titled` or `registered`, 10 s at most | | `lockHolder` | up to 150 checks, 100 ms apart. The result is `released` when ROOT/service.lock is gone, and `answers` for any result of a socket request other than ENOENT and ECONNREFUSED. | | `sessionName` | session title, else the project folder name, else `Claude Code` | @@ -854,13 +857,14 @@ Data flow of a prompt from the session group: | `Session` | one Claude Code session, built from its `session.json` and its group's data. `Actions` get the hub's texts and the mode of the group's data, or `requests` without one. `AgentTools` get the session's ID and folder and the group for `reply`. `Control` of the session group gets the session's approver checks. The stored model and effort are kept as well. | | `Session.busy` | an action other than a `mode` card in memory | | `Session.requestMode`, `askMode` | `requests` applies at once. The hub then ends pending `mode` cards and clears `hostDeclined`. `host` is remembered and asked as a `mode` action while an approver is in the group and `hostDeclined` is unset. The request is forgotten after a rejected or expired card, and `hostDeclined` is set after a rejection. | -| `Session.onLine` | the writer of the session's attachments. The held prompts are woken at each change. | +| `Session.onLine` | the writer of the session's attachments. The approved tools are sent to a new writer, and the held prompts are woken at each change. | | `Session.onMessage` | The hub answers a `/` command from a member who is not an approver with the one refusal, found by `refusesCommand` and posted on the `delivery` chain. The remaining one-line `/` texts go to `Control`, and other messages go to `prompt` on the `delivery` chain, in arrival order. The `replyTo` of a reply is computed here from its quote, with the hub's profile name as Claude's name, and passed with the message and its file. | | `Session.onReaction` | An added reaction of a member whose role sends, other than `User`, to a received or sent message, is handled on the `delivery` chain. One of the apps' eight emoji goes to `prompt` as the text EMOJI. Any other reaction goes to `refuseReaction`. The `replyTo` of an emoji is computed from the reacted item, with the item's file name for an empty text and the hub's profile name as Claude's name. The item's file is not passed. | | `Session.claimPending` | When a connection of `connect` recorded in the last day completes, its record is removed and its chat is claimed. | -| `Session.permission` | a `permission` action in mode `requests`. Its verdict is written to the attachments, and the action is removed when decided. | +| `Session.permission` | a `permission` action in mode `requests`, marked `toolApproved` when its tool is approved for the session. Its verdict is written to the attachments, and the action is removed when decided. | | `Session.turn` | Before any await, at an answer or a prompt that is not mid-turn, the permissions created before its hook started are ended, and so are the steps. An answer's quote is chosen, and its hook's start is recorded as the latest answer's hook start. A turn record is added for a prompt whose hook started no earlier than the latest answer's hook, unless the prompt is mid-turn and matched no pushed prompt. The model and the effort level of the request are taken only when its `at` is not older than the `at` of the value taken last, kept apart for each (`newer`). A `/title` passes its model with the `at` of its SessionStart hook. A request without `at` counts as the current time. A changed description is recorded in `session.json`. After these steps, the request's `step` goes to `step`, Claude posts the request's `note` without a quote, silent, and `User` posts the terminal prompt unless its `typed` is false, or it is blank, made only of this plugin's channel tags, pushed or a command. A prompt without `typed` is posted as typed. The turn record of a prompt is kept whatever its `typed`. Claude posts the answer unless it is blank. The changed short description is set, even after a failed post. A prompt, a note, a step's line or an answer that the core refuses for a group preference is replaced by Claude's post with the preference's name. | | `Session.endPermissions`, `endSteps`, `fileDone` | the end of pending permissions created before a time; the end of the steps started before a time, each removed by `endStep`, its ID kept as finished and its line updated with its own text, live off; it returns the promise of all updates started so far. The end of a prompt's file | +| `Session.endToolApprovals`, `sendTools` | the approvals of tools dropped when the session closes or another process registers it, a process with another ID, another start time or an unknown one; the approved tools of `Control` written to the attachments as a `{tools}` line when they differ from the list sent last, which a new writer resets to empty | | `Session.invite`, `announceRights` | invitation through the Main group. At a member's join or role change, other than `User`'s, the rights of the member's role are posted. The `/observer` command is added only for a role that can send, other than owner. | | `Session.prompt` | a message of `User` dropped; the rest delivered. `User`'s reactions are dropped before, by `onReaction`. | | `Session.refuseReaction` | The reply `This reaction is not supported.`, quoting the reacted message, posted on the `delivery` chain once for each member and reacted message, recorded in `refusedReactions`. A reaction to a sent message with that text gets no reply. | @@ -875,7 +879,7 @@ Data flow of a prompt from the session group: | `Hub.sessionsText`, `join`, `inviteOwner` | `SessionGroups` of the Main group | | `Hub.stop` | actions stopped, events awaited, cancelled cards awaited up to 10 s, steps ended, cores closed | | `storedGroup`, `createSessionGroup` | the group of `session.json` with a matching session number; a new group with `User` added | -| `Hub.onEvent` | event dispatch. Pending connections are claimed at `contactConnected` and `userJoinedGroup`. A session group's membership events go to its `Control`, `announceRights` and `askMode`, one at a time. | +| `Hub.onEvent` | event dispatch. Pending connections are claimed at `contactConnected` and `userJoinedGroup`. A session group's membership events go to its `Control`, `sendTools`, `announceRights` and `askMode`, one at a time. | | `notAllowedForUser` | `NAME are not allowed for User in the group of this session; its owners can allow them in the group's preferences.` It is posted for a prompt of `User` refused by a group preference, including one that is on only for roles above that of `User`. | | `textParts` | the longest runs of whole characters that each fit in one message by `fitsMessage`, the first with the given quote. Each part is found by a binary search among the next `maxMessageLength` characters. | | `isRefusedQuote` | `errorStore` `invalidQuote`, `chatItemNotFound` or `largeMsg` | @@ -946,7 +950,7 @@ Data flow of a prompt from the session group: |---|---| | [`.claude-plugin/plugin.json`](../.claude-plugin/plugin.json) | plugin `simplex`, version, description, `userConfig` | | [`.mcp.json`](../.mcp.json) | server `simplex`: `node dist/cli.js session` in the plugin's folder, tool call timeout, options as environment variables | -| [`hooks/hooks.json`](../hooks/hooks.json) | SessionStart: `dist/cli.js hook session-start`; PreToolUse: `allow.js`; UserPromptSubmit, Stop, PostModelSwitch: `dist/cli.js hook turn`, in the background | +| [`hooks/hooks.json`](../hooks/hooks.json) | SessionStart: `dist/cli.js hook session-start`; PreToolUse: `allow.js` for the plugin's tools, and for every tool `dist/cli.js hook turn` in the background and the `mcp_tool` hook that calls `pre_tool_use` of the server `plugin:simplex:simplex`; UserPromptSubmit, Stop, PostModelSwitch, PostToolUse, PostToolUseFailure: `dist/cli.js hook turn`, in the background | | [`package.json`](../package.json) | `bundleDependencies: true`. The production packages are bundled in the package's `node_modules`, without a lockfile, so Claude Code installs nothing in the plugin's folder. [`package-lock.json`](../package-lock.json), the tree of `npm ci`, is not packed. | | [`plugin/allow.js`](../plugin/allow.js) | PreToolUse allow decision | | [`/.claude-plugin/marketplace.json`](../../../.claude-plugin/marketplace.json) | marketplace `simplex-chat`, plugin source npm `@simplex-chat/mcp` | @@ -958,14 +962,14 @@ Memory of the service: | Item | Holder | Written by | Read by | |---|---|---|---| | Entries of open sessions | [`Service.entries`](../src/service.ts) | `entry`, idle close, stop | routes, `status` | -| Line writers of the attachments | [`Entry.writers`](../src/service.ts) | `onAttach` | `Session.onLine` | +| Line writers of the attachments | [`Entry.writers`](../src/service.ts), each with the process ID of its `/attach` | `onAttach` | `Session.onLine` | | Stored sessions, next number | [`Service.stored`, `nextNumber`](../src/service.ts) | `Service` constructor, `openAgent` | `openHub`, `openAgent` | | Aliases of sessions | [`Service.aliases`](../src/service.ts), ID to session ID | `Service` constructor, `alias` | `canonical`, `resolve` | | Titles by process | [`Service.titles`](../src/service.ts), PID to session ID, time and the name of a held title, and the `titled` signal | `onTitle`, `applyTitle` | `processSession`, the wait of `resolve`, `onSession` | | Registrations by process | [`Service.registered`](../src/service.ts), the signal of a `/session` with that PID | `onSession` | the wait of a held title | | Held titles | [`Service.held`](../src/service.ts), PID to its last held `/title` request | `onTitle`, the end of its wait | `onTitle`, `shutdown` | | Processes of unattended runs | [`Service.unattended`](../src/service.ts), PID to the time of its mark | `onTitle` with `unattended` | `onSession` | -| Process of a session server | [`Entry.pid`, `Entry.seen`](../src/service.ts) | `onSession`, the end of the last attachment | `processSession` | +| Process of a session server | [`Entry.pid`, `Entry.started`, `Entry.seen`](../src/service.ts) | `onSession`, the end of the last attachment | `processSession`, `onSession`, the line writer of `onAttach` | | Sessions | [`Hub.sessions`](../src/hub.ts), by number | `Hub.session` | events, Main group commands | | End of the held prompts | [`Hub.promptsHeldUntil`](../src/hub.ts), 30 s after the stored sessions opened | `Hub.open` | `Session.deliver` | | Prompts in delivery | [`Session.delivery`](../src/hub.ts), a promise chain in arrival order | `onMessage`, `onReaction` | `deliver` | @@ -980,10 +984,12 @@ Memory of the service: | Model and effort | [`Session.description`](../src/hub.ts), also in `session.json` | constructor, `turn` | `turn` | | Turn records | [`Session.turns`](../src/hub.ts), the start time of each prompt hook that started no earlier than the latest answer's hook, except a mid-turn prompt that matched no pushed prompt, with its pushed prompt, or `null` for a terminal prompt or a command | `turn`. At an answer, the records that started before its hook are removed. | `turnQuote` | | A rejected mode `host` | [`Session.hostDeclined`](../src/hub.ts), also in `session.json` | constructor, `declineHost` | `askMode`, `requestMode` | +| Approvals of tools | [`Control.toolApprovals`](../src/control.ts), by tool name: the approver's name and member ID and the time | `/approve N all`, `/revoke TOOL`, `endToolApprovals` when the session closes, another process registers it or its group is lost | `approvedTools`: `Session.sendTools`, `Session.permission`, `/list` | +| Approved tools sent | [`Session.sentTools`](../src/hub.ts), the list last written to the attachments, empty for a new writer | `sendTools`, `onLine` | `sendTools` | | The requested mode | [`Session.requested`](../src/hub.ts) | `requestMode`, a rejected or expired `mode` card | `askMode` | | Members of the Main group, its link | [`MainGroup.members`, `linkText`](../src/main-group.ts) | `refreshMembers`, `openLink` | owner checks, the statement of trust at a join, `/status`, `/title`, `/link` | -A session process keeps one connection promise, one attachment, the refusal of the service, and the retry delay with its timer in memory (the fields of [`ServiceLink`](../src/session.ts)). +A session process keeps one connection promise, one attachment, the refusal of the service, and the retry delay with its timer in memory (the fields of [`ServiceLink`](../src/session.ts)). It also keeps the approved tools of each attachment, and answers the PreToolUse hook from those of the current one (`ServiceLink.approvedTools`). Chat database custom data is in the core `_hub` unless noted: @@ -1102,6 +1108,7 @@ Tool-use state machine, one action of tool `permission` per request: |---|---|---|---| | `permission_request` | | `pending`, card posted | [`Session.permission`](../src/hub.ts) | | `/approve N` | `pending` | `performing`, `allow` pushed, then `done` | [`Session.permission`](../src/hub.ts), [`AgentTools.perform`](../src/tools.ts) | +| `/approve N all` | `pending` | as `/approve N`, after the tool is approved for the session and the approved tools are pushed | [`Control.approveTool`](../src/control.ts) | | `/reject N` | `pending` | `rejected`, `deny` pushed | [`Session.permission`](../src/hub.ts) | | an answer, or a prompt that is not mid-turn, of a hook that started after the card's creation; end of the last attachment | `pending` | `expired`, card edited to `Ended.` | [`Session.turn`, `endPermissions`](../src/hub.ts), [`Service.onAttach`](../src/service.ts), [`Actions.end`](../src/actions.ts) | | expiry | `pending` | `expired`, card edited to `Expired.` | [`Actions.expire`](../src/actions.ts) | @@ -1111,6 +1118,7 @@ Tool-use state machine, one action of tool `permission` per request: stateDiagram-v2 [*] --> pending: permission_request pending --> performing: /approve N, allow pushed + pending --> performing: /approve N all, tools pushed, then allow pushed performing --> done pending --> rejected: /reject N, deny pushed pending --> expired: later answer or prompt that is not mid-turn, last detach, card Ended. @@ -1120,6 +1128,29 @@ stateDiagram-v2 expired --> [*]: removed ``` +Approval of a tool for the rest of a session, kept in `Control` by tool name. The session server answers the PreToolUse hook with `allow` for an approved tool, and Claude Code then runs the tool without a prompt, unless a deny or ask rule, a safety check such as a write to a protected path, plan mode or the auto mode classifier requires its permission flow. A prompt of that flow is relayed as a card, with the line that the tool is approved and Claude Code still asks. + +| Event | From | To | Code | +|---|---|---|---| +| `/approve N all` of a pending `permission` card | | approved by the sender | [`Control.approveTool`](../src/control.ts) | +| the approver is no longer an admin or owner, after a membership event or `/observer` | approved | inactive: not among the approved tools | [`Control.approvedTools`](../src/control.ts), [`Hub.onEvent`](../src/hub.ts) | +| the approver is an admin or owner again | inactive | approved | the same | +| `/approve N all` by another approver | inactive | approved by that approver | [`Control.approveTool`](../src/control.ts) | +| `/revoke TOOL`; the session closes; `/session` from another process, by its ID or start time, or with an unknown start time | approved, inactive | removed | [`Control.revokeTool`, `endToolApprovals`](../src/control.ts), [`Service.onSession`, `scheduleIdle`, `processStart`](../src/service.ts) | +| the session's group is lost: deleted, Claude removed, or Claude no longer its owner, at an event or at a load | approved, inactive | removed, and `{tools: []}` sent | [`Control.onEvent`, `load`, `lose`](../src/control.ts) | +| the session's process attaches again, as after a failed call | approved, inactive | unchanged | [`Service.onAttach`](../src/service.ts) | +| an attachment of a process other than the one of the last `/session` | approved, inactive | `{tools: []}` sent to that attachment in place of each `{tools}` line | [`Service.onAttach`](../src/service.ts) | + +```mermaid +stateDiagram-v2 + [*] --> approved: /approve N all + approved --> inactive: its approver is no longer an admin or owner + inactive --> approved: its approver is an admin or owner again + inactive --> approved: /approve N all by another approver, who is recorded + approved --> [*]: /revoke TOOL, the session closes, another process registers it, or the group is lost + inactive --> [*]: /revoke TOOL, the session closes, another process registers it, or the group is lost +``` + ### 8.6 Channel and mirroring | Direction | Message | Code | diff --git a/packages/simplex-chat-mcp/spec/flows.md b/packages/simplex-chat-mcp/spec/flows.md index c57792280a..1081759e41 100644 --- a/packages/simplex-chat-mcp/spec/flows.md +++ b/packages/simplex-chat-mcp/spec/flows.md @@ -60,6 +60,7 @@ Claude Code plugin ([participants](#claude-code-plugin-flows)): 31. [A prompt of Claude Code](#31-a-prompt-of-claude-code) 32. [The steps of a turn](#32-the-steps-of-a-turn) 33. [A reaction in the session group](#33-a-reaction-in-the-session-group) +34. [A tool approved for the rest of a session](#34-a-tool-approved-for-the-rest-of-a-session) --- @@ -1073,7 +1074,7 @@ sequenceDiagram CC->>CC: the terminal dialog stays open S->>D: POST /permission {id, requestId, toolName, description, inputPreview} D->>N: permission - N->>O: card in #35;G: I want to use `Bash`: `DESCRIPTION`, preview, /'approve N' or /'reject N' + N->>O: card in #35;G: I want to use `Bash`: `DESCRIPTION`, preview, /'approve N', /'approve N all' or /'reject N' O->>N: /approve N N->>N: performing N->>D: onLine {permission: {requestId, behavior: allow}} @@ -1089,6 +1090,7 @@ Notes: - The first answer, in the terminal or in the group, applies. The last line of a card that is still pending becomes `Ended.` at an answer, or at a prompt that is not mid-turn, whose hook started after the card was created, and when the last attachment of the session ends. A prompt that Claude Code adds to the running turn ends no card ([`Session.turn`, `endPermissions`](../src/hub.ts), [`Service.onAttach`](../src/service.ts), [`cardText`](../src/control.ts)). - The input preview is cut to fit the card ([`Control.refusal`, `fittedLines`](../src/control.ts)). - The card is posted in mode `requests` also for a session in mode `host` ([`Session.permission`](../src/hub.ts)). +- `/approve N all` also approves the tool for the rest of the session, see [flow 34](#34-a-tool-approved-for-the-rest-of-a-session). Source: the notification handler of [`startSession`](../src/session.ts), [`ServiceLink.permission`](../src/session.ts), the `POST /permission` route of [`Service.routes`](../src/service.ts), [`Session.permission`](../src/hub.ts), [`requestLines`](../src/control.ts). @@ -1544,3 +1546,63 @@ Notes: - Owners turn reactions off with the group's preference "Message reactions", and the core then emits no `chatItemReaction`. Source: [`Session.onReaction`, `prompt`, `refuseReaction`, `deliver`, `answer`, `Hub.onEvent`](../src/hub.ts), [`channelNotification`](../src/session.ts). + +--- + +## 34. A tool approved for the rest of a session + +```mermaid +sequenceDiagram + participant CC as Claude Code + participant S as Session process + participant D as Service + participant N as Session N + participant O as Owner + CC->>S: notifications/claude/channel/permission_request {request_id, tool_name: Bash, description, input_preview} + S->>D: POST /permission + D->>N: permission, Bash not approved + N->>O: card: I want to use Bash, /'approve 5', /'approve 5 all' or /'reject 5' + O->>N: /approve 5 all + N->>N: toolApprovals: Bash by Alice, logged + N->>D: onLine {tools: [{tool: Bash, approvedBy: Alice}]} + D->>S: the line on /attach, kept as the list of that attachment + N->>D: onLine {permission: {requestId, behavior: allow}} + D->>S: the line on /attach + S->>CC: notifications/claude/channel/permission allow + N->>O: card edited: Approved by Alice. + N->>O: reply: Approved Bash for the rest of this session by Alice. /'revoke Bash' + CC->>S: PreToolUse hook of type mcp_tool: tools/call pre_tool_use {tool: Bash} + S-->>CC: allow + CC->>CC: the next Bash use runs without a prompt, unless Claude Code's own rules ask +``` + +A use that Claude Code asks for by its own rules: + +```mermaid +sequenceDiagram + participant CC as Claude Code + participant S as Session process + participant D as Service + participant N as Session N + participant O as Owner + CC->>S: PreToolUse hook: tools/call pre_tool_use {tool: Bash} + S-->>CC: allow + CC->>CC: the command writes to .bashrc, a protected path: the permission flow + CC->>S: notifications/claude/channel/permission_request {request_id, tool_name: Bash, ...} + S->>D: POST /permission + D->>N: permission, Bash approved + N->>O: card with the line: Bash is approved for this session, and Claude Code still asks for this use. /'approve 6' or /'reject 6' +``` + +Notes: + +- Claude Code re-checks a call that a PreToolUse hook allows. A deny rule refuses it, and an ask rule, a safety check such as a write to a protected path, plan mode or the auto mode classifier sends it through the permission flow, which relays the prompt as a card. With Claude Code before 2.1.299, a hook's `allow` also ran writes in plan mode. +- One tap approves its own card only. Other pending cards of the tool stay pending. +- An approval counts while its approver is an admin or owner of the group. After a membership event, the hub sends the approved tools before the rights post; after `/observer`, `Control` sends them after it reads the members again. +- `/revoke TOOL` removes an approval, and the session gets the new list. `/list` shows the approved tools after the chats. +- The approvals belong to the Claude Code process of the session. A session server answers from the list of its current attachment only. When it drops the attachment after a failed call and attaches again, the hub sends it the approved tools, which it keeps. The approvals are dropped when `/session` comes from another process and when the session closes. The service tells processes apart by their ID and their start time, read on Linux and macOS; a `/session` whose start time is unknown counts as another process. While two processes have the session attached, only the attachments of the process of the last `/session` get the approved tools; the others get `{tools: []}`. The approvals also end when the session's group is lost, found at an event or at a load, and the session server gets `{tools: []}`. +- The approvals are kept in memory, so a service restart drops them. +- The terminal shows nothing at the approval, and Claude Code's `/permissions` doesn't list it. +- While the plugin's MCP server is not connected, Claude Code reports `MCP server 'plugin:simplex:simplex' not connected` as a non-blocking PreToolUse hook error at each tool use, and the tool use goes on. + +Source: [`Control.ownerCommand`, `approveTool`, `revokeTool`, `approvedTools`, `endToolApprovals`, `load`, `lose`, `requestLines`, `commandsLine`, `ownerRequest`](../src/control.ts), [`Session.permission`, `onLine`, `sendTools`, `endToolApprovals`, `Hub.onEvent`](../src/hub.ts), [`Service.onSession`, `onAttach`, `scheduleIdle`, `processStart`](../src/service.ts), [`startSession`, `ServiceLink.open`, `ServiceLink.approvedBy`, `hookOutput`](../src/session.ts), [`hooks/hooks.json`](../hooks/hooks.json). diff --git a/packages/simplex-chat-mcp/src/actions.ts b/packages/simplex-chat-mcp/src/actions.ts index 6260a883d1..e7e1a2eb15 100644 --- a/packages/simplex-chat-mcp/src/actions.ts +++ b/packages/simplex-chat-mcp/src/actions.ts @@ -143,6 +143,7 @@ export interface PermissionAction extends ActionRecord { readonly input: {requestId: string; toolName: string; description: string; inputPreview: string} readonly subject?: undefined readonly chat?: undefined + readonly toolApproved: boolean previewBytes?: number } diff --git a/packages/simplex-chat-mcp/src/control.ts b/packages/simplex-chat-mcp/src/control.ts index a0e404b168..2c1fbdf184 100644 --- a/packages/simplex-chat-mcp/src/control.ts +++ b/packages/simplex-chat-mcp/src/control.ts @@ -1,9 +1,10 @@ import {CEvt, ChatEvent, T} from "@simplex-chat/types" import {api, core} from "simplex-chat" -import {Action, ActionHooks, Actions, DownloadAction, Standing, State, Subject, ToolError, hasUnknownServers, leaveVerbs, subjectText, summary} from "./actions" +import {Action, ActionHooks, Actions, DownloadAction, PermissionAction, Standing, State, Subject, ToolError, hasUnknownServers, leaveVerbs, subjectText, summary} from "./actions" import {ExitError, chatErrorOf, errorText, fileError, log, logError, oneLine, serverHostname, shellWord} from "./log" import {chatRef, fileContent, isChatRef, utcMinutes, validName, viewName} from "./messages" import {linkCommand} from "./owner" +import type {ApprovedTool} from "./protocol" import {qrCodeText} from "./qr" import type {OwnerEntry, QrCodeSize} from "./serve" import {AgentTools, chatSubject, customDataOf, featureOff, fitsMessage, isActive, isConnected, memberCurrent, memberCurrentOrPending, refusedFeature, refusedFileReason, setChatData} from "./tools" @@ -75,6 +76,7 @@ export interface SessionOptions { approves: (member: T.GroupMember) => boolean ownerOf: (session: number) => string | undefined isUser: (member: T.GroupMember) => boolean + toolsChanged: () => void } export interface Command { @@ -93,6 +95,8 @@ interface ChatApproval { type OwnerRequest = | {type: "approve" | "reject" | "receive" | "forward"; action: number; chat?: string} | {type: "receiveAll"; action: number; chat: string} + | {type: "approveTool"; action: number} + | {type: "revokeTool"; tool: string} | {type: "approveChat" | "revoke"; chat: string; standing: Standing} | {type: "leave" | "deleteFiles"; chat: string} | {type: "give"; chat: string; session: number} @@ -111,6 +115,7 @@ const inChat: Shown = {name: safeName, command: codeSpan} export class Control implements Pick { private members: T.GroupMember[] = [] + private readonly toolApprovals = new Map() private writes: Promise = Promise.resolve() private profileUpdates: Promise = Promise.resolve() private ownerCommands: Promise = Promise.resolve() @@ -296,6 +301,8 @@ export class Control implements Pick this.approvers().some(({groupMemberId}) => groupMemberId === approvedById)).map(([tool, {approvedBy}]) => ({tool, approvedBy})) + } + + // spec: spec/architecture.md#control-control-approvedtools + endToolApprovals(): void { + this.toolApprovals.clear() + } + + // spec: spec/api.md#session-groups + private approveTool(sender: T.GroupMember, action: PermissionAction): string { + const {toolName} = action.input + const approvedBy = sender.memberProfile.displayName + this.toolApprovals.set(toolName, {approvedBy, approvedById: sender.groupMemberId, approvedAt: new Date().toISOString()}) + log(`${oneLine(toolName)} approved for the rest of the session in "${this.options.displayName}" by ${oneLine(approvedBy)}.`) + this.options.session?.toolsChanged() + const approver = safeName(approvedBy) + this.actions.approve(action, approver) + return `Approved ${codeSpan(oneLine(toolName))} for the rest of this session by ${approver}. /'revoke ${toolName}'` + } + + // spec: spec/api.md#session-groups + private revokeTool(tool: string): string { + if (!this.toolApprovals.delete(tool)) return `Uses of ${codeSpan(tool)} have no standing approval.` + log(`${tool} needs approval again in "${this.options.displayName}".`) + this.options.session?.toolsChanged() + return `Uses of ${codeSpan(tool)} need approval again.` + } + // spec: spec/api.md#control-commands private forward(action: DownloadAction): void { this.tools @@ -427,6 +466,7 @@ export class Control implements Pick 0) lines.push(`${rest} older chat${rest === 1 ? " is" : "s are"} not shown.`) + lines.push(...this.approvedTools().map(({tool, approvedBy}) => `${codeSpan(oneLine(tool))} approved for this session by ${safeName(approvedBy)}`)) return lines.length > 0 ? lines.join("\n") : "No chats." } @@ -532,6 +573,8 @@ export class Control implements Pick void + private sentTools = "[]" private readonly attaching = new Changes() private delivery: Promise = Promise.resolve() private readonly refusedReactions = new Set() @@ -140,6 +141,7 @@ export class Session { approves: (member: T.GroupMember) => this.approves(member), ownerOf: (n: number) => hub.sessionId(n), isUser: (member: T.GroupMember) => this.isUser(member), + toolsChanged: () => this.sendTools(), } this.control = new Control(chat, group, {displayName: group.groupProfile.displayName, session, registerHint: "", qrCode: "small"}, this.actions, this.tools) } @@ -155,6 +157,8 @@ export class Session { set onLine(writer: ((line: AttachLine) => void) | undefined) { this.writer = writer + this.sentTools = "[]" + this.sendTools() this.attaching.notify() } @@ -226,7 +230,8 @@ export class Session { // spec: spec/architecture.md#hub-session-permission permission({requestId, toolName, description, inputPreview}: PermissionRequest): void { - const action = this.actions.create(`permission ${requestId}`, {tool: "permission", input: {requestId, toolName, description, inputPreview}}, undefined, this.number, "requests") + const toolApproved = this.control.approvedTools().some(({tool}) => tool === toolName) + const action = this.actions.create(`permission ${requestId}`, {tool: "permission", input: {requestId, toolName, description, inputPreview}, toolApproved}, undefined, this.number, "requests") const unsubscribe = action.changes.subscribe(() => { const behavior = action.state === "performing" ? "allow" : action.state === "rejected" ? "deny" : undefined if (behavior !== undefined) this.onLine?.({permission: {requestId, behavior}}) @@ -283,6 +288,21 @@ export class Session { return this.finalizing } + // spec: spec/architecture.md#hub-session-endtoolapprovals + endToolApprovals(): void { + this.control.endToolApprovals() + this.sendTools() + } + + // spec: spec/architecture.md#hub-session-endtoolapprovals + sendTools(): void { + const tools = this.control.approvedTools() + const sent = JSON.stringify(tools) + if (sent === this.sentTools) return + this.sentTools = sent + this.onLine?.({tools}) + } + // spec: spec/architecture.md#hub-session-endpermissions fileDone(fileId: number, error?: string): void { const waiting = this.receiving.get(fileId) @@ -699,7 +719,7 @@ export class Hub implements SessionGroups { } const session = sessions.find(({control}) => isControlEvent(event, control.groupId)) if (session !== undefined) { - this.controlEvents = this.controlEvents.then(() => session.control.onEvent(event)).then(() => session.announceRights(event)).then(() => session.askMode()).catch(error => logError(`${event.type} in the group of session ${session.number}`, error)) + this.controlEvents = this.controlEvents.then(() => session.control.onEvent(event)).then(() => session.sendTools()).then(() => session.announceRights(event)).then(() => session.askMode()).catch(error => logError(`${event.type} in the group of session ${session.number}`, error)) } } } diff --git a/packages/simplex-chat-mcp/src/protocol.ts b/packages/simplex-chat-mcp/src/protocol.ts index 9ae0df1d4a..6c31bdb856 100644 --- a/packages/simplex-chat-mcp/src/protocol.ts +++ b/packages/simplex-chat-mcp/src/protocol.ts @@ -78,6 +78,13 @@ export interface Step { export interface AttachLine { prompt?: {text: string; from: string; item: number; file?: string; replyTo?: {item?: number; from?: string}} permission?: {requestId: string; behavior: "allow" | "deny"} + tools?: ApprovedTool[] +} + +// spec: spec/architecture.md#protocol-attachline +export interface ApprovedTool { + tool: string + approvedBy: string } // spec: spec/architecture.md#protocol-titlereply @@ -96,6 +103,7 @@ export interface SessionReply extends ServiceInfo { // spec: spec/architecture.md#protocol-titlereply export interface AttachRequest { id: string + pid?: number } // spec: spec/architecture.md#protocol-titlereply diff --git a/packages/simplex-chat-mcp/src/service.ts b/packages/simplex-chat-mcp/src/service.ts index e993a8e346..21421e4027 100644 --- a/packages/simplex-chat-mcp/src/service.ts +++ b/packages/simplex-chat-mcp/src/service.ts @@ -1,7 +1,10 @@ +import {execFile} from "child_process" import {EventEmitter} from "events" import {existsSync, writeSync} from "fs" +import {readFile} from "fs/promises" import {Server, ServerResponse} from "http" import {basename, join} from "path" +import {promisify} from "util" import {CallToolResult} from "@modelcontextprotocol/server" import {Action, Mode} from "./actions" import {Config, readConfig} from "./config" @@ -17,11 +20,13 @@ import {version} from "./version" const idleClose = 10 * 60_000 const idleStop = 10 * 60_000 const processWait = 10_000 +const psWait = 2_000 const logCheck = 3_600_000 const lockChecks = 150 const lockCheckWait = 100 const firstFreeFd = 3 const unnamedSession = "Claude Code" +const run = promisify(execFile) // spec: spec/architecture.md#service-hublike export interface HubLike { @@ -48,6 +53,7 @@ export interface SessionLike { turn(request: TurnRequest): Promise endPermissions(): void endSteps(): Promise + endToolApprovals(): void } // spec: spec/architecture.md#service-hublike @@ -57,6 +63,7 @@ export interface ServiceDeps { version: string openHub(config: Config, stored: StoredSession[]): Promise onStopped(code: number): void + processStart(pid: number): Promise } // spec: spec/architecture.md#service-entry @@ -65,9 +72,10 @@ interface Entry { agent?: SessionLike attached: number calls: number - writers: Set<(line: AttachLine) => void> + writers: Map<(line: AttachLine) => void, number | undefined> idle?: NodeJS.Timeout pid?: number + started?: string seen?: number } @@ -212,14 +220,18 @@ export class Service { private async onSession(request: SessionRequest): Promise { validConfig(request.config) this.refuseUnattended(request.pid) + const started = request.pid === undefined ? undefined : await this.deps.processStart(request.pid) const id = await this.resolve(request.id, request.pid, true) this.refuseUnattended(request.pid) const title = request.pid === undefined ? undefined : this.titles.get(request.pid) const entry = this.entry(id, {...request, id, name: request.name ?? (title?.id === id ? title.name : undefined)}) + const previous = {pid: entry.pid, started: entry.started} entry.pid = request.pid + entry.started = started entry.seen = Date.now() if (request.pid !== undefined) this.registered.emit(String(request.pid)) const agent = await entry.opening + if (previous.pid !== undefined && (previous.pid !== request.pid || started === undefined || previous.started !== started)) agent.endToolApprovals() if (entry.attached === 0) this.scheduleIdle(id, entry) await this.hub.configure(request.config) agent.requestMode(request.config.approve) @@ -332,8 +344,8 @@ export class Service { clearTimeout(entry.idle) const write = startLines(res) write({version: this.deps.version, protocol: protocolVersion}) - entry.writers.add(write) - agent.onLine = line => entry.writers.forEach(writer => writer(line)) + entry.writers.set(write, request.pid) + agent.onLine = line => entry.writers.forEach((pid, writer) => writer(line.tools === undefined || pid === entry.pid ? line : {tools: []})) res.once("close", () => { entry.attached-- entry.writers.delete(write) @@ -386,7 +398,7 @@ export class Service { const existing = this.entries.get(id) if (existing !== undefined) return existing clearTimeout(this.stopTimer) - const entry: Entry = {attached: 0, calls: 0, writers: new Set(), opening: this.openAgent(id, folder, request)} + const entry: Entry = {attached: 0, calls: 0, writers: new Map(), opening: this.openAgent(id, folder, request)} this.entries.set(id, entry) this.scheduleIdle(id, entry) entry.opening.then( @@ -439,6 +451,7 @@ export class Service { if (agent === undefined || entry.calls > 0 || agent.busy()) return this.scheduleIdle(id, entry) this.entries.delete(id) agent.open = false + agent.endToolApprovals() if (this.entries.size === 0) this.scheduleStop() }, idleClose) } @@ -494,6 +507,19 @@ export function productionDeps(root: string): ServiceDeps { version, openHub: (config, stored) => Hub.open(root, config, stored), onStopped: code => process.exit(code), + processStart, + } +} + +// spec: spec/architecture.md#service-processstart +export async function processStart(pid: number): Promise { + if (!Number.isSafeInteger(pid) || pid <= 0) return undefined + try { + if (process.platform === "linux") return (await readFile(`/proc/${pid}/stat`, "utf8")).split(") ").at(-1)?.split(" ")[19] + if (process.platform === "darwin") return (await run("/bin/ps", ["-o", "lstart=", "-p", String(pid)], {timeout: psWait})).stdout.trim() || undefined + return undefined + } catch { + return undefined } } diff --git a/packages/simplex-chat-mcp/src/session.ts b/packages/simplex-chat-mcp/src/session.ts index fede37fad2..e6074220a6 100644 --- a/packages/simplex-chat-mcp/src/session.ts +++ b/packages/simplex-chat-mcp/src/session.ts @@ -25,6 +25,11 @@ const channelInstructions = "Messages in the simplex channel are prompts of the const permissionFields = ["request_id", "tool_name", "description", "input_preview"] as const // spec: spec/architecture.md#session-unattendedrun const permissionRequest = fromJsonSchema({type: "object", properties: Object.fromEntries(permissionFields.map(field => [field, {type: "string"}])), required: [...permissionFields]} as JsonSchemaType) +// spec: spec/api.md#plugin-tools +const hookTool = { + description: "Answers the plugin's PreToolUse hook before each tool use: allow for a tool that an admin or owner of the SimpleX group of this session approved for the rest of the session, and nothing otherwise. You never need to call it.", + inputSchema: fromJsonSchema({type: "object", properties: {tool: {type: "string", description: "Name of the tool, from the hook's input."}}, required: ["tool"]} as JsonSchemaType), +} class ServiceStoppedError extends Error { constructor() { @@ -60,6 +65,7 @@ export async function startSession(env: NodeJS.ProcessEnv = process.env, io: Ses if (notification !== undefined) server.server.notification(notification).catch(error => logError("SimpleX channel", error)) }) registerTools(server, config.approve, async (name, input, call) => (configError === undefined ? link.call(name, input, call) : toolError(configError)), [replyTool]) + server.registerTool("pre_tool_use", hookTool, async input => ({content: [{type: "text", text: hookOutput(link.approvedBy((input as {tool: string}).tool))}]})) server.server.setNotificationHandler("notifications/claude/channel/permission_request", {params: permissionRequest}, params => { if (configError !== undefined) return const {request_id, tool_name, description, input_preview} = params as {[field in (typeof permissionFields)[number]]: string} @@ -78,9 +84,15 @@ class ServiceLink { private refused = false private retry = firstRetry private retryTimer?: NodeJS.Timeout + private readonly approvedTools = new WeakMap>() constructor(private readonly client: ServiceClient, private readonly request: SessionRequest, private readonly io: SessionIo, private readonly onLine: (line: unknown) => void) {} + // spec: spec/architecture.md#session-servicelink-approvedby + approvedBy(tool: string): string | undefined { + return this.attach === undefined ? undefined : this.approvedTools.get(this.attach)?.get(tool) + } + // spec: spec/architecture.md#session-servicelink-connect connect(): Promise { if (this.refused) return Promise.reject(new Error(unattendedRun)) @@ -183,8 +195,10 @@ class ServiceLink { this.attach = controller await new Promise((resolve, reject) => { this.client - .stream("/attach", {id: this.request.id}, line => { + .stream("/attach", {id: this.request.id, pid: this.request.pid}, line => { resolve() + const {tools} = line as AttachLine + if (tools !== undefined) this.approvedTools.set(controller, new Map(tools.map(({tool, approvedBy}) => [tool, approvedBy]))) this.onLine(line) }, controller.signal) .then(() => reject(new ServiceStoppedError()), reject) @@ -210,6 +224,11 @@ function toolError(text: string): CallToolResult { return {content: [{type: "text", text}], isError: true} } +// spec: spec/api.md#plugin-tools +function hookOutput(approvedBy: string | undefined): string { + return approvedBy === undefined ? "" : JSON.stringify({hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "allow", permissionDecisionReason: `Approved for this session by ${approvedBy} in the session's SimpleX group.`}}) +} + // spec: spec/architecture.md#session-channelnotification function channelNotification({prompt, permission}: AttachLine): {method: string; params: {[key: string]: unknown}} | undefined { if (prompt !== undefined) return {method: "notifications/claude/channel", params: {content: prompt.text, meta: {from: prompt.from, item: String(prompt.item), ...(prompt.file === undefined ? {} : {file: prompt.file}), ...(prompt.replyTo?.item === undefined ? {} : {reply_to: String(prompt.replyTo.item)}), ...(prompt.replyTo?.from === undefined ? {} : {reply_to_from: prompt.replyTo.from})}}} diff --git a/packages/simplex-chat-mcp/test/e2e/launch.test.ts b/packages/simplex-chat-mcp/test/e2e/launch.test.ts index 9b633d178e..ea917662e6 100644 --- a/packages/simplex-chat-mcp/test/e2e/launch.test.ts +++ b/packages/simplex-chat-mcp/test/e2e/launch.test.ts @@ -63,7 +63,7 @@ test("the unpacked plugin, with nothing installed, runs its hooks and its sessio const client = new LineClient(server.stdin, server.stdout) expect(await client.initialize()).toMatchObject({serverInfo: {name: "simplex-mcp", version}}) const {result} = await client.request("tools/list") - expect(result.tools.map(({name}: {name: string}) => name)).toEqual(["connect", "send", "receive", "download", "list", "leave", "reply"]) + expect(result.tools.map(({name}: {name: string}) => name)).toEqual(["connect", "send", "receive", "download", "list", "leave", "reply", "pre_tool_use"]) server.stdin.end() await new Promise(resolve => server.on("close", resolve)) expect(existsSync(join(dir, "home", "service.lock"))).toBe(false) diff --git a/packages/simplex-chat-mcp/test/e2e/service.test.ts b/packages/simplex-chat-mcp/test/e2e/service.test.ts index 47e10fb346..2248f811e2 100644 --- a/packages/simplex-chat-mcp/test/e2e/service.test.ts +++ b/packages/simplex-chat-mcp/test/e2e/service.test.ts @@ -454,7 +454,7 @@ test("the hooks post a prompt typed in the terminal as User, also the session's expect(fromUser.map(({meta}) => meta.itemText)).toEqual(["Fix the build"]) }, 600_000) -test("a session keeps its group for hooks with a new ID from its process, relays tool use to its owners, owns a contact and a group that accept after connect returned, asks for mode host, and gets a prompt sent before it attached again after a service start", async () => { +test("a session keeps its group for hooks with a new ID from its process, relays tool use to its owners, who approve Bash for the rest of the session, owns a contact and a group that accept after connect returned, asks for mode host, and gets a prompt sent before it attached again after a service start", async () => { const root = join(dir, "channel", "root") await prepareRoot(smpServer.address, root) const alice = await personIn("channel", "Alice") @@ -468,7 +468,7 @@ test("a session keeps its group for hooks with a new ID from its process, relays const attached: AttachLine[] = [] const controller = new AbortController() closing.push(async () => controller.abort()) - client.stream("/attach", {id: one}, line => attached.push(line as AttachLine), controller.signal).catch(() => undefined) + client.stream("/attach", {id: one, pid}, line => attached.push(line as AttachLine), controller.signal).catch(() => undefined) await until(() => attached.length === 1) const owner = await client.request("GET", "/link") const invitations = joinSessionGroups(alice, ["1 · one"]) @@ -488,6 +488,13 @@ test("a session keeps its group for hooks with a new ID from its process, relays await ownerSends(`/approve ${cardNumber(await toolUse)}`) await until(() => attached.some(({permission}) => permission !== undefined)) expect(attached.filter(({permission}) => permission !== undefined)).toEqual([{permission: {requestId: "abcde", behavior: "allow"}}]) + const toolUseAll = card("I want to use `Bash`: `Run shell command`") + const approvedAll = card("Approved `Bash` for the rest of this session by Alice. /'revoke Bash'") + await client.request("POST", "/permission", {id: one, requestId: "fghij", toolName: "Bash", description: "Run shell command", inputPreview: "pwd"}) + await ownerSends(`/approve ${cardNumber(await toolUseAll)} all`) + await approvedAll + await until(() => attached.some(({permission}) => permission?.requestId === "fghij")) + expect(attached.filter(({tools}) => tools !== undefined)).toEqual([{tools: [{tool: "Bash", approvedBy: "Alice"}]}]) const address = await bob.chat.apiCreateUserAddress(bob.user.userId) const requested = bob.chat.wait("receivedContactRequest", 60_000) @@ -652,7 +659,7 @@ test("a member of the Main group joins a session's group by /join as admin, prom expect((await alice.chat.apiListGroups(alice.user.userId)).find(({groupId}) => groupId === groupOne)?.membership.memberRole).toBe(T.GroupMemberRole.Owner) }, 600_000) -test("/observer ends the standing approvals of the member it makes an observer, and answers that a member who has not joined yet is no member", async () => { +test("/observer ends the standing approvals of the member it makes an observer, of a chat and of a tool, and answers that a member who has not joined yet is no member", async () => { const root = join(dir, "observer", "root") await prepareRoot(smpServer.address, root) const alice = await personIn("observer", "Alice") @@ -662,6 +669,11 @@ test("/observer ends the standing approvals of the member it makes an observer, const service = await startService(root) const client = ServiceClient.forRoot(root) await openSession(client, one, "one") + const attached: AttachLine[] = [] + const controller = new AbortController() + closing.push(async () => controller.abort()) + client.stream("/attach", {id: one}, line => attached.push(line as AttachLine), controller.signal).catch(() => undefined) + await until(() => attached.length === 1) const owner = await client.request("GET", "/link") const aliceInvited = joinSessionGroups(alice, ["1 · one"]) const mainGroupId = await joinByLink(alice, owner.link!) @@ -691,12 +703,18 @@ test("/observer ends the standing approvals of the member it makes an observer, await aliceSends("/list") return (await shown).chatItem.meta.itemText } - expect(await listed()).toBe(`${chat} bot Directory, approved for this chat by Bob`) + const toolUse = received(bob.chat, inGroup(bobGroupOne, textStarts("I want to use `Bash`"))) + await client.request("POST", "/permission", {id: one, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) + const bashApproved = received(bob.chat, inGroup(bobGroupOne, textStarts("Approved `Bash` for the rest of this session by Bob."))) + await bob.chat.apiSendTextMessage([T.ChatType.Group, bobGroupOne], `/approve ${cardNumber(await toolUse)} all`) + await bashApproved + expect(await listed()).toBe(`${chat} bot Directory, approved for this chat by Bob\n\`Bash\` approved for this session by Bob`) const bobObserver = aliceSees("Bob is an observer and can't send messages.") await aliceSends(`/${makeBobObserver}`) await bobObserver expect(await listed()).toBe(`${chat} bot Directory`) + expect(attached.filter(({tools}) => tools !== undefined)).toEqual([{tools: [{tool: "Bash", approvedBy: "Bob"}]}, {tools: []}]) const daveConnected = dave.chat.wait("connectedToGroupMember", ({member}) => member.memberProfile.displayName === "Claude", 60_000) const daveMain = await joinByLink(dave, mainLink) @@ -748,7 +766,7 @@ test("stdio session spawns the service and recovers after the service is killed" expect(await session.client.initialize()).toMatchObject({serverInfo: {name: "simplex-mcp"}}) const {result} = await session.client.request("tools/list") - expect(result.tools.map(({name}: {name: string}) => name)).toEqual(["connect", "send", "receive", "download", "list", "leave", "reply"]) + expect(result.tools.map(({name}: {name: string}) => name)).toEqual(["connect", "send", "receive", "download", "list", "leave", "reply", "pre_tool_use"]) const listed = await session.call("list", {}) expect(listed.isError).toBeUndefined() expect(listed.structuredContent.actions).toEqual([]) diff --git a/packages/simplex-chat-mcp/test/unit/cards.test.ts b/packages/simplex-chat-mcp/test/unit/cards.test.ts index c675b8c41b..a9ed8e29f1 100644 --- a/packages/simplex-chat-mcp/test/unit/cards.test.ts +++ b/packages/simplex-chat-mcp/test/unit/cards.test.ts @@ -249,3 +249,14 @@ describe("download cards", () => { expect(lastLines(["xftp://hash@a.example.com", "xftp://hash@evil`*bold*`/approve"])[0]).toBe("Servers: `a.example.com`, `evil'*bold*'`, unknown: downloading shows them this computer's IP address.") }) }) + +describe("tool-use cards", () => { + const permission = (toolApproved: boolean): NewAction => ({tool: "permission", input: {requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}, toolApproved}) + + it("offers the approval of the tool for the session, and says that Claude Code still asks for a use of an approved tool", () => { + const lines = (toolApproved: boolean, state: State, extra: Partial = {}): string[] => cardText(action(permission(toolApproved), state, extra), mode).split("\n") + expect(lines(false, "pending")).toEqual(["I want to use `Bash`: `Run shell command`", "`ls`", "/'approve 1', /'approve 1 all' or /'reject 1'"]) + expect(lines(true, "pending")).toEqual(["I want to use `Bash`: `Run shell command`", "`ls`", "`Bash` is approved for this session, and Claude Code still asks for this use.", "/'approve 1' or /'reject 1'"]) + expect(lines(true, "done", {decidedBy: "Alice"})).toEqual(["I want to use `Bash`: `Run shell command`", "`ls`", "`Bash` is approved for this session, and Claude Code still asks for this use.", "Approved by Alice."]) + }) +}) diff --git a/packages/simplex-chat-mcp/test/unit/plugin.test.ts b/packages/simplex-chat-mcp/test/unit/plugin.test.ts index 87d04e9460..ebadbc61cd 100644 --- a/packages/simplex-chat-mcp/test/unit/plugin.test.ts +++ b/packages/simplex-chat-mcp/test/unit/plugin.test.ts @@ -38,14 +38,14 @@ describe("plugin", () => { expect(read(".mcp.json").mcpServers.simplex.timeout).toBe((maxExpireHours + responseWaitHours) * 3_600_000 + marginMs) }) - it("runs the hooks from the plugin's own build, allows the plugin's tools, and runs the turn hook at the start and the end of every tool use", () => { + it("runs the hooks from the plugin's own build, allows the plugin's tools, runs the turn hook at the start and the end of every tool use, and asks the session server before every tool use whether its tool is approved", () => { const {hooks} = read("hooks/hooks.json") expect(hooks.SessionStart[0].hooks[0]).toEqual({type: "command", command: cli("hook session-start"), timeout: 600}) expect(hooks.PreToolUse[0].matcher).toBe("mcp__plugin_simplex_simplex__.*") expect(hooks.PreToolUse[0].hooks[0]).toEqual({type: "command", command: 'node "${CLAUDE_PLUGIN_ROOT}/plugin/allow.js"'}) for (const event of ["UserPromptSubmit", "Stop", "PostModelSwitch"]) expect(hooks[event]).toEqual([{hooks: [{type: "command", command: cli("hook turn"), async: true}]}]) const steps = {matcher: "*", hooks: [{type: "command", command: cli("hook turn"), async: true}]} - expect(hooks.PreToolUse[1]).toEqual(steps) + expect(hooks.PreToolUse[1]).toEqual({...steps, hooks: [...steps.hooks, {type: "mcp_tool", server: "plugin:simplex:simplex", tool: "pre_tool_use", input: {tool: "${tool_name}"}, timeout: 5}]}) for (const event of ["PostToolUse", "PostToolUseFailure"]) expect(hooks[event]).toEqual([steps]) }) diff --git a/packages/simplex-chat-mcp/test/unit/service.test.ts b/packages/simplex-chat-mcp/test/unit/service.test.ts index d6bd4849a7..e0c2c5fe6c 100644 --- a/packages/simplex-chat-mcp/test/unit/service.test.ts +++ b/packages/simplex-chat-mcp/test/unit/service.test.ts @@ -1,3 +1,4 @@ +import {spawn} from "child_process" import {once} from "events" import * as fs from "fs" import {closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync} from "fs" @@ -10,7 +11,7 @@ import {ServiceClient} from "../../src/client" import {defaultConfig} from "../../src/config" import {LockedError, createDataFolder, readSessionFile, serviceToken, sessionFolder, socketPath, writeSessionFile} from "../../src/files" import {protocolVersion} from "../../src/protocol" -import {HubLike, Service, ServiceDeps, SessionLike, productionDeps, runService} from "../../src/service" +import {HubLike, Service, ServiceDeps, SessionLike, processStart, productionDeps, runService} from "../../src/service" import * as socket from "../../src/socket" import {requestJson, streamLines} from "../../src/socket" import {closeServer, recordedRun, until} from "./fixtures" @@ -41,6 +42,7 @@ function deps(root: string) { const configs: unknown[] = [] const busy = new Set() const stored: unknown[] = [] + const starts = new Map() let expiryChecks = 0 const hubStops: number[] = [] const gates: {open?: Promise; call?: Promise; hubStop?: Promise} = {} @@ -86,6 +88,9 @@ function deps(root: string) { endSteps: async () => { agent.turns.push("steps ended") }, + endToolApprovals: () => { + agent.turns.push("tool approvals ended") + }, call: async (tool: string, _input: unknown, call: {signal: AbortSignal; progress: (m: string) => void}) => { agent.calls.push(tool) calling.resolve() @@ -117,13 +122,14 @@ function deps(root: string) { return hub }, onStopped, + processStart: async pid => (starts.has(pid) ? starts.get(pid) : "100"), } const gate = (name: keyof typeof gates): (() => void) => { const {promise, resolve} = deferred() gates[name] = promise return resolve } - return {d, agents, configs, busy, stored, expiryChecks: () => expiryChecks, hubStops, onStopped, stoppedCode: stopped.promise, opening: opening.promise, calling: calling.promise, aborted: aborted.promise, hubStopping: hubStopping.promise, gate} + return {d, agents, configs, busy, stored, starts, expiryChecks: () => expiryChecks, hubStops, onStopped, stoppedCode: stopped.promise, opening: opening.promise, calling: calling.promise, aborted: aborted.promise, hubStopping: hubStopping.promise, gate} } let root: string @@ -156,10 +162,10 @@ const titleReply = {mainGroup: "SimpleX MCP", owner: {owners: [], link: "https:/ const sessionsFolder = () => join(root, "_sessions") const lockFile = () => join(root, "service.lock") -function attach(id: string, signal: AbortSignal) { +function attach(id: string, signal: AbortSignal, pid?: number) { const first = deferred() const lines: unknown[] = [] - const attached = streamLines(socketPath(root), token, "/attach", {id}, line => (lines.push(line), first.resolve()), signal).catch(() => undefined) + const attached = streamLines(socketPath(root), token, "/attach", {id, pid}, line => (lines.push(line), first.resolve()), signal).catch(() => undefined) return {attached, firstLine: first.promise, lines} } @@ -622,6 +628,93 @@ describe("service", () => { await expect(post("/turn", {id: id2, answer: "x"})).rejects.toMatchObject({status: 409}) }) + it("keeps the tool approvals of a session when its process attaches again, and ends them when another process registers the session and when the session closes", async () => { + jest.useFakeTimers(fakeTimers) + storeSession(id1, 1, "app") + const {d, agents} = deps(root) + service = await Service.start(d, readDefaultConfig) + const registerFrom = (pid: number) => post("/session", {id: id1, pid, project: "/p/app", config: defaultConfig}) + const approvalsEnded = () => agents[0].turns.filter(turn => turn === "tool approvals ended").length + await registerFrom(300) + const first = new AbortController() + const {attached, firstLine} = attach(id1, first.signal) + await firstLine + first.abort() + await attached + await turnsUntil(() => agents[0].turns.includes("steps ended")) + await registerFrom(300) + const second = new AbortController() + const again = attach(id1, second.signal) + await again.firstLine + expect(approvalsEnded()).toBe(0) + await registerFrom(301) + expect(approvalsEnded()).toBe(1) + second.abort() + await again.attached + await turnsUntil(() => agents[0].turns.filter(turn => turn === "steps ended").length === 2) + await jest.advanceTimersByTimeAsync(10 * minutes) + expect(agents[0].open).toBe(false) + expect(approvalsEnded()).toBe(2) + }) + + it("ends the tool approvals when a process with the PID of an ended process of the session registers it, by the start time of the process, and at each registration of a process whose start time is unknown", async () => { + storeSession(id1, 1, "app") + const {d, agents, starts} = deps(root) + service = await Service.start(d, readDefaultConfig) + const registerFrom = (pid: number) => post("/session", {id: id1, pid, project: "/p/app", config: defaultConfig}) + const approvalsEnded = () => agents[0].turns.filter(turn => turn === "tool approvals ended").length + starts.set(300, "100") + await registerFrom(300) + await registerFrom(300) + expect(approvalsEnded()).toBe(0) + starts.set(300, "200") + await registerFrom(300) + expect(approvalsEnded()).toBe(1) + starts.set(300, undefined) + await registerFrom(300) + await registerFrom(300) + expect(approvalsEnded()).toBe(3) + }) + + it("sends the approved tools only to the attachments of the process that registered the session last, and an empty list to the others", async () => { + storeSession(id1, 1, "app") + const {d, agents} = deps(root) + service = await Service.start(d, readDefaultConfig) + const registerFrom = (pid: number) => post("/session", {id: id1, pid, project: "/p/app", config: defaultConfig}) + const controller = new AbortController() + await registerFrom(300) + const first = attach(id1, controller.signal, 300) + await first.firstLine + await registerFrom(301) + const second = attach(id1, controller.signal, 301) + await second.firstLine + const tools = {tools: [{tool: "Bash", approvedBy: "Alice"}]} + const prompt = {prompt: {text: "hi", from: "Alice", item: 7}} + agents[0].onLine!(tools) + agents[0].onLine!(prompt) + await until(() => first.lines.length === 3 && second.lines.length === 3) + expect(first.lines.slice(1)).toEqual([{tools: []}, prompt]) + expect(second.lines.slice(1)).toEqual([tools, prompt]) + controller.abort() + await first.attached + await second.attached + }) + + it("reads the start time of a running process, the same at each read and another for a later process, and nothing for a process that does not run or an ID that is not a positive integer", async () => { + const reads = process.platform === "linux" || process.platform === "darwin" + const start = await processStart(process.pid) + expect(start).toEqual(reads ? expect.stringMatching(/\S/) : undefined) + expect(await processStart(process.pid)).toBe(start) + const child = spawn(process.execPath, ["-e", "setInterval(() => undefined, 1000)"], {stdio: "ignore"}) + const childStart = await processStart(child.pid!) + child.kill() + await once(child, "exit") + expect(childStart).toEqual(reads ? expect.stringMatching(/\S/) : undefined) + expect(reads && childStart === start).toBe(false) + expect(await processStart(2 ** 22 + 1)).toBeUndefined() + for (const pid of [0, -1, 1.5, "self"]) expect(await processStart(pid as number)).toBeUndefined() + }) + it("does not delay the idle close of an open session with a title", async () => { jest.useFakeTimers(fakeTimers) const {d, agents} = deps(root) diff --git a/packages/simplex-chat-mcp/test/unit/session.test.ts b/packages/simplex-chat-mcp/test/unit/session.test.ts index 11884d5ec0..0d1a7285d9 100644 --- a/packages/simplex-chat-mcp/test/unit/session.test.ts +++ b/packages/simplex-chat-mcp/test/unit/session.test.ts @@ -214,7 +214,29 @@ describe("session server", () => { const {client} = await session({}, () => (spawned(), pending)) await spawning const {result} = await client.request("tools/list") - expect(result.tools.map(({name}: {name: string}) => name)).toEqual(["connect", "send", "receive", "download", "list", "leave", "reply"]) + expect(result.tools.map(({name}: {name: string}) => name)).toEqual(["connect", "send", "receive", "download", "list", "leave", "reply", "pre_tool_use"]) + }) + + it("answers the PreToolUse hook's call with allow for a tool that the service approved, and with an empty text for other tools, after its /attach ends and in a run that is not interactive", async () => { + let attaches = 0 + await fakeService(async res => endWithResult(res, listResult), res => { + attachLine(res) + if (++attaches === 1) res.write(`${JSON.stringify({tools: [{tool: "Bash", approvedBy: "Alice"}]})}\n${JSON.stringify({prompt: {text: "Fix the build", from: "Alice", item: 41}})}\n`) + }) + const attached = next("attach") + const {client} = await session() + const [res] = await attached + await until(() => client.notifications.some(({method}) => method === "notifications/claude/channel")) + const hook = async (to: LineClient, tool: string) => (await to.request("tools/call", {name: "pre_tool_use", arguments: {tool}})).result.content + const allow = [{type: "text", text: JSON.stringify({hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "allow", permissionDecisionReason: "Approved for this session by Alice in the session's SimpleX group."}})}] + const none = [{type: "text", text: ""}] + expect(await hook(client, "Bash")).toEqual(allow) + expect(await hook(client, "Edit")).toEqual(none) + const again = next("attach") + res.destroy() + await again + expect(await hook(client, "Bash")).toEqual(none) + for (const env of [{CLAUDE_CODE_ENTRYPOINT: "sdk-cli"}, {CLAUDE_PLUGIN_OPTION_APPROVE: "x"}]) expect(await hook((await session(env)).client, "Bash")).toEqual(none) }) it("is a channel: it passes prompts and verdicts of the service to Claude Code, and permission requests to the service", async () => { diff --git a/packages/simplex-chat-mcp/test/unit/sessions.test.ts b/packages/simplex-chat-mcp/test/unit/sessions.test.ts index 12278e692a..09cb103719 100644 --- a/packages/simplex-chat-mcp/test/unit/sessions.test.ts +++ b/packages/simplex-chat-mcp/test/unit/sessions.test.ts @@ -565,7 +565,7 @@ describe("session channel", () => { for (const requestId of ["abcde", "fghij", "kmnop"]) session.permission({id: id1, requestId, toolName: "Bash", description: "Run shell command", inputPreview: "rm -rf build"}) await until(() => sentTo(chat, 20).length === 3) const card = "I want to use `Bash`: `Run shell command`\n`rm -rf build`" - expect(sentTo(chat, 20)).toEqual([1, 2, 3].map(n => `${card}\n/'approve ${n}' or /'reject ${n}'`)) + expect(sentTo(chat, 20)).toEqual([1, 2, 3].map(n => `${card}\n/'approve ${n}', /'approve ${n} all' or /'reject ${n}'`)) expect(await session.control.ownerCommand(mallory, {keyword: "approve", params: "1"})).toBeUndefined() expect(await session.control.ownerCommand(invitedAlice, {keyword: "reject", params: "2"})).toBeUndefined() await until(() => chat.updates.length === 2) @@ -597,7 +597,158 @@ describe("session channel", () => { await until(() => sentTo(chat, 20).length === 1) const [card] = sentTo(chat, 20) expect(Buffer.byteLength(JSON.stringify(card))).toBeLessThanOrEqual(15_000) - expect(card.split("\n")).toEqual(["I want to use `Edit`: `Edit a file`", `\`${first}\``, expect.stringMatching(/^`"new_string": "字+…`$/), "/'approve 1' or /'reject 1'"]) + expect(card.split("\n")).toEqual(["I want to use `Edit`: `Edit a file`", `\`${first}\``, expect.stringMatching(/^`"new_string": "字+…`$/), "/'approve 1', /'approve 1 all' or /'reject 1'"]) + }) + + it("approves a tool for the rest of the session by /approve N all: the use runs, the reply names the tool and /revoke, the session gets the approved tools, and a later card of the tool says that Claude Code still asks for it", async () => { + const chat = new FakeChat() + const {session, lines} = await channel(chat) + session.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) + await until(() => sentTo(chat, 20).length === 1) + expect(sentTo(chat, 20)).toEqual(["I want to use `Bash`: `Run shell command`\n`ls`\n/'approve 1', /'approve 1 all' or /'reject 1'"]) + expect(await session.control.ownerCommand(invitedAlice, {keyword: "approve", params: "1 all"})).toBe("Approved `Bash` for the rest of this session by Alice. /'revoke Bash'") + expect(lines).toEqual([{tools: [{tool: "Bash", approvedBy: "Alice"}]}, {permission: {requestId: "abcde", behavior: "allow"}}]) + await until(() => chat.updates.length === 1) + expect(chat.updates[0].text).toBe("I want to use `Bash`: `Run shell command`\n`ls`\nApproved by Alice.") + session.permission({id: id1, requestId: "fghij", toolName: "Bash", description: "Run shell command", inputPreview: "echo x >> .bashrc"}) + session.permission({id: id1, requestId: "kmnop", toolName: "Edit", description: "Edit a file", inputPreview: "a.txt"}) + await until(() => sentTo(chat, 20).length === 3) + expect(sentTo(chat, 20).slice(1)).toEqual([ + "I want to use `Bash`: `Run shell command`\n`echo x >> .bashrc`\n`Bash` is approved for this session, and Claude Code still asks for this use.\n/'approve 2' or /'reject 2'", + "I want to use `Edit`: `Edit a file`\n`a.txt`\n/'approve 3', /'approve 3 all' or /'reject 3'", + ]) + expect(lines).toHaveLength(2) + }) + + it("counts an approved tool only while its approver is an admin or owner, after a role change and after /observer, and sends each change to the session", async () => { + const chat = new FakeChat() + const {hub, session, lines} = await channel(chat) + const dan = member(12, "Dan", T.GroupMemberRole.Admin) + chat.members.set(20, [self, invitedAlice, dan]) + await session.control.load() + const roleChange = (role: T.GroupMemberRole, fromRole: T.GroupMemberRole) => { + chat.members.set(20, [self, invitedAlice, {...dan, memberRole: role}]) + return hub["onEvent"]({type: "memberRole", groupInfo: group(20, "1 · auth"), byMember: invitedAlice, member: {...dan, memberRole: role}, fromRole, toRole: role} as unknown as ChatEvent) + } + const list = () => session.control.ownerCommand(invitedAlice, {keyword: "list", params: ""}) + const bash = {tools: [{tool: "Bash", approvedBy: "Dan"}]} + session.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) + await until(() => session.actions.get(1)?.card !== undefined) + expect(await session.control.ownerCommand(dan, {keyword: "approve", params: "1 all"})).toBe("Approved `Bash` for the rest of this session by Dan. /'revoke Bash'") + expect(await list()).toBe("`Bash` approved for this session by Dan") + await roleChange(T.GroupMemberRole.Member, T.GroupMemberRole.Admin) + await until(() => lines.length === 3) + expect(await list()).toBe("No chats.") + await roleChange(T.GroupMemberRole.Admin, T.GroupMemberRole.Member) + await until(() => lines.length === 4) + expect(await session.control.ownerCommand(invitedAlice, {keyword: "observer", params: "#20 12"})).toBe("Dan is an observer and can't send messages.") + expect(lines.filter(line => line.tools !== undefined)).toEqual([bash, {tools: []}, bash, {tools: []}]) + }) + + it("counts the approved tools of an approver no more when the approver leaves or is removed, and sends the new list to the session", async () => { + const chat = new FakeChat() + const {hub, session, lines} = await channel(chat) + const dan = member(12, "Dan", T.GroupMemberRole.Admin) + const mia = member(13, "Mia", T.GroupMemberRole.Admin) + const danLeft = {...dan, memberStatus: T.GroupMemberStatus.Left} + chat.members.set(20, [self, invitedAlice, dan, mia]) + await session.control.load() + const groupEvent = (type: string, fields: object) => hub["onEvent"]({type, groupInfo: group(20, "1 · auth"), ...fields} as unknown as ChatEvent) + const approveAll = async (approver: T.GroupMember, requestId: string, toolName: string, n: number) => { + session.permission({id: id1, requestId, toolName, description: "Run shell command", inputPreview: "ls"}) + await until(() => session.actions.get(n)?.card !== undefined) + await session.control.ownerCommand(approver, {keyword: "approve", params: `${n} all`}) + } + const toolLines = () => lines.filter(line => line.tools !== undefined) + await approveAll(dan, "abcde", "Bash", 1) + await approveAll(mia, "fghij", "Edit", 2) + chat.members.set(20, [self, invitedAlice, danLeft, mia]) + await groupEvent("leftMember", {member: danLeft}) + await until(() => toolLines().length === 3) + chat.members.set(20, [self, invitedAlice, danLeft]) + await groupEvent("deletedMember", {byMember: invitedAlice, deletedMember: mia, withMessages: false}) + await until(() => toolLines().length === 4) + expect(toolLines()).toEqual([ + {tools: [{tool: "Bash", approvedBy: "Dan"}]}, + {tools: [{tool: "Bash", approvedBy: "Dan"}, {tool: "Edit", approvedBy: "Mia"}]}, + {tools: [{tool: "Edit", approvedBy: "Mia"}]}, + {tools: []}, + ]) + expect(await session.control.ownerCommand(invitedAlice, {keyword: "list", params: ""})).toBe("No chats.") + }) + + const losses: {loss: string; type: string; fields: object}[] = [ + {loss: "the group is deleted", type: "groupDeleted", fields: {member: invitedAlice}}, + {loss: "Claude is removed from the group", type: "deletedMemberUser", fields: {member: invitedAlice, withMessages: false}}, + {loss: "Claude is no longer an owner of the group", type: "memberRole", fields: {byMember: invitedAlice, member: {...self, memberRole: T.GroupMemberRole.Admin}, fromRole: T.GroupMemberRole.Owner, toRole: T.GroupMemberRole.Admin}}, + ] + for (const {loss, type, fields} of losses) { + it(`ends the tool approvals when the session's group is lost because ${loss}, and sends the empty list to the session`, async () => { + const chat = new FakeChat() + const {hub, session, lines} = await channel(chat) + session.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) + await until(() => session.actions.get(1)?.card !== undefined) + await session.control.ownerCommand(invitedAlice, {keyword: "approve", params: "1 all"}) + await hub["onEvent"]({type, groupInfo: group(20, "1 · auth"), ...fields} as unknown as ChatEvent) + await until(() => lines.filter(line => line.tools !== undefined).length === 2) + expect(lines.filter(line => line.tools !== undefined)).toEqual([{tools: [{tool: "Bash", approvedBy: "Alice"}]}, {tools: []}]) + expect(session.control.approvedTools()).toEqual([]) + }) + } + + it("ends the tool approvals when a load finds the session's group lost, and sends the empty list to the session", async () => { + const chat = new FakeChat() + const {session, lines} = await channel(chat) + session.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) + await until(() => session.actions.get(1)?.card !== undefined) + await session.control.ownerCommand(invitedAlice, {keyword: "approve", params: "1 all"}) + const lost = session.control["group"] + session.control["group"] = {...lost, membership: {...lost.membership, memberRole: T.GroupMemberRole.Admin}} + await session.control.load() + expect(lines.filter(line => line.tools !== undefined)).toEqual([{tools: [{tool: "Bash", approvedBy: "Alice"}]}, {tools: []}]) + expect(session.control.approvedTools()).toEqual([]) + }) + + it("revokes an approved tool by /revoke TOOL, lists approved tools after the chats in /list, and answers /approve N all of an action that is not a tool use", async () => { + const chat = new FakeChat() + const {session, lines} = await channel(chat) + chat.chats.set("@4", {chatInfo: ownedContact(4, "SimpleX Directory", id1), items: []}) + const command = (keyword: string, params: string) => session.control.ownerCommand(invitedAlice, {keyword, params}) + session.permission({id: id1, requestId: "abcde", toolName: "mcp__github__create_issue", description: "Create an issue", inputPreview: "{}"}) + session.requestMode("host") + await until(() => sentTo(chat, 20).length === 2) + expect(await command("approve", "2 all")).toBe("Action 2 is not a tool use.") + expect(await command("approve", "9 all")).toBe("Action 9 is not pending.") + expect(await command("approve", "1 all")).toBe("Approved `mcp__github__create_issue` for the rest of this session by Alice. /'revoke mcp__github__create_issue'") + expect(await command("list", "")).toBe("@4 bot SimpleX Directory\n`mcp__github__create_issue` approved for this session by Alice") + expect(await command("revoke", "mcp__github__create_issue")).toBe("Uses of `mcp__github__create_issue` need approval again.") + expect(await command("revoke", "mcp__github__create_issue")).toBe("Uses of `mcp__github__create_issue` have no standing approval.") + expect(await command("list", "")).toBe("@4 bot SimpleX Directory") + expect(session.actions.get(2)?.state).toBe("pending") + expect(lines.filter(line => line.tools !== undefined)).toEqual([{tools: [{tool: "mcp__github__create_issue", approvedBy: "Alice"}]}, {tools: []}]) + }) + + it("keeps the approvals of tools across a detach, sends them to each new attachment, and ends them at endToolApprovals", async () => { + const chat = new FakeChat() + const {session} = await channel(chat) + session.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) + await until(() => session.actions.get(1)?.card !== undefined) + await session.control.ownerCommand(invitedAlice, {keyword: "approve", params: "1 all"}) + const second: AttachLine[] = [] + session.onLine = line => second.push(line) + expect(second).toEqual([{tools: [{tool: "Bash", approvedBy: "Alice"}]}]) + session.onLine = undefined + const third: AttachLine[] = [] + session.onLine = line => third.push(line) + expect(third).toEqual([{tools: [{tool: "Bash", approvedBy: "Alice"}]}]) + session.endToolApprovals() + expect(third).toEqual([{tools: [{tool: "Bash", approvedBy: "Alice"}]}, {tools: []}]) + session.onLine = line => third.push(line) + expect(third).toHaveLength(2) + expect(await session.control.ownerCommand(invitedAlice, {keyword: "list", params: ""})).toBe("No chats.") + session.permission({id: id1, requestId: "fghij", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) + await until(() => sentTo(chat, 20).length === 2) + expect(sentTo(chat, 20)[1]).toBe("I want to use `Bash`: `Run shell command`\n`ls`\n/'approve 2', /'approve 2 all' or /'reject 2'") }) it("passes the messages of owners to the session as prompts, with their files, and not their commands", async () => { @@ -1491,12 +1642,11 @@ describe("session channel", () => { expect(chat.sent).toEqual([]) }) - it("has no commands for files of reply: /approve N all and a bare /revoke are unknown in a session group", async () => { + it("has no command for files of reply: a bare /revoke is unknown in a session group", async () => { const chat = new FakeChat() const {session} = await channel(chat) session.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"}) await until(() => session.actions.get(1)?.card !== undefined) - expect(await session.control.ownerCommand(invitedAlice, {keyword: "approve", params: "1 all"})).toBe(unknownCommand) expect(await session.control.ownerCommand(invitedAlice, {keyword: "revoke", params: ""})).toBe(unknownCommand) expect(session.actions.get(1)?.state).toBe("pending") }) diff --git a/plans/2026-11-13-mcp-allow-tool.md b/plans/2026-11-13-mcp-allow-tool.md new file mode 100644 index 0000000000..82f1a2a547 --- /dev/null +++ b/plans/2026-11-13-mcp-allow-tool.md @@ -0,0 +1,382 @@ +# SimpleX MCP: approve a tool for the rest of a session + +Status: approved by the user on 2026-11-13 and implemented on `ep/mcp-allow-tool`, stacked on `ep/mcp-activity`; decisions 29 to 32 were made in the implementation, 33 to 35 after review round 1, and 36 and 37 after the re-check of `1d16c6942`; decision 36 was amended after the re-check of `b7032308c`. Code references: master `97bbbd9ac` (MCP 0.3.0 with #8157). Claude Code references: version 2.1.322 and its binary at the offsets given, the documentation pages quoted, and three `claude -p` runs of Claude Code 2.1.323, recorded on 2026-11-13 (R1 to R3). Decisions of the 0.3.0 plan are cited as "0.3.0 decision N". + +The runs used a test MCP server whose tool `pre_tool_use` answers a PreToolUse hook of type `mcp_tool`, with `--setting-sources project --permission-mode default`. A `-p` run refuses a call that would show a prompt, so a refusal there stands for a prompt in an interactive session. +- R1: the hook answered `allow` for Bash and Write. `echo one > a.txt` with Bash ran, and a Write of `notes.txt` ran. A Write of `.bashrc` was refused: "Claude requested permissions to edit .../.bashrc which is a sensitive file." The server logged three calls, `{"tool":"Bash"}`, `{"tool":"Write"}` and `{"tool":"Write"}`. +- R2: the hook answered with empty text. Bash and Write were refused, and no file was written. The run's final answer failed with an API error after the refusals. +- R3: the server and the hook were in a test plugin loaded with `--plugin-dir`, and the hook named the server `plugin:gatep:gate`. The hook answered `allow` for Bash only. Bash ran, and Write was refused. + +## 1. Goal + +Roadmap line of [ROADMAP.md](../packages/simplex-chat-mcp/ROADMAP.md): "Allow a tool for the rest of a session with one tap." The user's feature list of 2026-11-11 has no other words on it. + +Outcome: +- A tool-use card has a third command, `/approve N all`. One tap allows this use and every later use of its tool in the session. +- Later uses of that tool run without a card and without a terminal prompt. +- Claude Code still asks where its own rules require it, also for an approved tool, and that prompt comes as a card. +- `/list` shows the approval. `/revoke TOOL` removes it before the session ends. + +## 2. What users see + +Before, in 0.3.0: +``` +Claude: I want to use `Bash`: `List files` + `PREVIEW` + /approve 5 or /reject 5 +``` + +After: +``` +Claude: I want to use `Bash`: `List files` + `PREVIEW` + /approve 5, /approve 5 all or /reject 5 +Alice: /approve 5 all +Claude: (replying to Alice) Approved `Bash` for the rest of this session by Alice. /revoke Bash +``` + +The card is edited to `Approved by Alice.` as after `/approve 5`. PREVIEW is the input preview of Claude Code, one code span per line, as in 0.3.0. The app shows each `/'...'` command as a command that one tap sends. + +Texts, as the code writes them: +``` +where text +commands of a tool-use card /'approve N', /'approve N all' or /'reject N' +reply to /approve N all Approved `TOOL` for the rest of this session by NAME. /'revoke TOOL' +card of a use Claude Code still asks I want to use `TOOL`: `DESCRIPTION` +for, while TOOL is approved PREVIEW lines + `TOOL` is approved for this session, and Claude Code still asks for this use. + /'approve N' or /'reject N' +reply to /revoke TOOL Uses of `TOOL` need approval again. +reply to /revoke TOOL, no approval Uses of `TOOL` have no standing approval. +/list, a line per approved tool `TOOL` approved for this session by NAME +reply to /approve N all, N not a tool Action N is not a tool use. +use +``` + +Before and after: +``` +event 0.3.0 this pull request +Claude Code asks for a tool use card: /approve N or /reject N card: /approve N, /approve N all or /reject N +/approve N all Unknown command. the use runs; the reply above +a later use of the approved tool card and terminal prompt runs: no card, no terminal prompt +a later use Claude Code still asks for: card and terminal prompt card with the line above, and terminal prompt + a matching ask rule, a write to a + protected path such as .bashrc or + .git, plan mode, the auto mode + classifier +/revoke TOOL Unknown command. the reply above; later uses ask again +/list chats chats, then approved tools +the session ends cards end cards and approvals end +``` + +Rules: +- An approval covers every later use of its tool in the Claude Code session, by subagents too. +- It counts while its approver is an admin or owner of the group, as a standing approval of a chat does (0.3.0 decision 93). +- It is dropped when the session's Claude Code process ends: when another process opens the session, when the session closes, or when the service restarts (decisions 33 and 36). It also ends when the session's group is lost (decision 35). +- While two Claude Code processes have the session open, only the one that opened it last gets it (decision 37). +- One tap approves its own card only. The other pending cards of the same tool stay pending. +- The terminal shows nothing at the approval. Claude Code's `/permissions` does not list it, because the plugin keeps it. +- With `ep/mcp-activity`, each use that runs has its step line in the group. + +```mermaid +sequenceDiagram + participant CC as Claude Code + participant S as session server + participant D as service + participant O as owner's app + CC->>S: permission_request abcde, Bash + S->>D: POST /permission + D->>O: card 5: /approve 5, /approve 5 all or /reject 5 + O->>D: /approve 5 all + D->>S: line tools: Bash approved by Alice + D->>S: line permission: abcde allow + S->>CC: verdict allow, the use runs + D->>O: card edited: Approved by Alice + D->>O: reply: Approved Bash for the rest of this session by Alice + CC->>S: PreToolUse hook: tools/call pre_tool_use, tool Bash + S-->>CC: allow + CC->>CC: the next Bash use runs, no prompt +``` + +A use that Claude Code asks for by its own rules: +```mermaid +sequenceDiagram + participant CC as Claude Code + participant S as session server + participant D as service + participant O as owner's app + CC->>S: PreToolUse hook: tools/call pre_tool_use, tool Bash + S-->>CC: allow + CC->>CC: the command writes to .bashrc, a protected path: the permission flow + CC->>S: permission_request fghij, Bash + S->>D: POST /permission + D->>O: card 6 with the line: Bash is approved, and Claude Code still asks + O->>D: /approve 6 or /reject 6 +``` + +## 3. Questions for the user + +None. The rules of the 0.3.0 plan decide who approves: rule 3 of its trust model gives approvals of tool use to admins and owners. The roadmap line decides the scope, a tool, and the lifetime, the rest of a session. Every other choice is a decision below. + +## 4. Decisions + +Facts: +1. A channel verdict has only `request_id` and `behavior`, `allow` or `deny` (binary 308442958: `params:u({request_id:o(),behavior:B(["allow","deny"])})`). Claude Code applies a channel `allow` to the one call: it records `permanent: false` and allows the input as asked, with no permission update (320830192 to 320830575). The documentation: "Neither verdict affects future calls." (https://code.claude.com/docs/en/channels-reference, "Permission request fields"). An answer of Remote Control can carry `updatedPermissions` (320828195); a channel verdict can't. +2. The terminal has no option that allows a whole tool for the session. Its "Yes, and don't ask again" for a Bash command adds a rule for that command to `.claude/settings.local.json`, the destination `localSettings` (binary 283896153). For file edits it switches the session to `acceptEdits` (289605509). The permissions page: "Bash commands ... Permanently per repository and command"; "File modification ... Until session end" (https://code.claude.com/docs/en/permissions). +3. A PermissionRequest hook gets `tool_name`, `tool_input` and `permission_suggestions`, without `tool_use_id` (binary 296949420). The hooks page: "PermissionRequest hooks receive tool_name and tool_input fields like PreToolUse hooks, but without tool_use_id." The request ID of the channel is five random letters (`adi`, 313061500). Nothing links a PermissionRequest hook to a card. +4. When a PermissionRequest hook answers `allow` with `updatedInput` and Claude Code asks again, it removes the channel's handler of that prompt before it shows the prompt again (`"reprompted"in q`, 320831909). The card of that prompt can then no longer answer it. +5. A PreToolUse hook's `allow` skips the prompt only where Claude Code's rules allow it. Claude Code re-checks the call: a deny rule refuses it, and an ask rule, a safety check, such as a write to a protected path, or plan mode sends it through the full permission flow (binary 297460810: "but an ask rule, a safety check, a ToolHost's person-only ask or plan mode requires the full permission pipeline"; the check `zx` at 296504842 returns any safety-check ask, `il` at 296516350). The hooks page: `"allow"` "skips the permission prompt, except for actions no mode auto-approves ... Deny and ask rules are still evaluated regardless of what the hook returns". The permission modes page: "permissions.allow rules in settings files do not pre-approve protected-path writes." In auto mode the classifier decides the call (297461722). The full permission flow relays the prompt to the channel. R1: under the hook's `allow`, the Write of `.bashrc` was refused. +6. A hook of type `mcp_tool` calls a tool of an MCP server with `tools/call`, without a look-up in the server's tool list (binary 296921422), and reads its text as the output of a command hook. `${tool_name}` in its input is replaced from the hook's input (R1). A plugin names its own server `plugin:PLUGIN:SERVER` (hooks page; R3). An empty text is no decision (R2). Claude Code has had `mcp_tool` hooks since 2.1.118 (CHANGELOG: "Hooks can now invoke MCP tools directly via `type: "mcp_tool"`"), and the plugin needs 2.1.214 or later ([REFERENCE.md, "Install"](../packages/simplex-chat-mcp/REFERENCE.md#install)). +7. The plugin's server is `plugin:simplex:simplex`: it is the `source` of its channel tags ([`channelPrompt`](../packages/simplex-chat-mcp/src/hub.ts)). +8. The MCP SDK 2.3.1 lists every registered and enabled tool and answers `tools/call` only for them (`node_modules/@modelcontextprotocol/server/dist/mcp-BumlNux0.cjs:1763-1780`). A second handler of `tools/call` is refused (`assertCanSetRequestHandler`, `src-BhnGYybN.cjs:6902-6904`). So the tool that the hook calls is listed to Claude. +9. Tool names match `^[a-zA-Z0-9_-]{1,128}$` (Messages API, the `name` of a tool). +10. In 0.3.0, `/approve N all` and `/revoke TOOL` get `Unknown command.` in a session group ([`ownerRequest`](../packages/simplex-chat-mcp/src/control.ts); the test "has no commands for files of reply: /approve N all and a bare /revoke are unknown in a session group" of [sessions.test.ts](../packages/simplex-chat-mcp/test/unit/sessions.test.ts)). +11. A standing approval of a chat counts only while its approver is an approver ([`Control.standingApprover`](../packages/simplex-chat-mcp/src/control.ts)); after `/observer`, the members are read again ([`Control.setObserver`](../packages/simplex-chat-mcp/src/control.ts)). +12. Tool-use cards end at the last detach ([`Service.onAttach`](../packages/simplex-chat-mcp/src/service.ts), [`Session.endPermissions`](../packages/simplex-chat-mcp/src/hub.ts)). +13. `ep/mcp-activity` posts a step line for each tool use of the main conversation (its plan, section 2). +14. With Claude Code before 2.1.299, a PreToolUse `allow` ran writes in plan mode (CHANGELOG 2.1.299: "Fixed plan mode running a write ... that a `PreToolUse` hook ... allowed"). The re-check of fact 5 is in the binaries of 2.1.303 to 2.1.323 on this machine. + +Choices: + +15. `/approve N all` on a pending tool-use card approves its use and records the approval of its tool. It follows `/approve CHAT all` and `/receive CHAT N all`, where `all` adds the later ones. +16. A PreToolUse hook of type `mcp_tool` applies the approval (section 5). Claude Code's own rules keep asking (fact 5). +17. Admins and owners approve and revoke, as for every approval (0.3.0 trust model, rule 3). An approval counts while its approver is an admin or owner of the group, and counts again when that member becomes one again (fact 11). +18. The approvals are kept in memory and dropped at the last detach, when the cards are ended (fact 12); replaced by decision 33. They are not stored: a stored approval would outlive the Claude Code process that it was given for. +19. `/approve N all` approves card N only. Other pending cards of the tool stay pending: Claude Code may ask for them by its own rules (fact 5). +20. A card of an approved tool has the line of section 2 before its commands, and no `all` command. The line is fixed when the card is created. +21. The texts are those of section 2. `/revoke TOOL` accepts a name of letters, digits, `_` and `-` (fact 9), so it never matches a chat reference. `/list` puts the tool lines after the chat lines; `No chats.` stays only when both are empty. +22. No post for a use that the approval allows. The step lines show it (fact 13). +23. The session server has the tool `pre_tool_use`, input `{tool}`. It answers from its own list, without a request to the service, and never with an error: also before the service attaches, in a run that is not interactive and with an invalid option. The answer is the text `{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","permissionDecisionReason":"Approved for this session by NAME in the session's SimpleX group."}}`, or an empty text. Claude Code writes the reason of an `allow` to its debug log only (hooks page). +24. Its description, which Claude sees: `Answers the plugin's PreToolUse hook before each tool use: allow for a tool that an admin or owner of the SimpleX group of this session approved for the rest of the session, and nothing otherwise. You never need to call it.` +25. The service sends the approved tools as an `/attach` line `{tools: [{tool, approvedBy}]}`. It sends it to each new attachment, and when the list changes: at an approval, at a revocation, after a membership event and after `/observer`. The session server replaces its list at each such line, and empties it when its attachment ends. +26. The hook's timeout is 5 s. A hook that times out does not block the call (hooks page: "a timed-out command, http, or mcp_tool hook doesn't block the tool call"). +27. The protocol version stays 1. `tools` is optional; a session server of 0.3.0 ignores the line, because `channelNotification` returns nothing for it ([`channelNotification`](../packages/simplex-chat-mcp/src/session.ts)). +28. The service logs `TOOL approved for the rest of session N by NAME.` and `TOOL needs approval again in session N.` Replaced by decision 29. + +Decided in the implementation: + +29. The log lines name the group, as the other log lines of `Control` do: `TOOL approved for the rest of the session in "N · NAME" by MEMBER.` and `TOOL needs approval again in "N · NAME".` `Control` has the group's name and not the session's number. +30. After a membership event, the hub sends the approved tools right after `Control` reads the members again, before the rights post. A refused rights post then can't keep a demoted approver's tools in the session server's list. +31. The session server keeps the list of each attachment apart and answers from the list of the current one. A list is then dropped also when the session server drops its attachment after a failed call, which ends the stream without the end handler of the current attachment. +32. The docs cite the new code by file and function name, by the user's rule of 2026-11-13 that line numbers create churn. The line citations of other code in `spec/`, which this change shifts in `control.ts`, `hub.ts`, `session.ts`, `service.ts` and `protocol.ts`, are not renumbered; the move of the specs to function names replaces them. + +Decided after review round 1 of `c4099e36d`: + +33. The approvals belong to the Claude Code process of the session, as the approved lifetime "the rest of a session" requires. Before, the last detach ended them, so a session server that dropped its attachment after a failed call and attached again lost them without a post. Now `Service.onAttach` keeps them; `Service.onSession` ends them when the session is registered from a process other than the recorded one (decision 36), and `Service.scheduleIdle` ends them when the session closes, 10 minutes after Claude Code ends. The close waits while a call runs or the session has an action in memory other than a `mode` card, such as a pending card (`Session.busy`). It replaces the drop at the last detach of decision 18. Between the end of Claude Code and the session's close, `/list` still shows them; no process can use them, because another process's registration ends them first. +34. While the plugin's MCP server is not connected, Claude Code 2.1.322 reports a non-blocking PreToolUse hook error at each tool use: `Ayr` returns `MCP server 'plugin:simplex:simplex' not connected`, and the hook runner yields `hook_non_blocking_error` (binary: `let st=` of `Ayr` at 296919784; the error branch `if(yu.error||!yu.ok)` at 297052655, with its `hook_non_blocking_error` yield at 297052849). REFERENCE says so; the hook stays of type `mcp_tool`. +35. The tool approvals end when the session's group is lost: when it is deleted, when Claude is removed, and when Claude is no longer its owner, as `Control.onEvent` finds, and at `Control.load` of a lost group. `Control.lose` ends them and calls `toolsChanged`, so the session server gets `{tools: []}`. `Control.load` runs when the hub opens a session and at a rename (`Hub.session`, `Session.rename`, `Control.rename`). After a load, the `toolsChanged` call of `Control.lose` sends the empty list, as `Hub.onEvent` does after an event; the test of a load of a lost group fails without that call. + +Decided after the re-check of `1d16c6942`: + +36. A process of a session is its ID and its start time. `processStart` reads the start time: on Linux, field 22 of `/proc/PID/stat`, the start in clock ticks after boot, by one file read; on macOS, the output of `/bin/ps -o lstart= -p PID`, the start to the second, by one `ps` run with a 2 s timeout. It returns nothing on other systems, for a process that does not run, after a failed read, and for an ID that is not a positive integer, which reaches neither the path nor the `ps` arguments. `Service.onSession` reads it before its wait for a title, records it in `Entry.started`, and ends the approvals when a process was recorded and the ID differs, the start time differs, or the start time is unknown. On other systems the approvals then end at each `/session` of the session's process, as after a failed call. +37. `/attach` has the session server's parent process ID, `pid`. `Service.onAttach` records it with the attachment's writer in `Entry.writers`. The session's line writer passes a `{tools}` line to the writers whose `pid` is the one of the last `/session`, and `{tools: []}` to the others; the other lines reach every writer. No attachment is ended. + +## 5. Design + +Options: +``` +option producer consumers Claude Code's rules cost +P. PreToolUse hook of type mcp_tool the hub keeps the approvals the session server keeps a list kept (fact 5) about 75 source lines; one tool + (chosen) and sends them on /attach and answers the hook; Claude Code listed to Claude (fact 8); one + calls it in process stdio call per tool use +S. the hub answers later prompts the hub keeps the approvals none bypassed about 45 source lines; the + of the tool at once and answers the channel terminal prompt opens and closes + at each use +H. PermissionRequest hook adds a the hub keeps the approvals a hook process per prompt waits kept, then the card about 140 source lines + Claude Code session rule and answers the hook for the card's decision can't answer (fact 4) +C. PreToolUse hook of type command as P a node process per tool use kept about 50 ms per tool use +``` + +Under S, the hub answers every prompt of the tool, also the prompts that an allow rule never skips, such as a write to `.bashrc` or `.git/hooks` and a match of the person's ask rules. Under H, no field links a hook's prompt to its card (fact 3), and after a re-ask the card no longer answers the prompt (fact 4); a rule in Claude Code can't be revoked from the group either. C needs a process for every tool use of every session. Under P, Claude Code's rules stay in force, the running session server answers, and a revocation applies at once. The tool that P adds is visible to Claude, because an unlisted tool would need the SDK's private handler map (fact 8). + +Changes: +``` +file function change +hooks/hooks.json PreToolUse + {"matcher": "*", "hooks": [{"type": "mcp_tool", "server": "plugin:simplex:simplex", + "tool": "pre_tool_use", "input": {"tool": "${tool_name}"}, "timeout": 5}]} +src/protocol.ts AttachLine + tools?: ApprovedTool[] + ApprovedTool new: {tool, approvedBy} + AttachRequest + pid?: number (decision 37) +src/session.ts startSession registers pre_tool_use with the description of decision 24 + ServiceLink + its list: replaced at a tools line, emptied when its /attach ends; approvedBy(tool) + ServiceLink.open /attach with the parent process ID (decision 37) + hookOutput new: the allow JSON of decision 23, or "" +src/actions.ts PermissionAction + toolApproved: boolean +src/control.ts SessionOptions + toolsChanged + OwnerRequest, ownerRequest + approveTool {action}: "approve N all"; + revokeTool {tool}: "revoke TOOL"; session groups only + ownerCommand approveTool, in the action requests after the pending check: a tool use, else + "Action N is not a tool use."; revokeTool + approveTool, revokeTool new: record or delete, log, toolsChanged, the replies of section 2 + approvedTools new: the approvals whose approver is an approver now + endToolApprovals new: empties the approvals + lose endToolApprovals, then toolsChanged (decision 35) + setObserver toolsChanged after the members are read again + chatsText + a line per approved tool + requestLines, commandsLine permission: the line of an approved tool; the all command otherwise +src/hub.ts Session constructor + toolsChanged: () => this.sendTools() + onLine setter a new attachment gets the approved tools + permission toolApproved from control.approvedTools() + sendTools new: the tools line when the list differs from the one sent + endToolApprovals new: control.endToolApprovals(), then sendTools() + Hub.onEvent the control events of a session group end with session.sendTools() +src/service.ts SessionLike + endToolApprovals() + ServiceDeps, processStart new: the start time of a process, for a positive integer ID; /bin/ps with a + timeout (decision 36) + Entry + started; writers record the pid of their /attach + onSession ends the approvals at another process ID, another start time or an + unknown one (decisions 33, 36) + onAttach {tools} to the writers of the last /session's pid, {tools: []} to the + others (decision 37) + scheduleIdle ends the approvals at the session's close (decision 33) +``` + +Service: +``` +on /approve N all by approver A: action N pending, with a card, of tool permission; else the replies of section 2 + approvals[TOOL] = {A's name, A's member ID, now} + log; send tools + approve N: allow pushed, card "Approved by A." + reply "Approved `TOOL` for the rest of this session by A. /'revoke TOOL'" +on /revoke TOOL by an approver: approvals has TOOL: delete it, log, send tools, reply "Uses of `TOOL` need approval again." + otherwise: reply "Uses of `TOOL` have no standing approval." +approved tools: the approvals whose member is an admin or owner of the group now, other than Claude and User +send tools: approved tools differ from those last sent: line {tools} to the attachments + of the process of the last /session, {tools: []} to the others (decision 37) +on a new attachment: last sent = []; send tools +on a membership event, /observer: send tools +on the last detach: cards ended (0.3.0); approvals kept; last sent = [] +on /session from another process: approvals emptied; a process is its ID and start time; an unknown start time + counts as another process (decisions 33, 36) +on the session's close: approvals emptied (decision 33); the close waits while a call runs or an + action other than a mode card, such as a pending card, is in memory +on the group's loss: approvals emptied; send tools; found at an event or a load (decision 35) +on permission_request of TOOL: card, as in 0.3.0; TOOL among the approved tools: the line of section 2 and no all command +``` + +Session server and Claude Code: +``` +on its /attach: the request has its parent process ID (decision 37) +on a line {tools}: list = tools +on the end of its /attach: list = [] +on PreToolUse(tool_name): the mcp_tool hook calls pre_tool_use {tool: tool_name} + list has tool: allow, with the reason of decision 23 + otherwise: no decision +Claude Code, on allow: runs the call, unless a deny or ask rule, a safety check, plan mode or the auto mode + classifier sends it through the permission flow; that prompt is relayed as a card +``` + +```mermaid +flowchart LR + O[approver: /approve N all] --> C[Control: approvals in memory] + C --> H[Session: send tools] + E[membership event, /observer] --> H + A[new attachment] --> H + H -- line tools on /attach --> L[session server: list] + H -- empty tools line on /attach --> K[session server of another process: empty list] + X[another process registers, the session closes, or the group is lost] --> Z[approvals emptied] + Z --> H + P[Claude Code: PreToolUse] -- tools/call pre_tool_use --> L + L -- allow or nothing --> P + P --> R{Claude Code's rules ask} + R -- no --> U[the use runs] + R -- yes --> Q[permission flow: card with the approved line] +``` + +```mermaid +stateDiagram-v2 + [*] --> approved: /approve N all + approved --> inactive: its approver is no longer an admin or owner + inactive --> approved: its approver is an admin or owner again + inactive --> approved: /approve N all by another approver, who is recorded + approved --> [*]: /revoke TOOL, the session closes, another process registers it, or the group is lost + inactive --> [*]: /revoke TOOL, the session closes, another process registers it, or the group is lost +``` + +## 6. Compatibility + +- Older SimpleX apps: text messages with command links, as in 0.3.0. +- Older Claude Code: `mcp_tool` hooks exist in every version the plugin supports (fact 6). With Claude Code before 2.1.299, an approved tool also runs writes in plan mode (fact 14); REFERENCE says so. +- Older plugin data folders: nothing is stored. A session server of 0.3.0 with this service ignores the tools line (decision 27). A service of 0.3.0 with this session server sends no tools line, so the hook gets no decision. The plugin stops an older service when it starts one of its own ([`ServiceClient.ensureService`](../packages/simplex-chat-mcp/src/client.ts)), so such a pair runs only until then. `package.json` stays at 0.3.0; the release bumps it. +- `serve`: unchanged. Its control chat parses neither request ([`ownerRequest`](../packages/simplex-chat-mcp/src/control.ts)), and it has no hooks. + +## 7. Acceptance and tests + +Done when: +``` +# criterion checked by +1 a tool-use card offers /approve N all; the tap allows the use and replies with /revoke TOOL unit: sessions; e2e +2 the session server answers the hook with allow for an approved tool, nothing otherwise unit: session +3 the approval reaches the session at once, and a new attachment gets it unit: sessions, service +4 an approval counts only while its approver is an admin or owner, also after /observer unit: sessions; e2e +5 /revoke TOOL ends it, /list shows it, /approve N all of another action is refused unit: sessions +6 the approvals hold across a re-attach; another process or the session's close ends them unit: sessions, service, session +7 a card of an approved tool has the line and no all command unit: sessions, cards +8 hooks.json has the mcp_tool hook; tools/list has pre_tool_use unit: plugin, session; e2e launch +9 real session: an approved Bash runs without a prompt; a write to .bashrc still asks TESTING check +10 serve and the other 0.3.0 tests pass unchanged, but for the tool list and the commands line npm test, e2e +11 a process is its ID and start time; another or an unknown start time ends the approvals unit: service +12 the group's loss ends the approvals; only the last process's attachments get them unit: sessions, service +``` + +Tests: +- `test/unit/sessions.test.ts`, "session channel": + - new "approves a tool for the rest of the session by /approve N all: the use runs, the reply names the tool and /revoke, the session gets the approved tools, and a later card of the tool says that Claude Code still asks for it". It fails on master, which replies `Unknown command.` + - new "counts an approved tool only while its approver is an admin or owner, after a role change and after /observer, and sends each change to the session". + - new "revokes an approved tool by /revoke TOOL, lists approved tools after the chats in /list, and answers /approve N all of an action that is not a tool use". + - new "keeps the approvals of tools across a detach, sends them to each new attachment, and ends them at endToolApprovals" (decision 33). + - new "counts the approved tools of an approver no more when the approver leaves or is removed, and sends the new list to the session". + - new, for each loss of decision 35: "ends the tool approvals when the session's group is lost because LOSS, and sends the empty list to the session", and "ends the tool approvals when a load finds the session's group lost, and sends the empty list to the session". + - changed: the cards test (559-577) and the preview test (589-598) expect the new commands line. The test of 1163-1171 keeps the bare `/revoke` as unknown and drops `/approve N all`. +- `test/unit/session.test.ts`, "session server": new "answers the PreToolUse hook's call with allow for a tool that the service approved, and with an empty text for other tools, after its /attach ends and in a run that is not interactive". It fails on master: there is no `pre_tool_use`. The tool list of 209 adds `pre_tool_use`. +- `test/unit/service.test.ts`: the fake session records `endToolApprovals`, and the deps give a start time per PID. New: "keeps the tool approvals of a session when its process attaches again, and ends them when another process registers the session and when the session closes" (decision 33); "ends the tool approvals when a process with the PID of an ended process of the session registers it, by the start time of the process, and at each registration of a process whose start time is unknown" and "reads the start time of a running process, the same at each read and another for a later process, and nothing for a process that does not run or an ID that is not a positive integer" (decision 36); "sends the approved tools only to the attachments of the process that registered the session last, and an empty list to the others" (decision 37). +- `test/unit/cards.test.ts`: the permission card with and without `toolApproved`. +- `test/unit/plugin.test.ts`: the hooks test (41-47) expects the `mcp_tool` entry. +- `test/e2e/service.test.ts`: the test of 426 adds `/approve N all` from the owner: the stream gets the tools line and `allow`, and the owner gets the reply; its `/attach` has the `pid` of its `/session` (decision 37). The test of 618 adds the tools line `[]` after `/observer` of the admin who approved Bash. The tool list of 714 adds `pre_tool_use`. +- `test/e2e/launch.test.ts:66`: the tool list adds `pre_tool_use`. +- Run: `npm test --prefix packages/simplex-chat-mcp`, and the end-to-end tests as TESTING.md states, in the reduced build of CI. No app changes, so no app test workflows. +- TESTING.md, check 7 of a real session, extended: tap `/approve N all` on a Bash card; ask for `pwd` with Bash, which runs without a card or a terminal prompt; ask Claude to append a line to `.bashrc` in the project with Bash, which gets a card with the line of section 2; send `/revoke Bash`, after which Bash asks again; exit, start with `--continue`, and Bash asks again. + +## 8. Docs to change + +- `README.md:36`: one tap can also approve a tool for the rest of the session. Safety: an approved tool runs without asking until the session ends or `/revoke`, and Claude Code still asks where its own rules require. +- `REFERENCE.md`: "Tool use" (644-654): the commands, the rules of section 2, `/revoke TOOL`, `/list`, the minimum version for plan mode. "Sessions and their groups" (594): the new commands. The parts table (495): the `mcp_tool` hook and the tool `pre_tool_use`. "Plugin security" (708-720): an approved tool skips the terminal prompt, and Claude Code's own rules still apply to it. +- `ROADMAP.md:23`: the line is removed. +- `spec/api.md`: 4.1 (the tool `pre_tool_use`), 4.3 (the requests, the replies and the permission card), 4.6 (the tools line of `/attach`), 4.8 (the hook in `hooks.json`). +- `spec/architecture.md`: 8.2 (`session.ts`, `hub.ts`, `control.ts`), 8.3 (the approvals in memory), 8.5 (the rule and the state machine of section 5). +- `spec/flows.md`: flow 22 notes; a new flow 34, a tool approved for the rest of a session, with both diagrams of section 2. +- `TESTING.md`: the automated tests summary (147-190) and check 7. + +## 9. Conflict areas with the other items + +``` +file where items +hooks/hooks.json PreToolUse mcp-activity adds a "*" entry; the two "*" entries merge into one +src/protocol.ts AttachLine (262-265) mcp-replies (prompt.replyTo), mcp-reactions +src/session.ts startSession (52-57), ServiceLink.open (160-185), mcp-replies (channelInstructions, channelNotification), + channelNotification (197-201) mcp-live-answers +src/service.ts SessionLike (36-48), onAttach close (315-323) mcp-activity (endSteps) +src/hub.ts Session constructor (98-103), onLine (114-117), mcp-activity (turn, post), mcp-replies, mcp-session-list + permission (169-178), Hub.onEvent (519) +src/control.ts ownerRequest, ownerCommand, chatsText, requestLines, mcp-session-list, if it reads cards or adds commands + commandsLine +test/unit/sessions.test.ts session channel (538-1171) mcp-activity, mcp-replies, mcp-reactions +test/unit/session.test.ts tool list (209), channel test (212-238) mcp-replies +test/unit/service.test.ts fake session (82-84), 599-621 mcp-activity +test/unit/plugin.test.ts hooks test (41-47) mcp-activity +test/e2e/service.test.ts tests of 426, 618, 695 mcp-activity, mcp-replies, mcp-agent-profile, mcp-fixes +REFERENCE.md Tool use, parts table, Plugin security mcp-activity, mcp-fixes +ROADMAP.md line 23, adjacent to 22 mcp-context-summary +spec/* api 4.1, 4.3, 4.6, 4.8; architecture 8.2-8.5; flow 22 every item +``` + +## 10. Estimate + +``` +part source lines test lines +control.ts, actions.ts 40 90 (sessions, cards) +hub.ts, service.ts 15 60 (sessions, service) +session.ts, protocol.ts, hooks.json 20 40 (session, plugin) +e2e 30 +docs about 70 lines of text +``` +About one working day, with two review rounds.