@abraca/mcp 2.88.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,147 +0,0 @@
1
- /**
2
- * tool-detail — central enrichment of abracadabra MCP tool cards.
3
- *
4
- * Built-in Claude tools (Bash/Read/Edit/…) flow through the hook-bridge, which
5
- * attaches an expandable `detail` (command text, file path, diff) that the
6
- * cou-sh chat renders as a click-to-expand block. abracadabra's own MCP tools
7
- * are explicitly skipped by the hook-bridge and only ever emitted a bare
8
- * name+target pill — so their cards had nothing to expand ("no idea what docs
9
- * it sees or what the tree was").
10
- *
11
- * `wrapToolsWithDetail` patches `McpServer.tool` ONCE, before any tool is
12
- * registered, so every tool invocation records an expandable detail onto its
13
- * tool-history entry (via `server.recordToolDetail`). The detail leads with the
14
- * human-readable title + id of any document the call referenced (resolved from
15
- * the live tree), then the remaining arguments, then the text the tool returned
16
- * (e.g. the full document tree for `get_document_tree`). The pill itself is
17
- * still emitted by each tool's own `setActiveToolCall`; this only fills in the
18
- * expandable detail afterwards.
19
- */
20
- import { toPlain } from "@abraca/dabra";
21
- import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
22
- import type { AbracadabraMCPServer } from "./server.ts";
23
-
24
- /** Per-field cap (chars) — keeps the awareness payload bounded. Mirrors the
25
- * hook-bridge's DETAIL_MAX so built-in and MCP tool cards behave alike. */
26
- const DETAIL_MAX = 4000;
27
-
28
- /** Argument keys that hold a document id, in the order we surface them. */
29
- const DOC_ID_KEYS = [
30
- "docId",
31
- "id",
32
- "rootId",
33
- "parentId",
34
- "newParentId",
35
- "uploadId",
36
- ] as const;
37
-
38
- function cap(s: string): string {
39
- return s.length > DETAIL_MAX ? `${s.slice(0, DETAIL_MAX)}\n… (truncated)` : s;
40
- }
41
-
42
- function safeJson(value: unknown): string {
43
- try {
44
- return JSON.stringify(value);
45
- } catch {
46
- return String(value);
47
- }
48
- }
49
-
50
- /** Pull the joined text content out of a tool result, if any. */
51
- function resultText(result: unknown): string {
52
- const content = (result as { content?: unknown })?.content;
53
- if (!Array.isArray(content)) return "";
54
- return content
55
- .filter((c) => c && (c as { type?: string }).type === "text")
56
- .map((c) => (c as { text?: string }).text ?? "")
57
- .join("\n")
58
- .trim();
59
- }
60
-
61
- /**
62
- * Build the expandable detail shown when a tool card is clicked:
63
- * 1. one `id — "Title"` line per document the args referenced (title resolved
64
- * from the live tree when available),
65
- * 2. the remaining arguments as compact JSON,
66
- * 3. the text the tool returned (document tree, content, confirmation, …).
67
- * Rendered by cou-sh's ChatActionCard as a `kind: "text"` block.
68
- */
69
- export function buildToolDetail(
70
- toolArgs: unknown,
71
- result: unknown,
72
- resolveLabel?: (id: string) => string | undefined,
73
- ): { kind: "text"; text: string } {
74
- const lines: string[] = [];
75
- const rest: Record<string, unknown> =
76
- toolArgs && typeof toolArgs === "object"
77
- ? { ...(toolArgs as Record<string, unknown>) }
78
- : {};
79
-
80
- // Headline: each referenced doc as "id — title" (title when resolvable).
81
- for (const key of DOC_ID_KEYS) {
82
- const v = rest[key];
83
- if (typeof v === "string" && v.length > 0) {
84
- const label = resolveLabel?.(v);
85
- lines.push(label ? `${key}: ${v} — "${label}"` : `${key}: ${v}`);
86
- delete rest[key];
87
- }
88
- }
89
-
90
- // Remaining arguments (depth, type, label, meta, content, query, …).
91
- const restStr = Object.keys(rest).length > 0 ? safeJson(rest) : "";
92
- if (restStr && restStr !== "{}") lines.push(`args: ${restStr}`);
93
- if (lines.length === 0) lines.push("args: (no arguments)");
94
-
95
- const text = resultText(result);
96
- if (text) {
97
- lines.push("");
98
- lines.push(text);
99
- }
100
- return { kind: "text", text: cap(lines.join("\n")) };
101
- }
102
-
103
- /**
104
- * Monkey-patch `mcp.tool` so each registered tool's handler is wrapped to record
105
- * arguments + result detail after it resolves. Call once at startup, before the
106
- * register* functions run. Errors in detail-recording are swallowed — they must
107
- * never break the underlying tool.
108
- */
109
- export function wrapToolsWithDetail(
110
- mcp: McpServer,
111
- server: AbracadabraMCPServer,
112
- ): void {
113
- // Resolve a document id to its current label from the live tree, if loaded.
114
- const resolveLabel = (id: string): string | undefined => {
115
- try {
116
- const raw = server.getTreeMap()?.get(id);
117
- if (!raw) return undefined;
118
- const label = (toPlain(raw) as { label?: unknown })?.label;
119
- return typeof label === "string" && label.length > 0 ? label : undefined;
120
- } catch {
121
- return undefined;
122
- }
123
- };
124
-
125
- const original = mcp.tool.bind(mcp) as (...args: unknown[]) => unknown;
126
- (mcp as { tool: unknown }).tool = (...args: unknown[]) => {
127
- const name = args[0];
128
- const cbIndex = args.length - 1;
129
- const cb = args[cbIndex];
130
- if (typeof name === "string" && typeof cb === "function") {
131
- const handler = cb as (...a: unknown[]) => unknown;
132
- args[cbIndex] = async (...handlerArgs: unknown[]) => {
133
- const result = await handler(...handlerArgs);
134
- try {
135
- server.recordToolDetail(
136
- name,
137
- buildToolDetail(handlerArgs[0], result, resolveLabel),
138
- );
139
- } catch {
140
- /* detail recording must never break a tool */
141
- }
142
- return result;
143
- };
144
- }
145
- return original(...args);
146
- };
147
- }
@@ -1,159 +0,0 @@
1
- /**
2
- * Awareness tools — read/write presence state.
3
- */
4
- import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
5
- import { z } from 'zod'
6
- import { awarenessStatesToArray } from '@abraca/dabra'
7
- import { yjsToMarkdown } from '../converters/yjsToMarkdown.ts'
8
- import type { AbracadabraMCPServer } from '../server.ts'
9
-
10
- export function registerAwarenessTools(mcp: McpServer, server: AbracadabraMCPServer) {
11
- mcp.tool(
12
- 'set_presence',
13
- 'Set the AI agent\'s presence state. Use this to indicate which document you are viewing or your current status.',
14
- {
15
- docId: z.string().optional().describe('Document ID the agent is currently viewing. Sets docId in root awareness.'),
16
- status: z.string().optional().describe('Status text (e.g. "writing", "reviewing", "thinking").'),
17
- },
18
- async ({ docId, status }) => {
19
- const rootProvider = server.rootYProvider
20
- if (!rootProvider) return { content: [{ type: 'text', text: 'Not connected' }] }
21
-
22
- if (docId !== undefined) {
23
- rootProvider.awareness.setLocalStateField('docId', docId)
24
- }
25
- if (status !== undefined) {
26
- rootProvider.awareness.setLocalStateField('status', status)
27
- }
28
-
29
- return { content: [{ type: 'text', text: 'Presence updated' }] }
30
- }
31
- )
32
-
33
- mcp.tool(
34
- 'set_doc_awareness',
35
- 'Set renderer-specific awareness fields on a child document. Use this to broadcast item-level presence (e.g. which kanban card, table cell, or slide you are interacting with). Setting a field to null clears it.',
36
- {
37
- docId: z.string().describe('Document ID to set awareness on.'),
38
- fields: z.record(z.string(), z.unknown()).describe('Key-value pairs to set on the child document\'s awareness state. Use namespaced keys like "kanban:hovering", "table:editing", "slides:viewing", "outline:editing", "calendar:focused", "gallery:focused", "timeline:focused", "graph:focused", "map:focused", "doc:scroll". Set a key to null to clear it.'),
39
- },
40
- async ({ docId, fields }) => {
41
- server.setActiveToolCall({ name: 'set_doc_awareness', target: docId })
42
- try {
43
- const provider = await server.getChildProvider(docId)
44
- for (const [key, value] of Object.entries(fields)) {
45
- provider.awareness.setLocalStateField(key, value ?? null)
46
- }
47
- return { content: [{ type: 'text', text: 'Doc awareness updated' }] }
48
- } catch (error: any) {
49
- return {
50
- content: [{ type: 'text', text: `Error: ${error.message}` }],
51
- isError: true,
52
- }
53
- }
54
- }
55
- )
56
-
57
- mcp.tool(
58
- 'poll_inbox',
59
- 'Check the "AI Inbox" document for pending instructions from humans. Returns the inbox content and any pending task sub-documents. Create the inbox as a doc called "AI Inbox" under the hub doc if it does not exist yet. Note: channel-based watching via watch_chat is preferred for real-time use.',
60
- {},
61
- async () => {
62
- server.setActiveToolCall({ name: 'poll_inbox' })
63
- try {
64
- const treeMap = server.getTreeMap()
65
- const rootDocId = server.rootDocId
66
- if (!treeMap || !rootDocId) {
67
- return { content: [{ type: 'text', text: 'Not connected' }] }
68
- }
69
-
70
- // Find "AI Inbox" doc that is a direct child of the hub doc
71
- let inboxId: string | null = null
72
- treeMap.forEach((value: any, id: string) => {
73
- if (
74
- value.parentId === rootDocId &&
75
- typeof value.label === 'string' &&
76
- value.label.toLowerCase() === 'ai inbox'
77
- ) {
78
- inboxId = id
79
- }
80
- })
81
-
82
- if (!inboxId) {
83
- return {
84
- content: [{
85
- type: 'text',
86
- text: JSON.stringify({
87
- pending: [],
88
- message: 'No AI Inbox document found. Create one under the hub doc with label "AI Inbox".',
89
- }),
90
- }],
91
- }
92
- }
93
-
94
- const resolvedInboxId: string = inboxId
95
- const provider = await server.getChildProvider(resolvedInboxId)
96
- const fragment = provider.document.getXmlFragment('default')
97
- const markdown = yjsToMarkdown(fragment, 'AI Inbox')
98
-
99
- // Collect direct children of inbox (pending task sub-docs)
100
- const pendingTasks: Array<{ id: string; label: string }> = []
101
- treeMap.forEach((value: any, id: string) => {
102
- if (value.parentId === resolvedInboxId) {
103
- pendingTasks.push({ id, label: value.label || 'Untitled' })
104
- }
105
- })
106
-
107
- return {
108
- content: [{
109
- type: 'text',
110
- text: JSON.stringify({ inboxId: resolvedInboxId, content: markdown, pendingTasks }, null, 2),
111
- }],
112
- }
113
- } catch (error: any) {
114
- return {
115
- content: [{ type: 'text', text: `Error: ${error.message}` }],
116
- isError: true,
117
- }
118
- }
119
- }
120
- )
121
-
122
- mcp.tool(
123
- 'list_connected_users',
124
- 'List all connected users and their awareness state. Shows who is online and what they are doing.',
125
- {
126
- docId: z.string().optional().describe('If provided, list users connected to this specific document. Otherwise lists users from root awareness.'),
127
- },
128
- async ({ docId }) => {
129
- server.setActiveToolCall({ name: 'list_connected_users', target: docId })
130
- try {
131
- let awareness
132
- if (docId) {
133
- const provider = await server.getChildProvider(docId)
134
- awareness = provider.awareness
135
- } else {
136
- const rootProvider = server.rootYProvider
137
- if (!rootProvider) return { content: [{ type: 'text', text: 'Not connected' }] }
138
- awareness = rootProvider.awareness
139
- }
140
-
141
- const states = awarenessStatesToArray(awareness.getStates())
142
- // Filter out empty states
143
- const users = states.filter(s => s.user)
144
-
145
- return {
146
- content: [{
147
- type: 'text',
148
- text: JSON.stringify(users, null, 2),
149
- }],
150
- }
151
- } catch (error: any) {
152
- return {
153
- content: [{ type: 'text', text: `Error: ${error.message}` }],
154
- isError: true,
155
- }
156
- }
157
- }
158
- )
159
- }
@@ -1,155 +0,0 @@
1
- /**
2
- * Channel tools — reply to channel events and send chat messages.
3
- */
4
-
5
- import { makeEntryMap } from "@abraca/dabra";
6
- import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
- import { z } from "zod";
8
- import { populateYDocFromMarkdown } from "../converters/markdownToYjs.ts";
9
- import type { AbracadabraMCPServer } from "../server.ts";
10
-
11
- export function registerChannelTools(
12
- mcp: McpServer,
13
- server: AbracadabraMCPServer,
14
- ) {
15
- mcp.tool(
16
- "reply",
17
- "Create a document reply. Creates a child document under doc_id with the reply content as a rich-text document. Use this for structured, persistent responses. For conversational chat, use send_chat_message instead.",
18
- {
19
- doc_id: z.string().describe("Document ID to create the reply under."),
20
- text: z.string().describe("Markdown content for the reply."),
21
- task_id: z
22
- .string()
23
- .optional()
24
- .describe(
25
- "If replying to an ai:task, the task ID to clear from awareness.",
26
- ),
27
- },
28
- async ({ doc_id, text, task_id }) => {
29
- try {
30
- server.setAutoStatus("writing", doc_id);
31
- server.setActiveToolCall({ name: "reply", target: doc_id });
32
-
33
- const treeMap = server.getTreeMap();
34
- const rootDoc = server.rootDocument;
35
- if (!treeMap || !rootDoc) {
36
- return {
37
- content: [{ type: "text" as const, text: "Not connected" }],
38
- isError: true,
39
- };
40
- }
41
-
42
- const timestamp = new Date()
43
- .toISOString()
44
- .replace("T", " ")
45
- .slice(0, 19);
46
- const snippet = text.slice(0, 40).replace(/\n/g, " ");
47
- const label = `AI Reply — ${timestamp}: ${snippet}`;
48
- const replyId = crypto.randomUUID();
49
- const now = Date.now();
50
-
51
- rootDoc.transact(() => {
52
- treeMap.set(
53
- replyId,
54
- makeEntryMap({
55
- label,
56
- parentId: doc_id,
57
- order: now,
58
- type: "doc",
59
- createdAt: now,
60
- updatedAt: now,
61
- }),
62
- );
63
- });
64
-
65
- const replyProvider = await server.getChildProvider(replyId);
66
- const fragment = replyProvider.document.getXmlFragment("default");
67
- populateYDocFromMarkdown(fragment, text);
68
-
69
- if (task_id) {
70
- server.clearAiTask(task_id);
71
- }
72
-
73
- return {
74
- content: [
75
- {
76
- type: "text" as const,
77
- text: JSON.stringify({ replyDocId: replyId, parentId: doc_id }),
78
- },
79
- ],
80
- };
81
- } catch (error: any) {
82
- return {
83
- content: [{ type: "text" as const, text: `Error: ${error.message}` }],
84
- isError: true,
85
- };
86
- }
87
- },
88
- );
89
-
90
- mcp.tool(
91
- "send_chat_message",
92
- 'Send a chat message visible in the dashboard chat UI. Pass channel_doc_id — the UUID of a doc with kind "channel" (group chat under a Space) or "dm" (direct message). Use list_connected_users + the doc tree to discover channels.',
93
- {
94
- channel_doc_id: z
95
- .string()
96
- .describe('Channel doc UUID (kind = "channel" or "dm")'),
97
- text: z.string().describe("Message text"),
98
- },
99
- async ({ channel_doc_id, text }) => {
100
- try {
101
- const rootProvider = server.rootYProvider;
102
- if (!rootProvider) {
103
- return {
104
- content: [{ type: "text" as const, text: "Not connected" }],
105
- isError: true,
106
- };
107
- }
108
-
109
- // Normalize literal escape sequences. Some LLM outputs emit the
110
- // 2-char `\n` / `\t` / `\r` instead of the real control chars, which
111
- // then render literally in the chat (markdown renderer can't see a
112
- // newline where there is just "\n"). Convert them back to real chars.
113
- const normalized = text
114
- .replace(/\\r\\n/g, "\n")
115
- .replace(/\\n/g, "\n")
116
- .replace(/\\t/g, "\t")
117
- .replace(/\\r/g, "\n");
118
-
119
- // Show a brief "writing" phase so the dashboard renders typing dots
120
- // just before the message lands (the reasoning phase showed the
121
- // incantation; this is the distinct compose/send phase). Clear any
122
- // tool pill, mark status 'writing' (the dashboard maps this to typing
123
- // dots, not the phrase), emit a typing frame, and pause briefly so
124
- // the dots are actually visible before the bubble appears.
125
- server.setActiveToolCall(null);
126
- server.setWritingStatus(channel_doc_id);
127
- await new Promise((r) => setTimeout(r, 650));
128
-
129
- rootProvider.sendStateless(
130
- JSON.stringify({
131
- type: "messages:send",
132
- channel_doc_id,
133
- content: normalized,
134
- mentions: [],
135
- }),
136
- );
137
-
138
- // End the turn AFTER the send: clears status, tool pill, turn id and
139
- // stops the typing heartbeat so nothing lingers after the reply.
140
- server.setAutoStatus(null);
141
-
142
- return {
143
- content: [
144
- { type: "text" as const, text: `Sent to ${channel_doc_id}` },
145
- ],
146
- };
147
- } catch (error: any) {
148
- return {
149
- content: [{ type: "text" as const, text: `Error: ${error.message}` }],
150
- isError: true,
151
- };
152
- }
153
- },
154
- );
155
- }