@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.
- package/LICENSE +21 -0
- package/README.md +203 -2
- package/package.json +58 -4
- package/src/config.js +214 -0
- package/src/files.js +108 -0
- package/src/http.js +238 -0
- package/src/index.js +33 -0
- package/src/poll.js +80 -0
- package/src/server.js +159 -0
- package/src/tools/analyze.js +177 -0
- package/src/tools/convert.js +97 -0
- package/src/tools/discover.js +109 -0
- package/src/tools/remediate.js +140 -0
package/src/http.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single place this server talks to the HonuOffice API.
|
|
3
|
+
*
|
|
4
|
+
* WHY NOT @honu-office/sdk. The SDK already wraps analyze, discovery and
|
|
5
|
+
* remediation, and would be the obvious foundation. It is unpublished --
|
|
6
|
+
* `npm view @honu-office/sdk` returns 404 -- so depending on it would make this
|
|
7
|
+
* server uninstallable. officea11y-ui was broken for everyone this month by
|
|
8
|
+
* exactly that: a pinned dependency on an unpublished package (OA-94). When the
|
|
9
|
+
* SDK is published, swapping to it is a change to this file alone.
|
|
10
|
+
*
|
|
11
|
+
* Auth matches what the SDK's request builder sends: `X-API-Key` for an API
|
|
12
|
+
* key, `Authorization: Bearer` for a JWT. An MCP server uses the key.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The API was reached and answered with a failure. `status` is its HTTP status,
|
|
17
|
+
* and `body` whatever it said. This is a problem with the request or the
|
|
18
|
+
* account.
|
|
19
|
+
*/
|
|
20
|
+
export class ApiError extends Error {
|
|
21
|
+
/**
|
|
22
|
+
* @param {string} message - Human-readable summary.
|
|
23
|
+
* @param {number} status - HTTP status the API returned.
|
|
24
|
+
* @param {unknown} body - Parsed response body, when there was one.
|
|
25
|
+
*/
|
|
26
|
+
constructor(message, status, body) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = 'ApiError';
|
|
29
|
+
this.status = status;
|
|
30
|
+
this.body = body;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The API could not be reached at all, or did not answer in time. This is a
|
|
36
|
+
* network, DNS, TLS or timeout problem -- NOT a rejected request.
|
|
37
|
+
*
|
|
38
|
+
* Kept distinct from ApiError on purpose. "The API said no" and "I could not
|
|
39
|
+
* ask" need different responses from whoever reads the error, and collapsing
|
|
40
|
+
* them is how a scan that never ran gets reported as a scan that passed.
|
|
41
|
+
*/
|
|
42
|
+
export class TransportError extends Error {
|
|
43
|
+
/**
|
|
44
|
+
* @param {string} message - Human-readable summary.
|
|
45
|
+
* @param {Error} [cause] - The underlying failure.
|
|
46
|
+
*/
|
|
47
|
+
constructor(message, cause) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = 'TransportError';
|
|
50
|
+
this.cause = cause;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Thin client over `fetch`. One instance per tool invocation is fine. */
|
|
55
|
+
export class ApiClient {
|
|
56
|
+
/**
|
|
57
|
+
* @param {{apiKey: string, baseUrl: string}} config - Resolved configuration.
|
|
58
|
+
* @param {typeof fetch} [fetchImpl] - Injectable for tests.
|
|
59
|
+
*/
|
|
60
|
+
constructor(config, fetchImpl = globalThis.fetch) {
|
|
61
|
+
this.apiKey = config.apiKey;
|
|
62
|
+
this.baseUrl = config.baseUrl;
|
|
63
|
+
this.fetchImpl = fetchImpl;
|
|
64
|
+
// Node's fetch imposes no usable deadline of its own: a server that accepts
|
|
65
|
+
// the connection and then says nothing leaves the request outstanding --
|
|
66
|
+
// measured at over 25 seconds with no sign of stopping. Every request
|
|
67
|
+
// therefore carries a deadline, because a hung MCP tool is worse than a
|
|
68
|
+
// failed one: the agent waits and the user sees the client freeze.
|
|
69
|
+
this.requestTimeoutMs = config.requestTimeoutMs ?? 60_000;
|
|
70
|
+
// Uploads get longer. A large document on a slow link is ordinary use, and
|
|
71
|
+
// a 60s ceiling would break it rather than protect anything.
|
|
72
|
+
this.uploadTimeoutMs = config.uploadTimeoutMs ?? 300_000;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Perform a request and return the parsed body.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} path - Path beginning with `/api/`.
|
|
79
|
+
* @param {{method?: string, body?: unknown, query?: Record<string, string|number|boolean|undefined>, signal?: AbortSignal, auth?: boolean}} [options] - Request options.
|
|
80
|
+
* @returns {Promise<unknown>} The parsed response body.
|
|
81
|
+
* @throws {ApiError} When the API answers with a non-2xx status.
|
|
82
|
+
* @throws {TransportError} When the API cannot be reached.
|
|
83
|
+
*/
|
|
84
|
+
async request(path, options = {}) {
|
|
85
|
+
const { method = 'GET', body, query, signal, auth = true } = options;
|
|
86
|
+
const timeoutMs = options.timeoutMs ?? this.requestTimeoutMs;
|
|
87
|
+
|
|
88
|
+
const url = new URL(path, this.baseUrl);
|
|
89
|
+
for (const [key, value] of Object.entries(query || {})) {
|
|
90
|
+
if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** @type {Record<string, string>} */
|
|
94
|
+
const headers = { Accept: 'application/json' };
|
|
95
|
+
if (auth) headers['X-API-Key'] = this.apiKey;
|
|
96
|
+
|
|
97
|
+
let payload = body;
|
|
98
|
+
// FormData sets its own multipart Content-Type, complete with the boundary.
|
|
99
|
+
// Setting it by hand here would produce a boundary-less header and the API
|
|
100
|
+
// would reject every upload.
|
|
101
|
+
if (body !== undefined && !(body instanceof FormData)) {
|
|
102
|
+
headers['Content-Type'] = 'application/json';
|
|
103
|
+
payload = JSON.stringify(body);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// A caller-supplied signal is honoured AND the deadline still applies:
|
|
107
|
+
// whichever fires first wins. Replacing the caller's signal would silently
|
|
108
|
+
// drop their ability to cancel.
|
|
109
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
110
|
+
const effectiveSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
111
|
+
|
|
112
|
+
let response;
|
|
113
|
+
try {
|
|
114
|
+
response = await this.fetchImpl(url.toString(), {
|
|
115
|
+
method,
|
|
116
|
+
headers,
|
|
117
|
+
body: payload,
|
|
118
|
+
signal: effectiveSignal,
|
|
119
|
+
});
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error?.name === 'AbortError' || error?.name === 'TimeoutError') {
|
|
122
|
+
// Say which abort it was. Blaming the deadline for a caller's own
|
|
123
|
+
// cancellation would assert something untrue -- and a message that
|
|
124
|
+
// misreports the cause is how time gets spent on the wrong problem.
|
|
125
|
+
throw new TransportError(
|
|
126
|
+
deadline.aborted
|
|
127
|
+
? `Request to ${path} did not complete within ${Math.round(timeoutMs / 1000)}s and was aborted. ` +
|
|
128
|
+
'The API may be unreachable or overloaded.'
|
|
129
|
+
: `Request to ${path} was cancelled before it completed.`,
|
|
130
|
+
error
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
throw new TransportError(
|
|
134
|
+
`Could not reach the HonuOffice API at ${this.baseUrl}: ${error.message}. ` +
|
|
135
|
+
'Check the host is correct and reachable from this machine.',
|
|
136
|
+
error
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const text = await response.text();
|
|
141
|
+
let parsed = null;
|
|
142
|
+
if (text) {
|
|
143
|
+
try {
|
|
144
|
+
parsed = JSON.parse(text);
|
|
145
|
+
} catch {
|
|
146
|
+
// A non-JSON body from a 2xx is a contract break worth surfacing; from
|
|
147
|
+
// an error status it is usually a proxy page, which the message shows.
|
|
148
|
+
parsed = text;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (!response.ok) {
|
|
153
|
+
throw new ApiError(describeFailure(response.status, parsed), response.status, parsed);
|
|
154
|
+
}
|
|
155
|
+
return parsed;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Upload a file as multipart/form-data.
|
|
160
|
+
*
|
|
161
|
+
* @param {string} path - Path beginning with `/api/`.
|
|
162
|
+
* @param {{buffer: Buffer, filename: string}} file - File content and name.
|
|
163
|
+
* @param {Record<string, string|number|boolean|undefined>} [fields] - Extra form fields.
|
|
164
|
+
* @param {{fieldName?: string, signal?: AbortSignal}} [options] - Upload options.
|
|
165
|
+
* @returns {Promise<unknown>} The parsed response body.
|
|
166
|
+
*/
|
|
167
|
+
async upload(path, file, fields = {}, options = {}) {
|
|
168
|
+
const form = new FormData();
|
|
169
|
+
form.append(
|
|
170
|
+
options.fieldName || 'file',
|
|
171
|
+
new Blob([file.buffer]),
|
|
172
|
+
file.filename
|
|
173
|
+
);
|
|
174
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
175
|
+
if (value !== undefined && value !== null) form.append(key, String(value));
|
|
176
|
+
}
|
|
177
|
+
return this.request(path, {
|
|
178
|
+
method: 'POST',
|
|
179
|
+
body: form,
|
|
180
|
+
signal: options.signal,
|
|
181
|
+
timeoutMs: options.timeoutMs ?? this.uploadTimeoutMs,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Turn a status and body into a message that says what to do about it.
|
|
188
|
+
*
|
|
189
|
+
* @param {number} status - HTTP status.
|
|
190
|
+
* @param {unknown} body - Parsed body, if any.
|
|
191
|
+
* @returns {string} The message.
|
|
192
|
+
*/
|
|
193
|
+
function describeFailure(status, body) {
|
|
194
|
+
const detail =
|
|
195
|
+
(body && typeof body === 'object' && (body.error?.message || body.message)) ||
|
|
196
|
+
(typeof body === 'string' && body.slice(0, 200)) ||
|
|
197
|
+
'';
|
|
198
|
+
|
|
199
|
+
if (status === 401 || status === 403) {
|
|
200
|
+
return (
|
|
201
|
+
`HonuOffice rejected the API key (HTTP ${status}${detail ? `: ${detail}` : ''}). ` +
|
|
202
|
+
'Check HONU_OFFICE_API_KEY is a current key for the right account.'
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
if (status === 404) {
|
|
206
|
+
return `Not found (HTTP 404${detail ? `: ${detail}` : ''}).`;
|
|
207
|
+
}
|
|
208
|
+
if (status === 413) {
|
|
209
|
+
return `The document is too large for this account's limit (HTTP 413${detail ? `: ${detail}` : ''}).`;
|
|
210
|
+
}
|
|
211
|
+
if (status === 429) {
|
|
212
|
+
return `Rate limited by HonuOffice (HTTP 429${detail ? `: ${detail}` : ''}). Retry shortly.`;
|
|
213
|
+
}
|
|
214
|
+
if (status >= 500) {
|
|
215
|
+
return `HonuOffice returned a server error (HTTP ${status}${detail ? `: ${detail}` : ''}).`;
|
|
216
|
+
}
|
|
217
|
+
return `HonuOffice rejected the request (HTTP ${status}${detail ? `: ${detail}` : ''}).`;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Take the payload out of the API's `{ success, data, meta }` envelope.
|
|
222
|
+
*
|
|
223
|
+
* Deliberately not done inside `request()`: `meta` carries pagination, and a
|
|
224
|
+
* client that silently discards it leaves callers unable to page. Unwrapping at
|
|
225
|
+
* the call site keeps both halves reachable.
|
|
226
|
+
*
|
|
227
|
+
* A response that is not enveloped is returned unchanged, so this is safe to
|
|
228
|
+
* apply to any endpoint.
|
|
229
|
+
*
|
|
230
|
+
* @param {unknown} body - A parsed response body.
|
|
231
|
+
* @returns {unknown} The payload.
|
|
232
|
+
*/
|
|
233
|
+
export function unwrap(body) {
|
|
234
|
+
if (body && typeof body === 'object' && 'data' in body && 'success' in body) {
|
|
235
|
+
return body.data;
|
|
236
|
+
}
|
|
237
|
+
return body;
|
|
238
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Entry point. Speaks MCP over stdio, which is what Claude Desktop launches.
|
|
4
|
+
*
|
|
5
|
+
* NOTHING may be written to stdout except protocol traffic. stdout *is* the
|
|
6
|
+
* transport: a stray `console.log` corrupts the JSON-RPC stream and the client
|
|
7
|
+
* reports a connection failure with no clue as to the cause. Diagnostics go to
|
|
8
|
+
* stderr, which the client logs.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
12
|
+
|
|
13
|
+
import { createServer, SERVER_VERSION } from './server.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Start the server.
|
|
17
|
+
*
|
|
18
|
+
* @returns {Promise<void>} Resolves once connected.
|
|
19
|
+
*/
|
|
20
|
+
async function main() {
|
|
21
|
+
const server = createServer();
|
|
22
|
+
const transport = new StdioServerTransport();
|
|
23
|
+
await server.connect(transport);
|
|
24
|
+
process.stderr.write(`honu-office-mcp ${SERVER_VERSION} ready\n`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
main().catch((error) => {
|
|
28
|
+
// Startup is the one place a failure cannot be returned as a tool error, so
|
|
29
|
+
// say it on stderr and exit non-zero rather than hanging as a live-looking
|
|
30
|
+
// server that answers nothing.
|
|
31
|
+
process.stderr.write(`honu-office-mcp failed to start: ${error?.stack || error}\n`);
|
|
32
|
+
process.exit(1);
|
|
33
|
+
});
|
package/src/poll.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wait for an asynchronous HonuOffice job to finish.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS. analyze, convert and remediate all return a job or request
|
|
5
|
+
* id and complete later. A tool that hands an agent an opaque id and stops is
|
|
6
|
+
* close to useless: the agent has no way to know when to look again, and the
|
|
7
|
+
* user asked a question that has not been answered yet. So the tools poll.
|
|
8
|
+
*
|
|
9
|
+
* The polling is bounded, and a timeout is NOT an error -- the job is still
|
|
10
|
+
* running server-side. The caller gets the id back so the work can be resumed
|
|
11
|
+
* rather than repeated, which matters when the operation cost money or minutes.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Terminal states, lowercased. Anything else is treated as still running. */
|
|
15
|
+
const DONE = new Set(['completed', 'complete', 'succeeded', 'success', 'finished', 'done']);
|
|
16
|
+
const FAILED = new Set(['failed', 'error', 'cancelled', 'canceled', 'rejected']);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Classify a status string.
|
|
20
|
+
*
|
|
21
|
+
* @param {unknown} status - Whatever the API reported.
|
|
22
|
+
* @returns {'done'|'failed'|'pending'} The classification.
|
|
23
|
+
*/
|
|
24
|
+
export function classifyStatus(status) {
|
|
25
|
+
const value = String(status ?? '').toLowerCase();
|
|
26
|
+
if (DONE.has(value)) return 'done';
|
|
27
|
+
if (FAILED.has(value)) return 'failed';
|
|
28
|
+
return 'pending';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Poll until the job reaches a terminal state, the deadline passes, or the
|
|
33
|
+
* signal aborts.
|
|
34
|
+
*
|
|
35
|
+
* Intervals back off from 1s to 5s. A fixed 1s interval would make a
|
|
36
|
+
* three-minute wait 180 requests against a rate-limited API for no benefit.
|
|
37
|
+
*
|
|
38
|
+
* @param {() => Promise<unknown>} fetchState - Reads the current job state.
|
|
39
|
+
* @param {{timeoutMs: number, signal?: AbortSignal, sleep?: (ms: number) => Promise<void>, now?: () => number}} options - Polling options.
|
|
40
|
+
* @returns {Promise<{outcome: 'done'|'failed'|'timeout', state: unknown}>} The result and the last state seen.
|
|
41
|
+
*/
|
|
42
|
+
export async function pollUntilDone(fetchState, options) {
|
|
43
|
+
const { timeoutMs, signal } = options;
|
|
44
|
+
const sleep = options.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
45
|
+
const now = options.now || (() => Date.now());
|
|
46
|
+
|
|
47
|
+
const deadline = now() + timeoutMs;
|
|
48
|
+
let interval = 1000;
|
|
49
|
+
let state = null;
|
|
50
|
+
|
|
51
|
+
for (;;) {
|
|
52
|
+
state = await fetchState();
|
|
53
|
+
const status = classifyStatus(readStatus(state));
|
|
54
|
+
if (status === 'done') return { outcome: 'done', state };
|
|
55
|
+
if (status === 'failed') return { outcome: 'failed', state };
|
|
56
|
+
|
|
57
|
+
// Check the deadline AFTER reading state, so a job that finished during the
|
|
58
|
+
// last sleep is reported as done rather than as a timeout.
|
|
59
|
+
if (now() >= deadline) return { outcome: 'timeout', state };
|
|
60
|
+
if (signal?.aborted) return { outcome: 'timeout', state };
|
|
61
|
+
|
|
62
|
+
await sleep(Math.min(interval, Math.max(0, deadline - now())));
|
|
63
|
+
interval = Math.min(interval * 1.5, 5000);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Find the status field, wherever the endpoint put it.
|
|
69
|
+
*
|
|
70
|
+
* The API is not uniform here: job endpoints report `status` at the top level,
|
|
71
|
+
* some wrap the payload in `data`, and remediation requests use `status` on the
|
|
72
|
+
* request object. Reading all three beats making each caller know which.
|
|
73
|
+
*
|
|
74
|
+
* @param {unknown} state - A parsed API response.
|
|
75
|
+
* @returns {unknown} The status value, or undefined.
|
|
76
|
+
*/
|
|
77
|
+
export function readStatus(state) {
|
|
78
|
+
if (!state || typeof state !== 'object') return undefined;
|
|
79
|
+
return state.status ?? state.data?.status ?? state.job?.status ?? state.request?.status;
|
|
80
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool registration.
|
|
3
|
+
*
|
|
4
|
+
* Kept separate from `index.js` so the server can be built and exercised in a
|
|
5
|
+
* test without opening a stdio transport.
|
|
6
|
+
*
|
|
7
|
+
* Two conventions worth stating, because they shape every handler below:
|
|
8
|
+
*
|
|
9
|
+
* 1. Configuration is read per call, not at startup. An MCP server that dies on
|
|
10
|
+
* boot because a key is missing appears in the client as "disconnected",
|
|
11
|
+
* with the reason nowhere the user can see it. Failing inside the tool puts
|
|
12
|
+
* the explanation in front of them.
|
|
13
|
+
* 2. A failed tool returns `isError: true` with a readable message rather than
|
|
14
|
+
* throwing. The agent can then tell the user what went wrong and what to do,
|
|
15
|
+
* instead of surfacing a protocol-level error.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
19
|
+
import { z } from 'zod';
|
|
20
|
+
|
|
21
|
+
import { loadConfig } from './config.js';
|
|
22
|
+
import { ApiClient } from './http.js';
|
|
23
|
+
import { analyze } from './tools/analyze.js';
|
|
24
|
+
import { convert, listFormats } from './tools/convert.js';
|
|
25
|
+
import { discover } from './tools/discover.js';
|
|
26
|
+
import { remediate } from './tools/remediate.js';
|
|
27
|
+
|
|
28
|
+
/** Package version reported to the client. */
|
|
29
|
+
export const SERVER_VERSION = '0.1.0';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Build the context a tool needs, failing with a readable message when the
|
|
33
|
+
* environment is not usable.
|
|
34
|
+
*
|
|
35
|
+
* @param {NodeJS.ProcessEnv} env - Environment to read.
|
|
36
|
+
* @param {typeof fetch} [fetchImpl] - Injectable for tests.
|
|
37
|
+
* @returns {{client: ApiClient, timeoutMs: number}} The context.
|
|
38
|
+
*/
|
|
39
|
+
function buildContext(env, fetchImpl) {
|
|
40
|
+
const config = loadConfig(env);
|
|
41
|
+
return { client: new ApiClient(config, fetchImpl), timeoutMs: config.timeoutMs };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Wrap a tool so every outcome becomes a well-formed MCP result.
|
|
46
|
+
*
|
|
47
|
+
* @param {(context: object, input: object) => Promise<unknown>} run - The tool.
|
|
48
|
+
* @param {{env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch}} options - Injection points.
|
|
49
|
+
* @returns {(input: object) => Promise<object>} An MCP tool handler.
|
|
50
|
+
*/
|
|
51
|
+
function handler(run, options = {}) {
|
|
52
|
+
return async (input) => {
|
|
53
|
+
try {
|
|
54
|
+
const context = buildContext(options.env || process.env, options.fetchImpl);
|
|
55
|
+
const result = await run(context, input);
|
|
56
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
57
|
+
} catch (error) {
|
|
58
|
+
// The message is the product here: ConfigError says what to set, ApiError
|
|
59
|
+
// says what the API refused, TransportError says it could not be reached.
|
|
60
|
+
return {
|
|
61
|
+
isError: true,
|
|
62
|
+
content: [{ type: 'text', text: `${error.name || 'Error'}: ${error.message}` }],
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Create the server with all four tools registered.
|
|
70
|
+
*
|
|
71
|
+
* @param {{env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch}} [options] - Injection points for tests.
|
|
72
|
+
* @returns {McpServer} The configured server.
|
|
73
|
+
*/
|
|
74
|
+
export function createServer(options = {}) {
|
|
75
|
+
const server = new McpServer({ name: 'honu-office', version: SERVER_VERSION });
|
|
76
|
+
|
|
77
|
+
server.registerTool(
|
|
78
|
+
'analyze',
|
|
79
|
+
{
|
|
80
|
+
title: 'Analyze a document for accessibility',
|
|
81
|
+
description:
|
|
82
|
+
'Check a PDF or Office document against PDF/UA and WCAG, and return the findings: ' +
|
|
83
|
+
'an overall score, issue counts by severity, and the most severe issues. ' +
|
|
84
|
+
'Takes a file on this machine or a URL. Waits for the result by default.',
|
|
85
|
+
inputSchema: {
|
|
86
|
+
file: z.string().optional().describe('Path to a document on this machine. Give this or `url`.'),
|
|
87
|
+
url: z.string().url().optional().describe('Publicly reachable URL of a document. Give this or `file`.'),
|
|
88
|
+
wait: z.boolean().optional().describe('Wait for the analysis to finish (default true). False returns a job id immediately.'),
|
|
89
|
+
maxIssues: z.number().int().positive().max(200).optional().describe('How many issues to return, most severe first (default 20).'),
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
handler(analyze, options)
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
server.registerTool(
|
|
96
|
+
'convert',
|
|
97
|
+
{
|
|
98
|
+
title: 'Convert a document to another format',
|
|
99
|
+
description:
|
|
100
|
+
'Convert a document — for example PDF to Word, or to HTML, text, RTF, EPUB or Markdown. ' +
|
|
101
|
+
'Returns the download location when the conversion finishes. ' +
|
|
102
|
+
'Use `list_formats: true` to see which conversions are supported.',
|
|
103
|
+
inputSchema: {
|
|
104
|
+
file: z.string().optional().describe('Path to the document on this machine.'),
|
|
105
|
+
to: z.string().optional().describe('Target format, e.g. "word", "html", "text", "markdown".'),
|
|
106
|
+
wait: z.boolean().optional().describe('Wait for the conversion to finish (default true).'),
|
|
107
|
+
list_formats: z.boolean().optional().describe('Return the supported conversions instead of converting.'),
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
handler(async (context, input) => {
|
|
111
|
+
if (input.list_formats) return { status: 'ok', formats: await listFormats(context) };
|
|
112
|
+
return convert(context, input);
|
|
113
|
+
}, options)
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
server.registerTool(
|
|
117
|
+
'discover',
|
|
118
|
+
{
|
|
119
|
+
title: 'Discover documents on a site',
|
|
120
|
+
description:
|
|
121
|
+
'Crawl a site to find documents. Crawls run for a long time, so this does not wait: ' +
|
|
122
|
+
'start one, then check its status and list what it found. ' +
|
|
123
|
+
'Actions: "start" (needs url), "status" and "documents" (need jobId), "list".',
|
|
124
|
+
inputSchema: {
|
|
125
|
+
action: z.enum(['start', 'status', 'documents', 'list']).optional().describe('Defaults to "start", or "status" when jobId is given.'),
|
|
126
|
+
url: z.string().url().optional().describe('Site to crawl. Required for "start".'),
|
|
127
|
+
jobId: z.string().optional().describe('Discovery job id. Required for "status" and "documents".'),
|
|
128
|
+
maxDepth: z.number().int().positive().optional().describe('How deep to crawl.'),
|
|
129
|
+
maxPages: z.number().int().positive().optional().describe('Cap on pages visited.'),
|
|
130
|
+
limit: z.number().int().positive().max(200).optional().describe('How many rows to return (default 50 for documents, 20 for lists).'),
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
handler(discover, options)
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
server.registerTool(
|
|
137
|
+
'remediate',
|
|
138
|
+
{
|
|
139
|
+
title: 'Submit a document for remediation',
|
|
140
|
+
description:
|
|
141
|
+
'Ask HonuOffice to fix a document\'s accessibility problems. Submit a file, a URL, or ' +
|
|
142
|
+
'the reportId from a previous analyze call. Remediation is worked on over time, so this ' +
|
|
143
|
+
'returns a request id and any quote rather than waiting. ' +
|
|
144
|
+
'Actions: "submit", "status" (needs requestId), "list".',
|
|
145
|
+
inputSchema: {
|
|
146
|
+
action: z.enum(['submit', 'status', 'list']).optional().describe('Defaults to "submit", or "status" when requestId is given.'),
|
|
147
|
+
file: z.string().optional().describe('Path to the document on this machine.'),
|
|
148
|
+
url: z.string().url().optional().describe('Publicly reachable URL of the document.'),
|
|
149
|
+
reportId: z.string().optional().describe('Report id from a previous analyze call — avoids re-uploading.'),
|
|
150
|
+
requestId: z.string().optional().describe('Remediation request id. Required for "status".'),
|
|
151
|
+
notes: z.string().optional().describe('Anything the remediation team should know.'),
|
|
152
|
+
limit: z.number().int().positive().max(200).optional().describe('How many requests to list (default 20).'),
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
handler(remediate, options)
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
return server;
|
|
159
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `analyze` — assess a document against PDF/UA and WCAG.
|
|
3
|
+
*
|
|
4
|
+
* Analysis is asynchronous: the upload returns a job id, and the finished job
|
|
5
|
+
* carries the findings. A tool that returned after the first call would answer
|
|
6
|
+
* "I started something", which is not what anyone asked, so this follows the
|
|
7
|
+
* job to completion and returns the findings.
|
|
8
|
+
*
|
|
9
|
+
* WHERE THE FINDINGS LIVE. Verified against a running API rather than inferred:
|
|
10
|
+
* the completed job holds everything at `result.analysis`, and the report id at
|
|
11
|
+
* `result.reportId` — NOT at the top level. Reading `job.reportId` finds
|
|
12
|
+
* nothing, which is what this tool used to do; it reported "completed but
|
|
13
|
+
* produced no report id" for every successful analysis. The inline payload is
|
|
14
|
+
* preferred because it is already in hand; `/api/file/reports/:id` returns the
|
|
15
|
+
* same `summary` and `issues` and is kept only as a fallback.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { unwrap } from '../http.js';
|
|
19
|
+
import { pollUntilDone, readStatus } from '../poll.js';
|
|
20
|
+
import { readDocument } from '../files.js';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Run an analysis.
|
|
24
|
+
*
|
|
25
|
+
* @param {{client: import('../http.js').ApiClient, timeoutMs: number}} context - Injected dependencies.
|
|
26
|
+
* @param {{file?: string, url?: string, wait?: boolean, maxIssues?: number}} input - Tool input.
|
|
27
|
+
* @param {{sleep?: (ms: number) => Promise<void>}} [testHooks] - Injectable timing for tests.
|
|
28
|
+
* @returns {Promise<object>} A structured result.
|
|
29
|
+
*/
|
|
30
|
+
export async function analyze(context, input, testHooks = {}) {
|
|
31
|
+
const { client, timeoutMs } = context;
|
|
32
|
+
const { file, url, wait = true, maxIssues = 20 } = input;
|
|
33
|
+
|
|
34
|
+
if (!file && !url) throw new Error('Give either `file` (a path on this machine) or `url`.');
|
|
35
|
+
if (file && url) throw new Error('Give `file` or `url`, not both.');
|
|
36
|
+
|
|
37
|
+
let started;
|
|
38
|
+
let subject;
|
|
39
|
+
if (file) {
|
|
40
|
+
const document = await readDocument(file);
|
|
41
|
+
subject = document.path;
|
|
42
|
+
started = unwrap(await client.upload('/api/file/analyze', document));
|
|
43
|
+
} else {
|
|
44
|
+
subject = url;
|
|
45
|
+
started = unwrap(await client.request('/api/file/analyze-url', { method: 'POST', body: { url } }));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const jobId = started?.jobId;
|
|
49
|
+
if (!jobId) {
|
|
50
|
+
// The contract says a job id comes back. Saying so plainly beats a later
|
|
51
|
+
// undefined-shaped failure three calls away from the cause.
|
|
52
|
+
return { status: 'unexpected', subject, message: 'HonuOffice accepted the document but returned no job id.', raw: started };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!wait) {
|
|
56
|
+
return { status: 'started', subject, jobId, message: `Analysis started. Poll job ${jobId} for the result.` };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const { outcome, state } = await pollUntilDone(
|
|
60
|
+
async () => unwrap(await client.request(`/api/jobs/${jobId}`)),
|
|
61
|
+
{ timeoutMs, sleep: testHooks.sleep }
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
if (outcome === 'timeout') {
|
|
65
|
+
return {
|
|
66
|
+
status: 'timeout',
|
|
67
|
+
subject,
|
|
68
|
+
jobId,
|
|
69
|
+
lastStatus: readStatus(state),
|
|
70
|
+
message: `Still running after ${Math.round(timeoutMs / 1000)}s. The job is not lost — ask again for job ${jobId}.`,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
if (outcome === 'failed') {
|
|
74
|
+
return { status: 'failed', subject, jobId, message: state?.error || 'Analysis failed.', raw: state };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const result = state?.result || {};
|
|
78
|
+
const reportId = result.reportId ?? state?.reportId;
|
|
79
|
+
|
|
80
|
+
// Prefer the analysis the job already carries; fall back to the report
|
|
81
|
+
// endpoint only when it is absent.
|
|
82
|
+
let analysis = result.analysis;
|
|
83
|
+
if (!analysis && reportId) {
|
|
84
|
+
analysis = unwrap(await client.request(`/api/file/reports/${reportId}`));
|
|
85
|
+
}
|
|
86
|
+
if (!analysis) {
|
|
87
|
+
return { status: 'completed', subject, jobId, reportId, message: 'Analysis completed but returned no findings.', raw: state };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return summarizeAnalysis(analysis, {
|
|
91
|
+
subject,
|
|
92
|
+
jobId,
|
|
93
|
+
reportId,
|
|
94
|
+
maxIssues,
|
|
95
|
+
filename: state?.filename ?? analysis.pdfName,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Severity order for the findings an agent should read first. */
|
|
100
|
+
const SEVERITY_RANK = { critical: 0, high: 1, major: 1, serious: 1, medium: 2, moderate: 2, low: 3, minor: 3, info: 4 };
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Reduce an analysis to what is worth putting in front of an agent.
|
|
104
|
+
*
|
|
105
|
+
* TWO THINGS HERE ARE EASY TO GET WRONG, and both were got wrong before a
|
|
106
|
+
* running API was consulted:
|
|
107
|
+
*
|
|
108
|
+
* 1. `issues` is the list of every check performed, not the list of problems.
|
|
109
|
+
* Most entries carry `status: "pass"`. Returning them unfiltered presents
|
|
110
|
+
* passing checks as findings.
|
|
111
|
+
* 2. `summary.critical` / `.high` / `.medium` count checks BY SEVERITY,
|
|
112
|
+
* including the ones that passed — on a measured document they summed to
|
|
113
|
+
* 88 while only 6 checks had actually failed. Reporting them as issue
|
|
114
|
+
* counts would put "25 critical issues" in front of a user with 6 errors.
|
|
115
|
+
* The real failure counts are `summary.errors` and `summary.warnings`, and
|
|
116
|
+
* the severity breakdown below is computed from the failing checks alone.
|
|
117
|
+
*
|
|
118
|
+
* @param {object} analysis - The `result.analysis` payload, or a report body.
|
|
119
|
+
* @param {{subject: string, jobId: string, reportId?: string, maxIssues: number, filename?: string}} meta - Context.
|
|
120
|
+
* @returns {object} The summary.
|
|
121
|
+
*/
|
|
122
|
+
export function summarizeAnalysis(analysis, meta) {
|
|
123
|
+
const summary = analysis?.summary || {};
|
|
124
|
+
const checks = Array.isArray(analysis?.issues) ? analysis.issues : [];
|
|
125
|
+
|
|
126
|
+
const failing = checks.filter((check) => String(check?.status).toLowerCase() !== 'pass');
|
|
127
|
+
const sorted = [...failing].sort(
|
|
128
|
+
(a, b) => (SEVERITY_RANK[String(a.severity).toLowerCase()] ?? 9) - (SEVERITY_RANK[String(b.severity).toLowerCase()] ?? 9)
|
|
129
|
+
);
|
|
130
|
+
const shown = sorted.slice(0, meta.maxIssues);
|
|
131
|
+
|
|
132
|
+
const bySeverity = {};
|
|
133
|
+
for (const issue of failing) {
|
|
134
|
+
const key = String(issue.severity ?? 'unknown').toLowerCase();
|
|
135
|
+
bySeverity[key] = (bySeverity[key] || 0) + 1;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
status: 'completed',
|
|
140
|
+
subject: meta.subject,
|
|
141
|
+
jobId: meta.jobId,
|
|
142
|
+
reportId: meta.reportId,
|
|
143
|
+
filename: meta.filename,
|
|
144
|
+
compliant: summary.overallStatus ? summary.overallStatus === 'compliant' : undefined,
|
|
145
|
+
overallStatus: summary.overallStatus,
|
|
146
|
+
complianceScore: summary.complianceScore,
|
|
147
|
+
conformsTo: analysis?.conformsTo,
|
|
148
|
+
pageCount: analysis?.pageCount,
|
|
149
|
+
checks: {
|
|
150
|
+
total: summary.totalChecks ?? checks.length,
|
|
151
|
+
passed: summary.passed,
|
|
152
|
+
failed: failing.length,
|
|
153
|
+
},
|
|
154
|
+
// Counts of checks that actually failed, split the way the API splits them.
|
|
155
|
+
failures: {
|
|
156
|
+
errors: summary.errors,
|
|
157
|
+
warnings: summary.warnings,
|
|
158
|
+
bySeverity,
|
|
159
|
+
},
|
|
160
|
+
issues: shown.map((issue) => ({
|
|
161
|
+
id: issue.id,
|
|
162
|
+
rule: issue.rule,
|
|
163
|
+
clause: issue.clause,
|
|
164
|
+
standard: issue.standard,
|
|
165
|
+
severity: issue.severity,
|
|
166
|
+
status: issue.status,
|
|
167
|
+
location: issue.location ?? issue.context,
|
|
168
|
+
page: issue.page,
|
|
169
|
+
occurrenceCount: issue.occurrenceCount,
|
|
170
|
+
description: issue.description,
|
|
171
|
+
impact: issue.guidance?.impact,
|
|
172
|
+
howToFix: issue.guidance?.howToFix,
|
|
173
|
+
detail: issue.details?.errorMessage,
|
|
174
|
+
})),
|
|
175
|
+
issuesOmitted: Math.max(0, sorted.length - shown.length),
|
|
176
|
+
};
|
|
177
|
+
}
|