From d6e6e99b6050db58fea89bffda8fa4a78a2f4c1f Mon Sep 17 00:00:00 2001 From: brenzi-agent Date: Sat, 21 Nov 2026 13:36:56 +0100 Subject: [PATCH] mcp server: recall the chat history in a new agent session (#8141) * mcp server: recall the chat history in a new agent session * docs: chat history in receive for a new agent session * mcp server: type the history page for the compiler * mcp server: recall the chat history after a compaction too * docs: history plan changes with the message helpers of master Claude-Session: https://claude.ai/code/session_01AV2VpomCCQNciqggT9gr75 * docs: drop anchor remapping from the docs table of the history plan Claude-Session: https://claude.ai/code/session_01AV2VpomCCQNciqggT9gr75 --------- Co-authored-by: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com> --- packages/simplex-chat-mcp/REFERENCE.md | 5 +- packages/simplex-chat-mcp/TESTING.md | 1 + packages/simplex-chat-mcp/spec/README.md | 2 +- packages/simplex-chat-mcp/spec/api.md | 12 ++- .../simplex-chat-mcp/spec/architecture.md | 4 +- packages/simplex-chat-mcp/spec/flows.md | 8 +- packages/simplex-chat-mcp/src/messages.ts | 11 ++ packages/simplex-chat-mcp/src/tools.ts | 18 +++- .../simplex-chat-mcp/test/unit/http.test.ts | 2 + .../test/unit/messages.test.ts | 101 ++++++++++++++++++ plans/2026-10-19-mcp-server.md | 17 ++- plans/2026-11-12-mcp-history.md | 73 +++++++++++++ 12 files changed, 236 insertions(+), 18 deletions(-) create mode 100644 plans/2026-11-12-mcp-history.md diff --git a/packages/simplex-chat-mcp/REFERENCE.md b/packages/simplex-chat-mcp/REFERENCE.md index 557b0092be..82426c5c8c 100644 --- a/packages/simplex-chat-mcp/REFERENCE.md +++ b/packages/simplex-chat-mcp/REFERENCE.md @@ -299,7 +299,7 @@ Six tools: |---|---| | `connect` | Joins a contact, bot, business, group or channel by a link or a SimpleX name, as the agent's profile or incognito. Returns the chat, its profile, welcome message, the commands a bot advertises, and the messages so far. | | `send` | Sends a message, with a file of this computer when asked, and returns every message received in that chat after it, until none arrives for `idle` seconds (30 by default). A directory bot's search results arrive this way. | -| `receive` | Returns the chat's unread messages and those that arrive while it waits, waiting for one when asked. | +| `receive` | Returns the chat's unread messages and those that arrive while it waits, waiting for one when asked. With `history`, it also returns up to 50 messages before the new ones, the agent's own included. | | `download` | Downloads the file of a received message to the data folder and returns its full path. | | `list` | Lists the agent's chats with unread counts and `approved: true` for chats approved for all messages, and its actions without a result. | | `leave` | Deletes a contact, or leaves a group, business chat or channel, and deletes the chat; the contact or the members are notified. | @@ -348,6 +348,8 @@ answer each one in that chat, and call receive again after every answer, until I Approve the connection in "My Agent", and accept the request in the app if it asks. On the card of the agent's first answer, tap `all`: its later answers to you need no approval. +In a new Claude Code session, give the same prompt again. The agent can recall the conversation: `receive` with `history` returns up to 50 earlier messages of that chat, its own answers included. + ## Several agents Each agent is its own process, with its own data folder, port, agent control chat and Claude Code server: @@ -367,6 +369,7 @@ Add an entry with the URL `http://127.0.0.1:5226/mcp` and the header `Authorizat |---|---| | The server was not running when Claude Code started | Start the server, then run `/mcp reconnect all` in Claude Code (2.1.284 or later). | | The server restarted while Claude Code was running | Claude Code reconnects up to five times within about 30 seconds. After that, in an interactive session, run `/mcp reconnect all`; `claude -p` runs and Agent SDK sessions keep retrying for about half an hour. Open calls fail, and pending actions are cancelled; the agent's repeated call creates a new request. | +| The Claude Code session ended or was compacted | Ask the agent to recall the chat: `receive` with `history` returns up to 50 messages before the new ones, the agent's own included. | | A second server was started on the same data folder | It exits with `Another server uses (PID N). If no server runs, remove /lock.` | | Every owner left the agent control chat or was removed | `connect`, `send`, `download` and `leave` fail. Without `--owners`, the server logs `No owners in the agent control chat.` and prints a new link; join with it. With an `--owners` list, the agent posts and the server logs `No owners remain: restart the server with --reset-owners --owners`. | | The agent was removed from the agent control chat, the chat was deleted, or the agent lost its owner role | `connect`, `send`, `download` and `leave` fail, and the server logs `The agent lost its control chat. Restart the server with --reset-owners.` | diff --git a/packages/simplex-chat-mcp/TESTING.md b/packages/simplex-chat-mcp/TESTING.md index 4c76c9b070..3af22f510c 100644 --- a/packages/simplex-chat-mcp/TESTING.md +++ b/packages/simplex-chat-mcp/TESTING.md @@ -64,6 +64,7 @@ The directory by its address (`docs/DIRECTORY.md`): 4. `Check for new messages from the directory, waiting up to 60 seconds.` `receive` with `wait`. 5. `List your chats and pending actions.` `list`. 6. Reject one card with its `/reject @N A`: the call returns `status: rejected`; the card ends with `Rejected by Alice.` `/pending` lists the waiting cards. +7. Start a new Claude Code session and ask: `Recall your conversation with the directory.` `receive` with `history`: the last messages of the chat, oldest first, Claude's own with the agent's name and `from_type: agent`. Approval of all messages to a chat, and leaving: diff --git a/packages/simplex-chat-mcp/spec/README.md b/packages/simplex-chat-mcp/spec/README.md index 01d8e2c812..235df831f6 100644 --- a/packages/simplex-chat-mcp/spec/README.md +++ b/packages/simplex-chat-mcp/spec/README.md @@ -184,7 +184,7 @@ graph TD | [`tools.ts`](../src/tools.ts) | tool schemas, descriptions, handlers, connect plans, perform steps, downloads, files to send, chat owners | | [`actions.ts`](../src/actions.ts) | action records, state machine, expiry timers, per-session limits, stop | | [`control.ts`](../src/control.ts) | agent control chat and session groups: link, owners, owner commands, cards, counter | -| [`messages.ts`](../src/messages.ts) | message items and their files, item watch, waits, unread paging, display names, durations | +| [`messages.ts`](../src/messages.ts) | message items and their files, item watch, waits, unread and history paging, display names, durations | | [`core.ts`](../src/core.ts) | one SimpleX core: init, user, network config, temp folder, event buffer, profile update | | [`files.ts`](../src/files.ts) | data folders, lock, token, `headers.json`, `server.json`, session folders, socket path, service log | | [`log.ts`](../src/log.ts) | log lines, error texts, shell quoting | diff --git a/packages/simplex-chat-mcp/spec/api.md b/packages/simplex-chat-mcp/spec/api.md index 1833f4fa72..12fdeec79b 100644 --- a/packages/simplex-chat-mcp/spec/api.md +++ b/packages/simplex-chat-mcp/spec/api.md @@ -204,7 +204,7 @@ The perform fails with `file: PATH changed after the request.` when the file's r ### 1.4 `receive` -Handler: [`AgentTools.receive`](../src/tools.ts). Schemas: input [`receiveSchema`](../src/tools.ts), output [`receiveOutput`](../src/tools.ts). +Handler: [`AgentTools.receive`](../src/tools.ts). History: [`historyMessages`](../src/tools.ts), [`historyItems`](../src/messages.ts). Schemas: input [`receiveSchema`](../src/tools.ts), output [`receiveOutput`](../src/tools.ts). Input: @@ -213,14 +213,16 @@ Input: | `chat` | string | | required | `@N` or `#N` of the agent | | `wait` | number | 0 to 86400 | 0 | seconds to wait when no message is new | | `limit` | integer | 1 to 100 | 50 | most messages returned | +| `history` | integer | 1 to 50 | | most message items returned in `history` | -Output (all fields always present): +Output (`history` only with its input): | Field | Value | |---|---| | `chat` | the chat reference | | `messages` | unread received messages in chat order, then received messages that arrived during the call; live items left out; at most `limit` | | `more` | new messages not returned, overflow, and unread items left unread by the page reads | +| `history` | at most `history` message items: the last ones before the first item of `messages`, or the last ones of the chat when `messages` is empty, in chat order; sent items included; new and live items, and items with `itemDeleted` (deleted, blocked or moderated), left out; read after the wait | Tool errors: `No chat CHAT. list shows the agent's chats.` for an invalid reference, the control chat, or a store error of the first read, `initial` 1 ([`AgentTools.receive`](../src/tools.ts)); other chat errors, a store error of a later page read included, as their error text ([`errorText`, `chatErrorText`](../src/log.ts)). @@ -333,9 +335,9 @@ Tool errors: `No chat CHAT. list shows the agent's chats.` when no action with t |---|---|---|---| | `chat` | string | always | chat reference of the item | | `item` | integer | always | `meta.itemId` | -| `from` | string | always | `groupRcv`: member display name
`directRcv`: contact display name
`channelRcv`: channel display name
sent items in `connect`: the agent's name in that chat | +| `from` | string | always | `groupRcv`: member display name
`directRcv`: contact display name
`channelRcv`: channel display name
sent items in `connect` and in `history` of `receive`: the agent's name in that chat | | `from_member` | integer | `groupRcv` | `groupMemberId` | -| `from_type` | string | when the profile has a peer type | sender's `peerType`; the agent's own for its non-incognito items in `connect` | +| `from_type` | string | when the profile has a peer type | sender's `peerType`; the agent's own for its non-incognito items in `connect` and in `history` of `receive` | | `time` | string | always | `meta.itemTs` | | `text` | string | always | `msgContent.text` | | `file` | object | a received item with a file | below | @@ -366,7 +368,7 @@ Tool errors: `No chat CHAT. list shows the agent's chats.` when no action with t | `path` | `received`: the download path | | `error` | `failed`: the error text ([`fileError`, `fileStatusError`, `fileErrorText`, `srvErrorText`](../src/log.ts)) | -Only received message items (`rcvMsgContent`) are returned by `send` and `receive`; `connect` also returns sent ones (`sndMsgContent`) ([`ChatItemsWatch.collect`](../src/messages.ts), [`AgentTools.connectedChat`](../src/tools.ts)). +Only received message items (`rcvMsgContent`) are returned in `responses` of `send` and in `messages` of `receive`; `connect` and `history` of `receive` also return sent ones (`sndMsgContent`) ([`ChatItemsWatch.collect`, `historyItems`](../src/messages.ts), [`AgentTools.connectedChat`, `historyMessages`](../src/tools.ts)). Command ([`commandsOf`](../src/tools.ts), schema [`commandSchema`](../src/tools.ts)): diff --git a/packages/simplex-chat-mcp/spec/architecture.md b/packages/simplex-chat-mcp/spec/architecture.md index 430b7a879c..738955151f 100644 --- a/packages/simplex-chat-mcp/spec/architecture.md +++ b/packages/simplex-chat-mcp/spec/architecture.md @@ -268,6 +268,7 @@ Hooks are bound in [`startAgent`](../src/serve.ts), where `actions` is created: | `fileOffer`, `fileContent` | file fields of an item; message content of a file | | `getChat`, `receivingFiles`, `markRead` | `apiGetChat` and `apiChatItemsRead` by chat reference; the IDs of a chat's files in status `rcvAccepted`, `rcvTransfer` or `rcvWarning`, paged | | `unreadItems` | unread items of a chat after its `initial` read, paged | +| `historyItems` | message items of a chat before an item, or at its end, paged; new and live items, and items with `itemDeleted`, left out | | `reportProgress`, `nextChange`, `awaitResponses` | waits | | `duration` | a time rounded to whole milliseconds: `41 ms`, `2.0 s`, `42 s`, `4 min 12 s`, `1 h 5 min`, for the step lines and the end line of the plugin | | `validName`, `viewName` | display name rules and `@name` form | @@ -690,9 +691,10 @@ The server writes the tappable form `/'...'` only in the card's command line ([` | `wait` | 0 to 86400 s | [`connectSchema`, `sendSchema`, `receiveSchema`, `downloadSchema`](../src/tools.ts) | | `idle` | 1 to 300 s, default 30 | [`connectSchema`, `sendSchema`, `defaultIdle`](../src/tools.ts) | | `limit` | 1 to 100, default 50 | [`sendSchema`, `receiveSchema`, `defaultLimit`](../src/tools.ts) | +| `receive.history` | 1 to 50 | [`receiveSchema`](../src/tools.ts) | | `connect` snapshot | last 50 items | [`messagesOnConnect`](../src/tools.ts) | | collected items per action or call | 100, then their IDs kept as overflow until deleted | [`maxCollected`, `ChatItemsWatch.collect`](../src/messages.ts) | -| unread page | 100 items | [`pageSize`](../src/messages.ts) | +| unread and history page | 100 items | [`pageSize`](../src/messages.ts) | | chat list read | one read of 1000000 chats | [`maxChats`](../src/tools.ts) | | `download` wait, default | 60 s | [`downloadWait`](../src/tools.ts) | | download check | every 60 s | [`downloadCheck`](../src/tools.ts) | diff --git a/packages/simplex-chat-mcp/spec/flows.md b/packages/simplex-chat-mcp/spec/flows.md index 8c9a968aea..a78500aa59 100644 --- a/packages/simplex-chat-mcp/spec/flows.md +++ b/packages/simplex-chat-mcp/spec/flows.md @@ -287,16 +287,17 @@ sequenceDiagram participant W as ChatItemsWatch participant C as Core participant D as Peer - A->>T: receive {chat: #35;12, wait: 3600, limit: 50} + A->>T: receive {chat: #35;12, wait: 3600, limit: 50, history: 20} T->>W: collect #35;12 into arrived T->>C: apiGetChat #35;12 initial 1 C-->>T: chatStats.unreadCount 0 T-->>A: progress: No new messages in #35;12, waiting until TIME. D->>C: post, item 40 C->>W: newChatItems: arrived + T->>C: apiGetChat #35;12 before 40 count 100 T->>C: apiChatItemsRead #35;12 [40] T->>W: stop collecting - T-->>A: {chat: #35;12, messages: [40], more: 0} + T-->>A: {chat: #35;12, messages: [40], more: 0, history} ``` Notes: @@ -306,8 +307,9 @@ Notes: - `more`: the arrived messages not returned, the overflow and the unread items not read ([`AgentTools.receive`](../src/tools.ts)). - Items received while the pages are read are returned once ([`AgentTools.receive`](../src/tools.ts)). - Exact progress text: `No new messages in CHAT; waiting until TIME.` ([`AgentTools.receive`](../src/tools.ts)). +- With `history`, after the wait the server reads pages of 100 items: `before` the first returned message, or `last` when none is returned, then `before` the first item of the previous page, until it holds `history` message items that are not new or live and have no `itemDeleted`, or a page is short; the agent's own items are named as in `connect` ([`AgentTools.receive`, `historyMessages`](../src/tools.ts), [`historyItems`](../src/messages.ts)). -Source: [`AgentTools.receive`](../src/tools.ts), [`unreadItems`, `isNewMessage`, `reportProgress`, `nextChange`, `awaitResponses`](../src/messages.ts). +Source: [`AgentTools.receive`, `historyMessages`](../src/tools.ts), [`unreadItems`, `isNewMessage`, `historyItems`, `reportProgress`, `nextChange`, `awaitResponses`](../src/messages.ts). --- diff --git a/packages/simplex-chat-mcp/src/messages.ts b/packages/simplex-chat-mcp/src/messages.ts index 37adc8898c..8eb09810a1 100644 --- a/packages/simplex-chat-mcp/src/messages.ts +++ b/packages/simplex-chat-mcp/src/messages.ts @@ -370,6 +370,17 @@ function isNewMessage(item: T.ChatItem): boolean { return item.content.type === "rcvMsgContent" && isNew(item) && !isLive(item) } +// spec: spec/architecture.md#messages-historyitems +export async function historyItems(chat: api.ChatApi, ref: string, before: number | undefined, count: number): Promise { + const items: T.ChatItem[] = [] + for (let pagination: T.ChatPagination = before === undefined ? {type: "last", count: pageSize} : {type: "before", chatItemId: before, count: pageSize}; ; ) { + const page: T.ChatItem[] = (await getChat(chat, ref, pagination)).chatItems + items.unshift(...page.filter(item => isMessageItem(item) && !isNew(item) && !isLive(item) && item.meta.itemDeleted === undefined)) + if (items.length >= count || page.length < pageSize) return items.slice(-count) + pagination = {type: "before", chatItemId: page[0].meta.itemId, count: pageSize} + } +} + // spec: spec/architecture.md#messages-reportprogress export function reportProgress(call: ToolCall, message: () => string): () => void { call.progress(message()) diff --git a/packages/simplex-chat-mcp/src/tools.ts b/packages/simplex-chat-mcp/src/tools.ts index 318eb2a995..1fbf811042 100644 --- a/packages/simplex-chat-mcp/src/tools.ts +++ b/packages/simplex-chat-mcp/src/tools.ts @@ -26,6 +26,7 @@ import { fileOffer, filePaths, getChat, + historyItems, isChatRef, isLive, isMessageItem, @@ -70,6 +71,7 @@ export interface ReceiveInput { chat: string wait?: number limit?: number + history?: number } // spec: spec/architecture.md#tools-inputs @@ -312,6 +314,7 @@ const receiveSchema: Schema = { chat: {type: "string", description: "Chat reference from connect or list: @N or #N."}, wait: {type: "number", minimum: 0, maximum: 86400, description: "Seconds to wait for a new message when none is unread. Default 0."}, limit: {type: "integer", minimum: 1, maximum: 100, description: "Most messages returned. Default 50; the rest stay unread."}, + history: {type: "integer", minimum: 1, maximum: 50, description: "Number of messages returned in history: the last ones before the new messages, yours included."}, }, required: ["chat"], additionalProperties: false, @@ -382,6 +385,7 @@ const receiveOutput: Schema = { chat: {type: "string", description: "Chat reference."}, messages: {type: "array", items: messageSchema, description: "New messages: the unread ones, then those that arrived during the call."}, more: {type: "integer", description: "New messages not returned; call receive again for them."}, + history: {type: "array", items: messageSchema, description: "With the input history: the last messages of the chat before the new ones, oldest first, yours included; not marked read."}, }, required: ["chat", "messages", "more"], } @@ -467,7 +471,8 @@ Send bot commands as text, for example /help. When a message has a file with sta // spec: spec/architecture.md#tools-instructions const receiveDescription = `Returns the new messages of a chat: the unread ones, then those that arrive during the call. With wait, it waits up to wait seconds when no message is new. -The returned messages are marked read; more counts the new ones not returned. It needs no approval. When a message has a file with status offered, call download when your user's task needs it.` +The returned messages are marked read; more counts the new ones not returned. It needs no approval. When a message has a file with status offered, call download when your user's task needs it. +With history N, it also returns the last N messages of the chat before the new ones, yours included, not marked read; at the start of a session, and after your context was compacted, call receive with history to recall the conversation.` // spec: spec/architecture.md#tools-instructions const downloadDescription = `Downloads the file of a received message to this computer and returns its full path. @@ -1344,7 +1349,7 @@ export class AgentTools { // spec: spec/api.md#tool-receive private async receive(input: ReceiveInput, call: ToolCall): Promise { - const {chat, wait = 0, limit = defaultLimit} = input + const {chat, wait = 0, limit = defaultLimit, history} = input if (!isChatRef(chat) || chat === this.agent.controlChat()) throw unknownChat(chat) const arrived = new Collected() const stop = this.agent.watch.collect(chat, arrived) @@ -1371,15 +1376,22 @@ export class AgentTools { } } const returned = fresh().slice(0, limit) + const recalled = history === undefined ? undefined : await this.historyMessages(chat, chatInfo, returned[0]?.chatItem.meta.itemId, history) if (call.signal.aborted) return undefined await markRead(this.agent.chat, chat, [...returned.map(({chatItem}) => chatItem.meta.itemId), ...skipped]) if (call.signal.aborted) return undefined - return {chat, messages: await this.toMessages(returned), more: arrived.items.length - returned.length + arrived.overflow.size + unreadRest} + return {chat, messages: await this.toMessages(returned), more: arrived.items.length - returned.length + arrived.overflow.size + unreadRest, ...defined({history: recalled})} } finally { stop() } } + // spec: spec/api.md#tool-receive + private async historyMessages(chat: string, chatInfo: T.ChatInfo, before: number | undefined, count: number): Promise { + const items = await historyItems(this.agent.chat, chat, before, count) + return this.toMessages(items.map(chatItem => ({chatInfo, chatItem}))) + } + // spec: spec/api.md#tool-list private async listChats(): Promise { const chats: object[] = [] diff --git a/packages/simplex-chat-mcp/test/unit/http.test.ts b/packages/simplex-chat-mcp/test/unit/http.test.ts index a8808223de..b9deb28c45 100644 --- a/packages/simplex-chat-mcp/test/unit/http.test.ts +++ b/packages/simplex-chat-mcp/test/unit/http.test.ts @@ -165,6 +165,8 @@ describe("MCP", () => { expect(await text({chat: "@4", text: "x", wait: -1})).toMatch(/data\/wait must be >= 0$/) expect(await text({chat: "@4", text: "x", colour: "red"})).toMatch(/data must NOT have additional properties$/) expect(await text({text: "x"})).toMatch(/data must have required property 'chat'$/) + const {result} = await body(await post(modern("tools/call", {name: "receive", arguments: {chat: "@4", history: 51}}), modernHeaders("tools/call", "receive"))) + expect(result).toMatchObject({isError: true, content: [{type: "text", text: "Input validation error: Invalid arguments for tool receive: data/history must be <= 50"}]}) expect(actions.all()).toHaveLength(0) }) diff --git a/packages/simplex-chat-mcp/test/unit/messages.test.ts b/packages/simplex-chat-mcp/test/unit/messages.test.ts index 9a1b56b8ce..0f0b278337 100644 --- a/packages/simplex-chat-mcp/test/unit/messages.test.ts +++ b/packages/simplex-chat-mcp/test/unit/messages.test.ts @@ -424,6 +424,107 @@ describe("receive", () => { expect(second).toMatchObject({messages: [{item: 23}], more: 0}) }) + it("returns as history the last messages before the new ones, oldest first, yours under your name, without live, deleted and other items, and marks only the new ones read", async () => { + const chat = new FakeChat() + const fromSwitchback: T.CIDirection = {type: "groupRcv", groupMember: member(44, "Switchback")} + const read = {status: "rcvRead"} + const connected = {...item(12, "connected", fromSwitchback, read), content: {type: "rcvGroupEvent", rcvGroupEvent: {type: "memberConnected"}}} as unknown as T.ChatItem + const deleted = item(13, "removed", fromSwitchback, read) + deleted.meta.itemDeleted = {type: "deleted", chatType: T.ChatType.Group} + const items = [ + item(9, "hello", fromSwitchback, read), + item(10, "trail map?", fromSwitchback, read), + item(11, "here it is", {type: "groupSnd"}), + connected, + deleted, + item(14, "Ridge", fromSwitchback, {...read, live: true}), + item(15, "anything else?", {type: "groupSnd"}), + item(16, "size 44?", fromSwitchback), + item(17, "map updated", {type: "groupSnd"}), + item(18, "and 45?", fromSwitchback), + item(19, "and 46?", fromSwitchback), + ] + chat.chats.set("#15", {chatInfo: groupChat(group(15, "Trail", member(1, "agent"))), items}) + const {tools} = agentTools(chat) + const result = (await tools.call("receive", {chat: "#15", limit: 2, history: 3}, signal().call))!.structuredContent as {messages: {item: number}[]; more: number; history: object[]} + expect(result.messages.map(({item}) => item)).toEqual([16, 18]) + expect(result.more).toBe(1) + const sent = {chat: "#15", from: "agent", from_type: "agent", time: "2026-10-17T10:00:00Z", new: false, mentions_me: false} + expect(result.history).toEqual([ + {chat: "#15", item: 10, from: "Switchback", from_member: 44, time: "2026-10-17T10:00:00Z", text: "trail map?", new: false, mentions_me: false}, + {...sent, item: 11, text: "here it is"}, + {...sent, item: 15, text: "anything else?"}, + ]) + expect(chat.commands.filter(cmd => cmd.startsWith("/_read"))).toEqual(["/_read chat items #15 16,18"]) + }) + + it("returns as history the latest messages when none is new, and no history without the input", async () => { + const chat = new FakeChat() + chat.chats.set("@4", {chatInfo: direct(contact(4, "Switchback")), items: [item(10, "hi", {type: "directRcv"}, {status: "rcvRead"}), item(11, "hello", {type: "directSnd"})]}) + const {tools} = agentTools(chat) + expect((await tools.call("receive", {chat: "@4", history: 50}, signal().call))!.structuredContent).toEqual({ + chat: "@4", + messages: [], + more: 0, + history: [ + {chat: "@4", item: 10, from: "Switchback", time: "2026-10-17T10:00:00Z", text: "hi", new: false, mentions_me: false}, + {chat: "@4", item: 11, from: "agent", from_type: "agent", time: "2026-10-17T10:00:00Z", text: "hello", new: false, mentions_me: false}, + ], + }) + expect((await tools.call("receive", {chat: "@4"}, signal().call))!.structuredContent).not.toHaveProperty("history") + expect(chat.commands.filter(cmd => cmd.startsWith("/_read"))).toEqual([]) + }) + + it("reads history when the call returns, after the wait", async () => { + const chat = new FakeChat() + chat.chats.set("@4", {chatInfo: direct(contact(4, "Switchback")), items: [item(10, "hi", {type: "directRcv"}, {status: "rcvRead"}), item(11, "hello", {type: "directSnd"})]}) + const {tools, watch} = agentTools(chat) + const {call, progress} = signal() + const receiving = tools.call("receive", {chat: "@4", wait: 30, history: 2}, call) + await settled() + expect(progress[0]).toMatch(/^No new messages in @4; waiting until /) + watch.deliver([chat.addItem("@4", item(12, "still there?", {type: "directSnd"})), chat.addItem("@4", item(13, "yes", {type: "directRcv"}))]) + const result = (await receiving)!.structuredContent as {messages: {item: number}[]; history: {item: number}[]} + expect(result.messages.map(({item}) => item)).toEqual([13]) + expect(result.history.map(({item}) => item)).toEqual([11, 12]) + }) + + it("leaves out of history a new message whose event has not arrived, and the next call returns it", async () => { + const chat = new FakeChat() + chat.chats.set("@4", {chatInfo: direct(contact(4, "Switchback")), items: [item(10, "hi", {type: "directRcv"}, {status: "rcvRead"}), item(11, "hello", {type: "directSnd"})]}) + const {tools, watch} = agentTools(chat) + const receiving = tools.call("receive", {chat: "@4", wait: 30, history: 5}, signal().call) + await settled() + chat.addItem("@4", item(12, "still there?", {type: "directRcv"})) + watch.deliver([chat.addItem("@4", item(13, "hello?", {type: "directRcv"}))]) + const result = (await receiving)!.structuredContent as {messages: {item: number}[]; history: {item: number}[]} + expect(result.messages.map(({item}) => item)).toEqual([13]) + expect(result.history.map(({item}) => item)).toEqual([10, 11]) + const next = (await tools.call("receive", {chat: "@4"}, signal().call))!.structuredContent as {messages: {item: number}[]} + expect(next.messages.map(({item}) => item)).toEqual([12]) + }) + + it("reads history in pages of 100 items, before the first new message or from the end, until it holds the messages", async () => { + const chat = new FakeChat() + const undecrypted = Array.from({length: 150}, (_, i) => ({...item(10 + i, "", {type: "directRcv"}, {status: "rcvRead"}), content: {type: "rcvDecryptionError"}}) as unknown as T.ChatItem) + const items = [item(1, "hi", {type: "directRcv"}, {status: "rcvRead"}), item(2, "hello", {type: "directSnd"}), ...undecrypted, item(160, "still there?", {type: "directSnd"}), item(161, "yes", {type: "directRcv"})] + chat.chats.set("@4", {chatInfo: direct(contact(4, "Switchback")), items}) + const {tools} = agentTools(chat) + const first = (await tools.call("receive", {chat: "@4", history: 3}, signal().call))!.structuredContent as {history: {item: number}[]} + expect(first.history.map(({item}) => item)).toEqual([1, 2, 160]) + const second = (await tools.call("receive", {chat: "@4", history: 1}, signal().call))!.structuredContent as {history: {item: number}[]} + expect(second.history.map(({item}) => item)).toEqual([161]) + expect(chat.commands.filter(cmd => /^\/_get chat @4 (count|before)=/.test(cmd))).toEqual(["/_get chat @4 before=161 count=100", "/_get chat @4 before=61 count=100", "/_get chat @4 count=100"]) + }) + + it("returns your messages in history under your incognito name", async () => { + const chat = new FakeChat() + chat.chats.set("#15", {chatInfo: groupChat(group(15, "Trail", {...member(1, "Quiet Fox"), memberContactProfileId: 99})), items: [item(11, "here it is", {type: "groupSnd"})]}) + const {tools} = agentTools(chat) + const result = (await tools.call("receive", {chat: "#15", history: 1}, signal().call))!.structuredContent as {history: object[]} + expect(result.history).toEqual([{chat: "#15", item: 11, from: "Quiet Fox", time: "2026-10-17T10:00:00Z", text: "here it is", new: false, mentions_me: false}]) + }) + it("names the agent in a quote of its own message by its name in the chat, the incognito name included", async () => { const chat = new FakeChat() const incognito = {...contact(4, "Ridgeline"), activeConn: {connId: 204, connStatus: {type: "ready"}, customUserProfileId: 77}} as unknown as T.Contact diff --git a/plans/2026-10-19-mcp-server.md b/plans/2026-10-19-mcp-server.md index 94a80058a1..0c18f2d64b 100644 --- a/plans/2026-10-19-mcp-server.md +++ b/plans/2026-10-19-mcp-server.md @@ -1,6 +1,6 @@ # SimpleX MCP server 0.2: plan -Status: draft · 2026-10-17, files and leave 2026-10-30 (`plans/2026-10-30-mcp-files-and-leave.md`) · person-facing manual: `REFERENCE.md`, the plugin in short in `README.md`. Code references: master `139ce5f8c` (`/code/simplex-chat-6`), unless marked `9711dcfc9` (core 7.1.0.11); `simplex-chat` 7.1.0-beta.10.2 loads core 7.1.0.20. Pending decisions: section Open. +Status: draft · 2026-10-17, files and leave 2026-10-30 (`plans/2026-10-30-mcp-files-and-leave.md`), history 2026-11-12 (`plans/2026-11-12-mcp-history.md`) · person-facing manual: `REFERENCE.md`, the plugin in short in `README.md`. Code references: master `139ce5f8c` (`/code/simplex-chat-6`), unless marked `9711dcfc9` (core 7.1.0.11); `simplex-chat` 7.1.0-beta.10.2 loads core 7.1.0.20. Pending decisions: section Open. ## Scope @@ -705,6 +705,7 @@ input field type rule chat string required; a chat of the agent wait number optional; seconds to wait when no message is new; 0 to 86400; default 0 limit number optional; 1 to 100; default 50 +history number optional; 1 to 50; most message items returned in history ``` ``` @@ -712,6 +713,7 @@ result field type present chat string always messages Message[] always; the new messages, up to limit: the unread ones in chat order, then those that arrive during the call more number always; new messages not returned +history Message[] with history; up to history message items: the last ones before the first of messages, or the last ones of the chat when messages is empty, in chat order; sent items included; new and live items, and items with itemDeleted (deleted, blocked or moderated), left out ``` - New: a received message that is unread when the call reads its page, or that arrives during the call. The returned ones are marked read; another call marking one read after this call collected it does not remove it. @@ -1360,8 +1362,11 @@ receive(input, ctx): none new and wait > 0: wait for newChatItems of chat until one is new | wait | signal progress at once and every 60 s: "No new messages in ; waiting until