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>
This commit is contained in:
brenzi-agentandbrenzi-agent authored and GitHub committed 2026-11-21 12:36:56 +00:00
1 parent 9abdf30ec5
commit d6e6e99b60
12 files changed
+236 -18

No files matched your search

+4 -1
View File
@@ -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 <folder> (PID N). If no server runs, remove <folder>/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.` |
+1
View File
@@ -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:
+1 -1
View File
@@ -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 |
+7 -5
View File
@@ -204,7 +204,7 @@ The perform fails with `file: PATH changed after the request.` when the file's r
### 1.4 `receive`
<a id="tool-receive"></a>Handler: [`AgentTools.receive`](../src/tools.ts). Schemas: input [`receiveSchema`](../src/tools.ts), output [`receiveOutput`](../src/tools.ts).
<a id="tool-receive"></a>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<br>`directRcv`: contact display name<br>`channelRcv`: channel display name<br>sent items in `connect`: the agent's name in that chat |
| `from` | string | always | `groupRcv`: member display name<br>`directRcv`: contact display name<br>`channelRcv`: channel display name<br>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)).
<a id="command-object"></a>Command ([`commandsOf`](../src/tools.ts), schema [`commandSchema`](../src/tools.ts)):
@@ -268,6 +268,7 @@ Hooks are bound in [`startAgent`](../src/serve.ts), where `actions` is created:
| <a id="messages-fileoffer"></a>`fileOffer`, `fileContent` | file fields of an item; message content of a file |
| <a id="messages-getchat"></a>`getChat`, `receivingFiles`, `markRead` | `apiGetChat` and `apiChatItemsRead` by chat reference; the IDs of a chat's files in status `rcvAccepted`, `rcvTransfer` or `rcvWarning`, paged |
| <a id="messages-unreaditems"></a>`unreadItems` | unread items of a chat after its `initial` read, paged |
| <a id="messages-historyitems"></a>`historyItems` | message items of a chat before an item, or at its end, paged; new and live items, and items with `itemDeleted`, left out |
| <a id="messages-reportprogress"></a>`reportProgress`, `nextChange`, `awaitResponses` | waits |
| <a id="messages-duration"></a>`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 |
| <a id="messages-validname"></a>`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) |
+5 -3
View File
@@ -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).
---
+11
View File
@@ -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<T.ChatItem[]> {
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())
+15 -3
View File
@@ -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<object | undefined> {
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<Message[]> {
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<object> {
const chats: object[] = []
@@ -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)
})
@@ -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
+13 -4
View File
@@ -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 <chat>; waiting until <time>."
messages: new, up to limit; more = the rest + s.chatStats.unreadCount - the rcvNew items of pages (the unread items not read, at least 0)
history given: history pages = /_get chat <chat> before=<the first item ID of messages> count=100, or count=100 when messages is empty,
then before=<the first item ID of the last page> count=100, while they hold fewer than history message items that are not rcvNew or live and have no itemDeleted, and the last page holds 100
history = the last history of those items, in chat order; the agent's own items named as in connect
not aborted: /_read chat items <chat> <the IDs of messages and of skipped, joined by ",">, when that list is non-empty
result {chat, messages, more}
result {chat, messages, more, history when given}
list():
/_get chats <user> pcc=off count=1000000 # parser Commands.hs:6342; count= is ORDER BY chat_ts DESC LIMIT without a time boundary, Store/Messages.hs:884, :995
@@ -1565,8 +1570,8 @@ options defaults, ranges, --stop-wait from 0 to 60, NAME, --display-name at
commands /approve [CHAT] N, /reject [CHAT] N, another chat, /approve CHAT all, /revoke, /pending, /list, unknown, multi-line, non-command text, a number from an earlier run; /list of 100 chats with cut lines and the older count; chat references over 15 digits; names with line breaks and escape sequences; a listed owner by the name on one line; the restart command as code; card size at 15000 bytes, with the current approvers' longest name; a connect refused for its message, its link texts cut to fit; mode host without approvals, /approve CHAT all refused; the wait at stop with cancelled cards, skipped without them, and ended by a second signal; /receive CHAT N all and /receive CHAT off beside the approval of messages; /approve of a download and /receive or /forward of other actions refused; /forward with its reply and failure, the file outside the chat's folder; download cards with the preview, resized to fit 15000 bytes; a refused file posted and logged; an image send card with its preview
actions every transition; attach rule; open counts; counter written before the card; a failed counter write or card post logged; stop edits pending and performing cards, aborts the performs' signal, and an interrupted perform logs no line; standing approval: performed at once, outcome card posted; 20 pending; 20 performing; decided actions deleted after expires
cards every card form and outcome; quoting; names and errors on one line; "as myself" and "incognito"; "where I am incognito"; leave forms; standing form; link texts cut to the bytes left; the reply quote cut by characters; download forms with sizes and the servers line; the attaching line of sends
messages message fields; responses with idle and wait; overflow IDs removed at deletion; receive with new messages under a concurrent call, stopping at limit + 1, a store error of a page read as its error; leave of @N and #N, pending membership included; approved in list; all chats in one read; an approval whose approver is no longer one; a group-role failure; a send to an unconnected contact or group refused; reply_to of an item other than a message refused; mentions of equal names refused; the connect wait cap; the connect wait ended by the stop; the file field of each file status and rejected, a forwarded file offered and then received; download: attach, performing at wait, a received file, a forwarded file kept outside the chat's folder and moved there at the approval, failures by events, a files approval, the wait for the file description and its end at wait, unknown servers without passwords and of disabled operators; send with file: the type and preview by extension, the resized copy deleted at sndFileCompleteXFTP and after a failed send, the fixed preview when the core can't resize or ffmpeg is absent, ffmpeg and ffprobe output, refused paths with symbolic links, a file changed after the request
http 401 without token; 403 with another Origin; 404 for other paths and for a request target that is not a URL, the server serving on; 503 with Retry-After until ready; SDK validation errors
messages message fields; responses with idle and wait; overflow IDs removed at deletion; receive with new messages under a concurrent call, stopping at limit + 1, a store error of a page read as its error; receive with history: its items in order before the returned new ones or at the end, read in pages after the wait, the agent's own under its name or incognito name, new, live and deleted items left out, none marked read, absent without the input; leave of @N and #N, pending membership included; approved in list; all chats in one read; an approval whose approver is no longer one; a group-role failure; a send to an unconnected contact or group refused; reply_to of an item other than a message refused; mentions of equal names refused; the connect wait cap; the connect wait ended by the stop; the file field of each file status and rejected, a forwarded file offered and then received; download: attach, performing at wait, a received file, a forwarded file kept outside the chat's folder and moved there at the approval, failures by events, a files approval, the wait for the file description and its end at wait, unknown servers without passwords and of disabled operators; send with file: the type and preview by extension, the resized copy deleted at sndFileCompleteXFTP and after a failed send, the fixed preview when the core can't resize or ffmpeg is absent, ffmpeg and ffprobe output, refused paths with symbolic links, a file changed after the request
http 401 without token; 403 with another Origin; 404 for other paths and for a request target that is not a URL, the server serving on; 503 with Retry-After until ready; SDK validation errors, receive with history 51 included
register entry JSON with headersHelper and no token; timeout from server.json; remove before add; errors; on Windows, claude through cmd.exe after ENOENT, with cmd.exe quoting
files lock: exclusive create, a running PID, a stale PID; folder mode at every start; headers.json; file modes set again on existing files
log every SimpleX error shape worded by the apps, in its JSON shape from @simplex-chat/types; the chain for other errors
@@ -1634,3 +1639,7 @@ C6 Claude Code closes the request stream when a call times out or its task
## Decisions of 2026-10-31
- The wait at stop is fixed for now: `--stop-wait` seconds, 10 by default, when cards were edited or posted at the stop; a second signal ends it. It replaces the count of pending deliveries read with `/sql`. A later change can post a final message and wait for its "sent" status for each owner.
## Decisions of 2026-11-12
- `receive` takes `history`, 1 to 50: the last message items of the chat before the new ones, the agent's own included and named as in `connect`; new and live items, and items with `itemDeleted`, are left out, and history items are not marked read (`plans/2026-11-12-mcp-history.md`).
+73
View File
@@ -0,0 +1,73 @@
# SimpleX MCP server, the next version: receive with history
Status: draft for review. Decided on 2026-11-12: history in `receive`, at most 50 messages. Code references: master `953389322`.
## Decisions
1. `receive` takes `history`, an integer from 1 to 50.
2. With it, the result has `history`: the last message items of the chat before the first item of `messages`, or the last ones when `messages` is empty, in chat order.
3. Message items are received and sent messages (`rcvMsgContent`, `sndMsgContent`); new and live items, and items with `itemDeleted` (deleted, blocked or moderated), are left out.
4. The agent's own items are named as in `connect`: its name in the chat; `from_type` only outside incognito chats.
5. History items are not marked read and do not change `more`.
6. History is read when the call returns, after any wait, before the returned messages are marked read.
## receive
Input:
```
field value
history integer from 1 to 50; optional
```
Output:
```
field value
history Message[]; only with the input
```
`historyItems(chat, ref, before, count)`:
```
pagination = before=<before> count=100, or count=100 without before
loop:
page = /_get chat <ref> <pagination>
items = the message items of page that are not rcvNew or live and have no itemDeleted, then items
items holds at least count, or page holds fewer than 100: return the last count of items
pagination = before=<the first item ID of page> count=100
```
Changes:
```
file function change
messages.ts historyItems new
tools.ts ReceiveInput history
receiveSchema history
receiveOutput history
receiveDescription one sentence on history
receive history read after the wait, before markRead; in the result only with the input
historyMessages new: historyItems, toMessages
```
## Tests
```
file test
test/unit/messages.test.ts items in order before the returned new ones; own ones under the agent's name; live, deleted and other items left out; only the new ones marked read
the latest items when none is new; no history without the input
history read after the wait
a new item whose event has not arrived left out of history; the next call returns it
pages of 100 items before the first new message, and from the end
own items under the incognito name
test/unit/http.test.ts history 51 refused by the schema
```
Docs:
```
file change
REFERENCE.md receive with history; the agent recalls the conversation in a new session; a recovery row for a lost session
TESTING.md a step: history in a new session
plans/2026-10-19-mcp-server.md receive input and result; receive steps; tests; decisions of 2026-11-12
spec/api.md 1.4: history input and output; 1.8: from, from_type and sent items
spec/architecture.md historyItems; limits
spec/flows.md 5: history in the diagram and the notes
spec/README.md the role of messages.ts
```