@honu-office/mcp 0.0.0-stage → 0.2.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.
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `convert` — turn a document into another format.
3
+ *
4
+ * Conversion is asynchronous and produces a downloadable artifact. This tool
5
+ * follows the job to completion and reports where the result can be fetched;
6
+ * it deliberately does NOT write the file to disk. An MCP server writing to the
7
+ * user's filesystem on its own initiative is a surprise, and the caller is
8
+ * better placed to choose the destination.
9
+ */
10
+
11
+ import { unwrap } from '../http.js';
12
+ import { pollUntilDone, readStatus } from '../poll.js';
13
+ import { readDocument } from '../files.js';
14
+
15
+ /**
16
+ * List the conversions HonuOffice supports.
17
+ *
18
+ * `/api/conversion/formats` is unauthenticated, so this works before a key is
19
+ * proven good — useful when the answer to "why did my conversion fail" is that
20
+ * the pair was never supported.
21
+ *
22
+ * @param {{client: import('../http.js').ApiClient}} context - Injected dependencies.
23
+ * @returns {Promise<unknown>} The supported formats.
24
+ */
25
+ export async function listFormats(context) {
26
+ return unwrap(await context.client.request('/api/conversion/formats', { auth: false }));
27
+ }
28
+
29
+ /**
30
+ * Convert a document.
31
+ *
32
+ * @param {{client: import('../http.js').ApiClient, timeoutMs: number}} context - Injected dependencies.
33
+ * @param {{file: string, to: string, wait?: boolean}} input - Tool input.
34
+ * @param {{sleep?: (ms: number) => Promise<void>}} [testHooks] - Injectable timing for tests.
35
+ * @returns {Promise<object>} A structured result.
36
+ */
37
+ export async function convert(context, input, testHooks = {}) {
38
+ const { client, timeoutMs } = context;
39
+ const { file, to, wait = true } = input;
40
+
41
+ if (!file) throw new Error('`file` is required — a path to the document on this machine.');
42
+ if (!to) throw new Error('`to` is required — the target format, e.g. "word", "html", "text".');
43
+
44
+ const document = await readDocument(file);
45
+ const target = String(to).toLowerCase();
46
+
47
+ const started = unwrap(
48
+ await client.upload('/api/conversion/convert', document, { outputFormat: target })
49
+ );
50
+
51
+ const jobId = started?.jobId || started?.id;
52
+ if (!jobId) {
53
+ // Some conversions answer synchronously with the artifact reference rather
54
+ // than a job. Treat that as success instead of inventing a failure.
55
+ return {
56
+ status: 'completed',
57
+ source: document.path,
58
+ to: target,
59
+ message: 'Conversion completed.',
60
+ raw: started,
61
+ };
62
+ }
63
+
64
+ if (!wait) {
65
+ return { status: 'started', source: document.path, to: target, jobId, message: `Conversion started. Poll job ${jobId}.` };
66
+ }
67
+
68
+ const { outcome, state } = await pollUntilDone(
69
+ async () => unwrap(await client.request(`/api/jobs/${jobId}`)),
70
+ { timeoutMs, sleep: testHooks.sleep }
71
+ );
72
+
73
+ if (outcome === 'timeout') {
74
+ return {
75
+ status: 'timeout',
76
+ source: document.path,
77
+ to: target,
78
+ jobId,
79
+ lastStatus: readStatus(state),
80
+ message: `Still converting after ${Math.round(timeoutMs / 1000)}s. The job is not lost — ask again for job ${jobId}.`,
81
+ };
82
+ }
83
+ if (outcome === 'failed') {
84
+ return { status: 'failed', source: document.path, to: target, jobId, message: state?.error || 'Conversion failed.', raw: state };
85
+ }
86
+
87
+ return {
88
+ status: 'completed',
89
+ source: document.path,
90
+ to: target,
91
+ jobId,
92
+ downloadPath: `/api/conversion/download/${jobId}`,
93
+ message:
94
+ `Converted. Download it from ${client.baseUrl}/api/conversion/download/${jobId} ` +
95
+ 'with the X-API-Key header.',
96
+ };
97
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `discover` — find documents across a site.
3
+ *
4
+ * A crawl is long-running by nature and can legitimately take much longer than
5
+ * an analysis, so this tool does not wait for completion by default. Blocking
6
+ * an agent for an hour is worse than handing back a job id it can check.
7
+ *
8
+ * `action` keeps one tool covering the whole lifecycle — start, check, list —
9
+ * rather than three near-identical tools an agent has to choose between.
10
+ */
11
+
12
+ import { unwrap } from '../http.js';
13
+
14
+ /**
15
+ * Start, inspect or list a discovery job.
16
+ *
17
+ * @param {{client: import('../http.js').ApiClient}} context - Injected dependencies.
18
+ * @param {{action?: string, url?: string, jobId?: string, maxDepth?: number, maxPages?: number, limit?: number}} input - Tool input.
19
+ * @returns {Promise<object>} A structured result.
20
+ */
21
+ export async function discover(context, input) {
22
+ const { client } = context;
23
+ const action = (input.action || (input.jobId ? 'status' : 'start')).toLowerCase();
24
+
25
+ switch (action) {
26
+ case 'start': {
27
+ if (!input.url) throw new Error('`url` is required to start a discovery crawl.');
28
+ const body = { url: input.url };
29
+ if (input.maxDepth !== undefined) body.maxDepth = input.maxDepth;
30
+ if (input.maxPages !== undefined) body.maxPages = input.maxPages;
31
+
32
+ const job = unwrap(await client.request('/api/discovery/jobs', { method: 'POST', body }));
33
+ const jobId = job?.jobId || job?.id;
34
+ return {
35
+ status: 'started',
36
+ jobId,
37
+ url: input.url,
38
+ message: jobId
39
+ ? `Crawl started as job ${jobId}. Check it with action "status", and list what it found with action "documents".`
40
+ : 'Crawl started, but HonuOffice returned no job id.',
41
+ raw: jobId ? undefined : job,
42
+ };
43
+ }
44
+
45
+ case 'status': {
46
+ const jobId = requireJobId(input, 'status');
47
+ const job = unwrap(await client.request(`/api/discovery/jobs/${jobId}`));
48
+ return {
49
+ status: 'ok',
50
+ jobId,
51
+ jobStatus: job?.status,
52
+ progress: job?.progress,
53
+ found: job?.pdfCount ?? job?.documentsFound ?? job?.totalPdfs,
54
+ raw: job,
55
+ };
56
+ }
57
+
58
+ case 'documents': {
59
+ const jobId = requireJobId(input, 'documents');
60
+ const limit = input.limit ?? 50;
61
+ const body = await client.request(`/api/discovery/jobs/${jobId}/pdfs`, { query: { limit } });
62
+ const documents = unwrap(body);
63
+ const list = Array.isArray(documents) ? documents : documents?.items || documents?.pdfs || [];
64
+ return {
65
+ status: 'ok',
66
+ jobId,
67
+ count: list.length,
68
+ total: body?.meta?.pagination?.total,
69
+ documents: list.slice(0, limit).map((item) => ({
70
+ id: item.id ?? item.pdfId,
71
+ url: item.url,
72
+ title: item.title,
73
+ size: item.size ?? item.fileSize,
74
+ })),
75
+ };
76
+ }
77
+
78
+ case 'list': {
79
+ const body = await client.request('/api/discovery/jobs', { query: { limit: input.limit ?? 20 } });
80
+ const jobs = unwrap(body);
81
+ const list = Array.isArray(jobs) ? jobs : jobs?.items || jobs?.jobs || [];
82
+ return {
83
+ status: 'ok',
84
+ count: list.length,
85
+ jobs: list.map((job) => ({
86
+ jobId: job.jobId ?? job.id,
87
+ url: job.url ?? job.startUrl,
88
+ jobStatus: job.status,
89
+ createdAt: job.createdAt,
90
+ })),
91
+ };
92
+ }
93
+
94
+ default:
95
+ throw new Error(`Unknown action "${input.action}". Use start, status, documents or list.`);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Require a job id, with a message that names the action needing it.
101
+ *
102
+ * @param {{jobId?: string}} input - Tool input.
103
+ * @param {string} action - The action being attempted.
104
+ * @returns {string} The job id.
105
+ */
106
+ function requireJobId(input, action) {
107
+ if (!input.jobId) throw new Error(`\`jobId\` is required for action "${action}".`);
108
+ return input.jobId;
109
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * `remediate` — submit a document to be fixed, and track the request.
3
+ *
4
+ * Remediation is the one operation here that is not purely computational: a
5
+ * request can be priced, queued and worked on over hours or days. So this tool
6
+ * submits and reports, and never blocks waiting for a human process to finish.
7
+ *
8
+ * It accepts the three starting points the API offers — a local file, a URL, or
9
+ * an existing analysis report — because "remediate what you just analyzed"
10
+ * is the common follow-up and re-uploading the file for it is wasteful.
11
+ */
12
+
13
+ import { unwrap } from '../http.js';
14
+ import { readDocument } from '../files.js';
15
+
16
+ /**
17
+ * Submit or track a remediation request.
18
+ *
19
+ * @param {{client: import('../http.js').ApiClient}} context - Injected dependencies.
20
+ * @param {{action?: string, file?: string, url?: string, reportId?: string, requestId?: string, notes?: string, limit?: number}} input - Tool input.
21
+ * @returns {Promise<object>} A structured result.
22
+ */
23
+ export async function remediate(context, input) {
24
+ const { client } = context;
25
+ const action = (input.action || (input.requestId ? 'status' : 'submit')).toLowerCase();
26
+
27
+ switch (action) {
28
+ case 'submit': {
29
+ const sources = [input.file, input.url, input.reportId].filter(Boolean);
30
+ if (sources.length === 0) {
31
+ throw new Error('Give one of `file` (a path on this machine), `url`, or `reportId` from a previous analysis.');
32
+ }
33
+ if (sources.length > 1) {
34
+ throw new Error('Give exactly one of `file`, `url` or `reportId`.');
35
+ }
36
+
37
+ let created;
38
+ let subject;
39
+ if (input.file) {
40
+ const document = await readDocument(input.file);
41
+ subject = document.path;
42
+ created = unwrap(
43
+ await client.upload('/api/remediation', document, { notes: input.notes })
44
+ );
45
+ } else if (input.url) {
46
+ subject = input.url;
47
+ created = unwrap(
48
+ await client.request('/api/remediation/from-url', {
49
+ method: 'POST',
50
+ body: { url: input.url, notes: input.notes },
51
+ })
52
+ );
53
+ } else {
54
+ subject = `report ${input.reportId}`;
55
+ created = unwrap(
56
+ await client.request('/api/remediation/from-report', {
57
+ method: 'POST',
58
+ body: { reportId: input.reportId, notes: input.notes },
59
+ })
60
+ );
61
+ }
62
+
63
+ const requestId = created?.requestId ?? created?.id;
64
+ return {
65
+ status: 'submitted',
66
+ subject,
67
+ requestId,
68
+ requestStatus: created?.status,
69
+ quote: readQuote(created),
70
+ message: requestId
71
+ ? `Remediation request ${requestId} created. Check it with action "status".`
72
+ : 'Request created, but HonuOffice returned no request id.',
73
+ raw: requestId ? undefined : created,
74
+ };
75
+ }
76
+
77
+ case 'status': {
78
+ if (!input.requestId) throw new Error('`requestId` is required for action "status".');
79
+ const request = unwrap(await client.request(`/api/remediation/${input.requestId}`));
80
+ return {
81
+ status: 'ok',
82
+ requestId: input.requestId,
83
+ requestStatus: request?.status,
84
+ quote: readQuote(request),
85
+ createdAt: request?.createdAt,
86
+ completedAt: request?.completedAt,
87
+ downloads:
88
+ String(request?.status).toLowerCase() === 'completed'
89
+ ? {
90
+ original: `/api/remediation/${input.requestId}/download/original`,
91
+ remediated: `/api/remediation/${input.requestId}/download/remediated`,
92
+ }
93
+ : undefined,
94
+ raw: request,
95
+ };
96
+ }
97
+
98
+ case 'list': {
99
+ const body = await client.request('/api/remediation/my-requests', {
100
+ query: { limit: input.limit ?? 20 },
101
+ });
102
+ const payload = unwrap(body);
103
+ const list = Array.isArray(payload) ? payload : payload?.items || payload?.requests || [];
104
+ return {
105
+ status: 'ok',
106
+ count: list.length,
107
+ requests: list.map((request) => ({
108
+ requestId: request.requestId ?? request.id,
109
+ filename: request.filename,
110
+ requestStatus: request.status,
111
+ createdAt: request.createdAt,
112
+ })),
113
+ };
114
+ }
115
+
116
+ default:
117
+ throw new Error(`Unknown action "${input.action}". Use submit, status or list.`);
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Pull out pricing, which is the thing a user most wants to see before
123
+ * committing — and which has been wrong before: a missing rate card once made
124
+ * every quote read $0.00 (api#433). Reporting the figure as the API gives it,
125
+ * and saying nothing when there is none, beats implying a free job.
126
+ *
127
+ * @param {unknown} payload - A remediation request payload.
128
+ * @returns {object|undefined} The quote, when present.
129
+ */
130
+ function readQuote(payload) {
131
+ const quote = payload?.quote ?? payload?.pricing ?? payload;
132
+ const amount = quote?.totalAmount ?? quote?.total ?? quote?.amount;
133
+ if (amount === undefined || amount === null) return undefined;
134
+ return {
135
+ totalAmount: amount,
136
+ currency: quote?.currency,
137
+ unitLabel: quote?.unitLabel,
138
+ ratePerUnit: quote?.ratePerUnit,
139
+ };
140
+ }