diff --git a/CHANGELOG.md b/CHANGELOG.md index 47582fb0d..c3d5684c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,11 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Packages without a separate changelog are covered by the cross-package notes below. -## [Unreleased] +## [Unreleased - Minor] + +### Added + +- `@relaycast/mcp` adds `message.dm.history` so an agent can page through a DM conversation without marking messages as read. ## [12.13.1] - 2026-11-20 diff --git a/docs/repository-guide.md b/docs/repository-guide.md index 13ac052ea..e5a00ccb3 100644 --- a/docs/repository-guide.md +++ b/docs/repository-guide.md @@ -593,6 +593,8 @@ Local stdio config: } ``` +Use `message.dm.list` to find a conversation ID, then call `message.dm.history` with that `conversation_id` to read the newest messages without marking them as read. Pass the same `workspace_id`, `workspace_alias` or `as` you used with `message.dm.list`; that agent must be a participant. The default page size is 20 messages and the maximum is 100. Pass `next_before` as `before` to fetch the next older page. A null cursor means the history is exhausted. + ## CLI Use the same command surface as the MCP tools from a terminal: diff --git a/packages/mcp/src/__tests__/integration.test.ts b/packages/mcp/src/__tests__/integration.test.ts index 39502b8e4..337854524 100644 --- a/packages/mcp/src/__tests__/integration.test.ts +++ b/packages/mcp/src/__tests__/integration.test.ts @@ -18,6 +18,7 @@ describe('MCP → SDK → HTTP integration', () => { let client: Client; let captured: CapturedRequest[]; let invalidAgentTokens: Set; + let dmMessages: Array<{ id: string; text: string }>; let originalFetch: typeof global.fetch; function lastReq(): CapturedRequest { @@ -31,6 +32,7 @@ describe('MCP → SDK → HTTP integration', () => { beforeEach(async () => { captured = []; invalidAgentTokens = new Set(); + dmMessages = []; originalFetch = global.fetch; global.fetch = vi.fn(async (url: string | URL, init?: RequestInit) => { @@ -121,6 +123,16 @@ describe('MCP → SDK → HTTP integration', () => { participants: [{ agent_id: 'a1' }, { agent_id: 'a2' }], created_at: new Date().toISOString(), }; + } else if (path === '/v1/dm/forbidden/messages' && req.method === 'GET') { + return Response.json({ + ok: false, + error: { code: 'forbidden', message: 'Not a participant in this conversation' }, + }, { status: 403 }); + } else if (path === '/v1/dm/conv1/messages' && req.method === 'GET') { + const { searchParams } = new URL(req.url); + const before = searchParams.get('before'); + const limit = Number(searchParams.get('limit') ?? 50); + data = dmMessages.filter((message) => before === null || message.id < before).slice(0, limit); } else if (path.includes('/dm/conv1/messages')) { data = { id: 'dm_msg_1', conversation_id: 'conv1', text: (req.body as Record)?.text }; } else if (path.includes('/reactions') && req.method === 'POST') { @@ -473,6 +485,97 @@ describe('MCP → SDK → HTTP integration', () => { expect(req!.url).toContain('limit=25'); }); + it('message.dm.history forwards the cursor and limit and returns the oldest ID when more messages exist', async () => { + dmMessages = Array.from({ length: 102 }, (_, index) => ({ + id: String(102 - index).padStart(3, '0'), + text: 'Direct message', + })); + const result = await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv1', before: '102', limit: 100 }, + }); + + const expected = { messages: dmMessages.slice(1, 101), next_before: '002' }; + expect(result.isError).toBeFalsy(); + expect(result.structuredContent).toEqual(expected); + expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(expected, null, 2) }]); + // Only history GETs use the current agent token; there is no mark-read call. + expect(captured.map(({ url, method, headers }) => [new URL(url).pathname, method, headers.authorization])) + .toEqual([ + ['/v1/dm/conv1/messages', 'GET', 'Bearer at_test_integration'], + ['/v1/dm/conv1/messages', 'GET', 'Bearer at_test_integration'], + ]); + expect(Object.fromEntries(new URL(captured[0].url).searchParams)).toEqual({ before: '102', limit: '100' }); + expect(Object.fromEntries(new URL(captured[1].url).searchParams)).toEqual({ before: '002', limit: '1' }); + + const nextPage = await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv1', before: expected.next_before, limit: 100 }, + }); + expect(nextPage.structuredContent).toEqual({ messages: dmMessages.slice(101), next_before: null }); + }); + + it('message.dm.history defaults to 20 and returns a null cursor for an empty page', async () => { + const result = await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv1' }, + }); + + expect(result.structuredContent).toEqual({ messages: [], next_before: null }); + expect(captured).toHaveLength(1); + expect(Object.fromEntries(new URL(lastReq().url).searchParams)).toEqual({ limit: '21' }); + }); + + it('message.dm.history uses the extra fetched message as the cursor signal without a second request', async () => { + dmMessages = [{ id: '003', text: 'Newest' }, { id: '002', text: 'Middle' }, { id: '001', text: 'Oldest' }]; + const result = await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv1', limit: 2 }, + }); + + expect(result.structuredContent).toEqual({ messages: dmMessages.slice(0, 2), next_before: '002' }); + expect(captured).toHaveLength(1); + expect(Object.fromEntries(new URL(lastReq().url).searchParams)).toEqual({ limit: '3' }); + }); + + it('message.dm.history returns a null cursor when the final page is full', async () => { + dmMessages = [{ id: '002', text: 'Newer' }, { id: '001', text: 'Older' }]; + const result = await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv1', limit: 2 }, + }); + + expect(result.structuredContent).toEqual({ messages: dmMessages, next_before: null }); + expect(captured).toHaveLength(1); + expect(Object.fromEntries(new URL(lastReq().url).searchParams)).toEqual({ limit: '3' }); + }); + + it.each([ + { limit: 101 }, + { token: 'other-token' }, + ])('message.dm.history rejects unsupported arguments %j without calling the API', async (args) => { + const result = await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv1', ...args }, + }); + + expect(result.isError).toBe(true); + expect(captured).toHaveLength(0); + }); + + it('message.dm.history reports a 403 without returning message content', async () => { + const result = await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'forbidden' }, + }); + + expect(result.isError).toBe(true); + expect(result.structuredContent).toBeUndefined(); + expect(result.content).toEqual([{ type: 'text', text: 'Not a participant in this conversation' }]); + expect(captured).toHaveLength(1); + expect(lastReq().method).toBe('GET'); + }); + it('message.dm.send_group → POST /v1/dm/group then POST /v1/dm/:id/messages', async () => { await client.callTool({ name: 'message.dm.send_group', arguments: { participants: ['A', 'B'], text: 'Hello' } }); const createReq = findReq((r) => r.url.includes('/dm/group')); diff --git a/packages/mcp/src/__tests__/messaging-tools.test.ts b/packages/mcp/src/__tests__/messaging-tools.test.ts index bf82a3736..8833bc3da 100644 --- a/packages/mcp/src/__tests__/messaging-tools.test.ts +++ b/packages/mcp/src/__tests__/messaging-tools.test.ts @@ -15,6 +15,7 @@ describe('messaging tools', () => { dm: vi.fn(), dms: { conversations: vi.fn(), + messages: vi.fn(), createGroup: vi.fn(), sendMessage: vi.fn(), }, @@ -149,6 +150,7 @@ describe('messaging tools with workspace routing and identity overrides', () => dm: vi.fn(), dms: { conversations: vi.fn(), + messages: vi.fn(), createGroup: vi.fn(), sendMessage: vi.fn(), }, @@ -161,6 +163,7 @@ describe('messaging tools with workspace routing and identity overrides', () => dm: vi.fn(), dms: { conversations: vi.fn(), + messages: vi.fn(), createGroup: vi.fn(), sendMessage: vi.fn(), }, @@ -173,6 +176,7 @@ describe('messaging tools with workspace routing and identity overrides', () => dm: vi.fn(), dms: { conversations: vi.fn(), + messages: vi.fn(), createGroup: vi.fn(), sendMessage: vi.fn(), }, @@ -252,6 +256,25 @@ describe('messaging tools with workspace routing and identity overrides', () => expect(identityClient.dms.conversations).toHaveBeenCalled(); }); + it('message.dm.history routes workspace and identity like message.dm.list', async () => { + routedClient.dms.messages.mockResolvedValue([{ id: '001' }]); + await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv_beta', workspace_alias: 'beta' }, + }); + expect(getAgentClient).toHaveBeenCalledWith({ workspace_id: undefined, workspace_alias: 'beta' }, undefined); + expect(routedClient.dms.messages).toHaveBeenCalledWith('conv_beta', { before: undefined, limit: 21 }); + + identityClient.dms.messages.mockResolvedValue([]); + await client.callTool({ + name: 'message.dm.history', + arguments: { conversation_id: 'conv_writer', as: 'WriterBot' }, + }); + expect(getAgentClient).toHaveBeenCalledWith(undefined, 'WriterBot'); + expect(identityClient.dms.messages).toHaveBeenCalledWith('conv_writer', { before: undefined, limit: 21 }); + expect(defaultClient.dms.messages).not.toHaveBeenCalled(); + }); + it('message.dm.send_group with workspace_alias and as routes to identity-scoped client', async () => { identityClient.dms.createGroup.mockResolvedValue({ id: 'conv1' }); identityClient.dms.sendMessage.mockResolvedValue({ id: 'msg1' }); diff --git a/packages/mcp/src/__tests__/server.test.ts b/packages/mcp/src/__tests__/server.test.ts index 47e4cfd25..5d031cadc 100644 --- a/packages/mcp/src/__tests__/server.test.ts +++ b/packages/mcp/src/__tests__/server.test.ts @@ -189,9 +189,9 @@ describe('createRelayMcpServer', () => { .not.toContain('message.file.download'); }); - it('lists all 48 tools', async () => { + it('lists all 49 tools', async () => { const tools = await client.listTools(); - expect(tools.tools.length).toBe(48); + expect(tools.tools.length).toBe(49); const toolNames = tools.tools.map((t) => t.name).sort(); expect(toolNames).toEqual([ 'agent.add', @@ -220,6 +220,7 @@ describe('createRelayMcpServer', () => { 'integration.webhook.delete', 'integration.webhook.list', 'integration.webhook.trigger', + 'message.dm.history', 'message.dm.list', 'message.dm.send', 'message.dm.send_group', diff --git a/packages/mcp/src/piggyback.ts b/packages/mcp/src/piggyback.ts index 1fc01a8fe..a01ee4f87 100644 --- a/packages/mcp/src/piggyback.ts +++ b/packages/mcp/src/piggyback.ts @@ -5,6 +5,7 @@ import type { McpTelemetry } from './telemetry.js'; const SKIP_PIGGYBACK = new Set([ 'message.inbox.check', + 'message.dm.history', 'workspace.create', 'workspace.set_key', 'workspace.join', diff --git a/packages/mcp/src/tools/messaging.ts b/packages/mcp/src/tools/messaging.ts index a245f6702..74f3ac409 100644 --- a/packages/mcp/src/tools/messaging.ts +++ b/packages/mcp/src/tools/messaging.ts @@ -10,6 +10,9 @@ import { /** Workspace routing arg type extracted from tool input. */ type WsRouting = { workspace_id?: string; workspace_alias?: string }; +/** Server-side cap on DM message page size. */ +const DM_HISTORY_MAX_LIMIT = 100; + /** Passthrough object schema for dynamic API responses. */ const jsonResult = z.object({}).passthrough(); @@ -162,6 +165,45 @@ export function registerMessagingTools( }; }); + server.registerTool('message.dm.history', { + title: 'Get DM History', + description: 'Retrieve direct messages in reverse chronological order for a conversation the current agent participates in. Get the conversation ID from message.dm.list (pass the same workspace_id, workspace_alias or as) and pass next_before back as before to read older messages. This does not mark messages as read.', + inputSchema: z.strictObject({ + conversation_id: z.string().min(1).describe('ID of the direct message conversation'), + before: z.string().min(1).optional().describe('Message ID cursor — return only messages older than this ID'), + limit: z.number().int().positive().max(DM_HISTORY_MAX_LIMIT).default(20).describe('Maximum number of messages per page (default 20, maximum 100)'), + ...workspaceRoutingInputShape, + ...identityOverrideInputShape, + }), + outputSchema: { + messages: z.array(jsonResult).describe('Array of direct messages, newest first'), + next_before: z.string().nullable().describe('Cursor for the next older page, or null when there are no more messages'), + }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }, + }, async ({ conversation_id, before, limit, workspace_id, workspace_alias, as: asIdentity }) => { + const client = getAgentClient(workspaceRefFromArgs({ workspace_id, workspace_alias }), asIdentity); + // Fetch one extra message to learn whether an older page exists. The API + // caps pages at 100, so a full 100-message page still needs a lookahead. + const fetchLimit = Math.min(limit + 1, DM_HISTORY_MAX_LIMIT); + const fetched = await client.dms.messages(conversation_id, { before, limit: fetchLimit }); + const messages = fetched.slice(0, limit); + const oldest = messages.at(-1); + let nextBefore: string | null = null; + + if (oldest && fetched.length > limit) { + nextBefore = oldest.id; + } else if (oldest && fetchLimit === limit && fetched.length === limit) { + const older = await client.dms.messages(conversation_id, { before: oldest.id, limit: 1 }); + if (older.length > 0) nextBefore = oldest.id; + } + + const result = { messages, next_before: nextBefore }; + return { + content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }], + structuredContent: result, + }; + }); + server.registerTool('message.dm.send_group', { title: 'Send Group DM', description: 'Create a new group direct message conversation with multiple agents. Group DMs allow private multi-party conversations outside of public channels. Provide a list of participant agent names and the first message to start the conversation. Optionally give the group a descriptive name.',