@honu-office/mcp 0.0.0-stage → 0.3.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 +228 -2
- package/package.json +60 -4
- package/src/config.js +227 -0
- package/src/files.js +184 -0
- package/src/http.js +243 -0
- package/src/index.js +33 -0
- package/src/poll.js +80 -0
- package/src/server.js +223 -0
- package/src/tools/analyze.js +177 -0
- package/src/tools/convert.js +97 -0
- package/src/tools/discover.js +127 -0
- package/src/tools/remediate.js +146 -0
package/src/files.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading the local files a tool was pointed at.
|
|
3
|
+
*
|
|
4
|
+
* This server runs on the user's machine, which is the whole reason it can take
|
|
5
|
+
* a path at all: the alternative would be making someone host a document
|
|
6
|
+
* publicly before they can ask whether it is accessible.
|
|
7
|
+
*
|
|
8
|
+
* That also means the paths come from a model, so they get checked rather than
|
|
9
|
+
* trusted — and the check is on the real target, after symlinks are resolved,
|
|
10
|
+
* because the bytes that get uploaded are the target's (OA-475). A clear refusal
|
|
11
|
+
* beats a stack trace, and beats uploading something the user did not mean to
|
|
12
|
+
* send. When HONU_OFFICE_ALLOWED_DIRS is set, a read is also confined to those
|
|
13
|
+
* directories; it is opt-in so existing setups that pass absolute paths keep
|
|
14
|
+
* working.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
|
|
20
|
+
/** Formats HonuOffice accepts for analysis or conversion. */
|
|
21
|
+
export const SUPPORTED_EXTENSIONS = new Set([
|
|
22
|
+
'.pdf',
|
|
23
|
+
'.docx',
|
|
24
|
+
'.doc',
|
|
25
|
+
'.xlsx',
|
|
26
|
+
'.xls',
|
|
27
|
+
'.pptx',
|
|
28
|
+
'.ppt',
|
|
29
|
+
'.html',
|
|
30
|
+
'.htm',
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
/** Raised when a path cannot be used. The message says why. */
|
|
34
|
+
export class FileError extends Error {
|
|
35
|
+
/** @param {string} message - What is wrong with the path. */
|
|
36
|
+
constructor(message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = 'FileError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Read a document from disk, with the checks worth doing before an upload.
|
|
44
|
+
*
|
|
45
|
+
* Symlinks are resolved first and every check below judges the real target, so
|
|
46
|
+
* a `.pdf` symlink pointing at a secret cannot slip past the extension
|
|
47
|
+
* allowlist on the link's own name.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} filePath - Absolute or relative path to the document.
|
|
50
|
+
* @param {{maxBytes?: number, allowAnyExtension?: boolean, allowedDirs?: string[]}} [options] - Read options. `allowedDirs` overrides HONU_OFFICE_ALLOWED_DIRS, for tests.
|
|
51
|
+
* @returns {Promise<{buffer: Buffer, filename: string, path: string, size: number}>} The file.
|
|
52
|
+
* @throws {FileError} When the path is missing, is not a file, is empty, is too
|
|
53
|
+
* large, has an extension HonuOffice does not handle, or — when directory
|
|
54
|
+
* confinement is configured — is outside the allowed directories.
|
|
55
|
+
*/
|
|
56
|
+
export async function readDocument(filePath, options = {}) {
|
|
57
|
+
const maxBytes = options.maxBytes ?? 100 * 1024 * 1024;
|
|
58
|
+
|
|
59
|
+
if (typeof filePath !== 'string' || filePath.trim() === '') {
|
|
60
|
+
throw new FileError('No file path was given.');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const resolved = path.resolve(filePath);
|
|
64
|
+
|
|
65
|
+
// Resolve symlinks before anything else and work from the real target.
|
|
66
|
+
let real;
|
|
67
|
+
try {
|
|
68
|
+
real = await realpath(resolved);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error.code === 'ENOENT') {
|
|
71
|
+
throw new FileError(
|
|
72
|
+
`No file at ${resolved}. Give an absolute path, or one relative to where this server was started.`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
if (error.code === 'EACCES') {
|
|
76
|
+
throw new FileError(`Not permitted to read ${resolved}.`);
|
|
77
|
+
}
|
|
78
|
+
throw new FileError(`Could not read ${resolved}: ${error.message}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Optional confinement: when allowed directories are configured, the real
|
|
82
|
+
// target must sit inside one of them.
|
|
83
|
+
await assertWithinAllowedDirs(real, options.allowedDirs);
|
|
84
|
+
|
|
85
|
+
let info;
|
|
86
|
+
try {
|
|
87
|
+
info = await stat(real);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (error.code === 'EACCES') {
|
|
90
|
+
throw new FileError(`Not permitted to read ${real}.`);
|
|
91
|
+
}
|
|
92
|
+
throw new FileError(`Could not read ${real}: ${error.message}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (info.isDirectory()) {
|
|
96
|
+
throw new FileError(`${real} is a directory, not a document.`);
|
|
97
|
+
}
|
|
98
|
+
if (!info.isFile()) {
|
|
99
|
+
throw new FileError(`${real} is not a regular file.`);
|
|
100
|
+
}
|
|
101
|
+
if (info.size === 0) {
|
|
102
|
+
// An empty file uploads fine and comes back with a baffling analysis
|
|
103
|
+
// failure, so it is worth catching here where the cause is obvious.
|
|
104
|
+
throw new FileError(`${real} is empty.`);
|
|
105
|
+
}
|
|
106
|
+
if (info.size > maxBytes) {
|
|
107
|
+
throw new FileError(
|
|
108
|
+
`${real} is ${formatBytes(info.size)}, over the ${formatBytes(maxBytes)} limit.`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const extension = path.extname(real).toLowerCase();
|
|
113
|
+
if (!options.allowAnyExtension && !SUPPORTED_EXTENSIONS.has(extension)) {
|
|
114
|
+
throw new FileError(
|
|
115
|
+
`${real} has an unsupported extension (${extension || 'none'}). ` +
|
|
116
|
+
`Supported: ${[...SUPPORTED_EXTENSIONS].join(', ')}.`
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const buffer = await readFile(real);
|
|
121
|
+
return { buffer, filename: path.basename(real), path: real, size: info.size };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Confine a resolved path to the configured allowed directories, when any are
|
|
126
|
+
* set. A no-op when confinement is not configured (opt-in).
|
|
127
|
+
*
|
|
128
|
+
* @param {string} realPath - A path with symlinks already resolved.
|
|
129
|
+
* @param {string[]} [override] - Allowed roots for tests; defaults to the env.
|
|
130
|
+
* @returns {Promise<void>} Resolves when the path is allowed.
|
|
131
|
+
* @throws {FileError} When confinement is configured and the path is outside it.
|
|
132
|
+
*/
|
|
133
|
+
async function assertWithinAllowedDirs(realPath, override) {
|
|
134
|
+
const configured = override ?? parseAllowedDirs(process.env.HONU_OFFICE_ALLOWED_DIRS);
|
|
135
|
+
if (!configured || configured.length === 0) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const roots = await Promise.all(
|
|
139
|
+
configured.map(async (dir) => {
|
|
140
|
+
const abs = path.resolve(dir);
|
|
141
|
+
try {
|
|
142
|
+
return await realpath(abs);
|
|
143
|
+
} catch {
|
|
144
|
+
return abs;
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
);
|
|
148
|
+
const allowed = roots.some((root) => realPath === root || realPath.startsWith(root + path.sep));
|
|
149
|
+
if (!allowed) {
|
|
150
|
+
throw new FileError(
|
|
151
|
+
`${realPath} is outside the directories this server may read. ` +
|
|
152
|
+
`Add its directory to HONU_OFFICE_ALLOWED_DIRS to allow it.`
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Parse a path-list env value into directory roots.
|
|
159
|
+
*
|
|
160
|
+
* @param {string|undefined} raw - A path.delimiter-separated list, or undefined.
|
|
161
|
+
* @returns {string[]|null} The directories, or null when unset/empty.
|
|
162
|
+
*/
|
|
163
|
+
function parseAllowedDirs(raw) {
|
|
164
|
+
if (typeof raw !== 'string' || raw.trim() === '') {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
const dirs = raw
|
|
168
|
+
.split(path.delimiter)
|
|
169
|
+
.map((d) => d.trim())
|
|
170
|
+
.filter(Boolean);
|
|
171
|
+
return dirs.length > 0 ? dirs : null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Render a byte count the way a person would say it.
|
|
176
|
+
*
|
|
177
|
+
* @param {number} bytes - The count.
|
|
178
|
+
* @returns {string} e.g. "2.4 MB".
|
|
179
|
+
*/
|
|
180
|
+
export function formatBytes(bytes) {
|
|
181
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
182
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
183
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
184
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
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
|
+
// Never follow a redirect: fetch strips Authorization on a
|
|
120
|
+
// cross-origin redirect but not the custom X-API-Key, so following one
|
|
121
|
+
// would hand the key to the redirect target (OA-497). The API does not
|
|
122
|
+
// redirect these calls.
|
|
123
|
+
redirect: 'error',
|
|
124
|
+
});
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (error?.name === 'AbortError' || error?.name === 'TimeoutError') {
|
|
127
|
+
// Say which abort it was. Blaming the deadline for a caller's own
|
|
128
|
+
// cancellation would assert something untrue -- and a message that
|
|
129
|
+
// misreports the cause is how time gets spent on the wrong problem.
|
|
130
|
+
throw new TransportError(
|
|
131
|
+
deadline.aborted
|
|
132
|
+
? `Request to ${path} did not complete within ${Math.round(timeoutMs / 1000)}s and was aborted. ` +
|
|
133
|
+
'The API may be unreachable or overloaded.'
|
|
134
|
+
: `Request to ${path} was cancelled before it completed.`,
|
|
135
|
+
error
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
throw new TransportError(
|
|
139
|
+
`Could not reach the HonuOffice API at ${this.baseUrl}: ${error.message}. ` +
|
|
140
|
+
'Check the host is correct and reachable from this machine.',
|
|
141
|
+
error
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const text = await response.text();
|
|
146
|
+
let parsed = null;
|
|
147
|
+
if (text) {
|
|
148
|
+
try {
|
|
149
|
+
parsed = JSON.parse(text);
|
|
150
|
+
} catch {
|
|
151
|
+
// A non-JSON body from a 2xx is a contract break worth surfacing; from
|
|
152
|
+
// an error status it is usually a proxy page, which the message shows.
|
|
153
|
+
parsed = text;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (!response.ok) {
|
|
158
|
+
throw new ApiError(describeFailure(response.status, parsed), response.status, parsed);
|
|
159
|
+
}
|
|
160
|
+
return parsed;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Upload a file as multipart/form-data.
|
|
165
|
+
*
|
|
166
|
+
* @param {string} path - Path beginning with `/api/`.
|
|
167
|
+
* @param {{buffer: Buffer, filename: string}} file - File content and name.
|
|
168
|
+
* @param {Record<string, string|number|boolean|undefined>} [fields] - Extra form fields.
|
|
169
|
+
* @param {{fieldName?: string, signal?: AbortSignal}} [options] - Upload options.
|
|
170
|
+
* @returns {Promise<unknown>} The parsed response body.
|
|
171
|
+
*/
|
|
172
|
+
async upload(path, file, fields = {}, options = {}) {
|
|
173
|
+
const form = new FormData();
|
|
174
|
+
form.append(
|
|
175
|
+
options.fieldName || 'file',
|
|
176
|
+
new Blob([file.buffer]),
|
|
177
|
+
file.filename
|
|
178
|
+
);
|
|
179
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
180
|
+
if (value !== undefined && value !== null) form.append(key, String(value));
|
|
181
|
+
}
|
|
182
|
+
return this.request(path, {
|
|
183
|
+
method: 'POST',
|
|
184
|
+
body: form,
|
|
185
|
+
signal: options.signal,
|
|
186
|
+
timeoutMs: options.timeoutMs ?? this.uploadTimeoutMs,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Turn a status and body into a message that says what to do about it.
|
|
193
|
+
*
|
|
194
|
+
* @param {number} status - HTTP status.
|
|
195
|
+
* @param {unknown} body - Parsed body, if any.
|
|
196
|
+
* @returns {string} The message.
|
|
197
|
+
*/
|
|
198
|
+
function describeFailure(status, body) {
|
|
199
|
+
const detail =
|
|
200
|
+
(body && typeof body === 'object' && (body.error?.message || body.message)) ||
|
|
201
|
+
(typeof body === 'string' && body.slice(0, 200)) ||
|
|
202
|
+
'';
|
|
203
|
+
|
|
204
|
+
if (status === 401 || status === 403) {
|
|
205
|
+
return (
|
|
206
|
+
`HonuOffice rejected the API key (HTTP ${status}${detail ? `: ${detail}` : ''}). ` +
|
|
207
|
+
'Check HONU_OFFICE_API_KEY is a current key for the right account.'
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
if (status === 404) {
|
|
211
|
+
return `Not found (HTTP 404${detail ? `: ${detail}` : ''}).`;
|
|
212
|
+
}
|
|
213
|
+
if (status === 413) {
|
|
214
|
+
return `The document is too large for this account's limit (HTTP 413${detail ? `: ${detail}` : ''}).`;
|
|
215
|
+
}
|
|
216
|
+
if (status === 429) {
|
|
217
|
+
return `Rate limited by HonuOffice (HTTP 429${detail ? `: ${detail}` : ''}). Retry shortly.`;
|
|
218
|
+
}
|
|
219
|
+
if (status >= 500) {
|
|
220
|
+
return `HonuOffice returned a server error (HTTP ${status}${detail ? `: ${detail}` : ''}).`;
|
|
221
|
+
}
|
|
222
|
+
return `HonuOffice rejected the request (HTTP ${status}${detail ? `: ${detail}` : ''}).`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Take the payload out of the API's `{ success, data, meta }` envelope.
|
|
227
|
+
*
|
|
228
|
+
* Deliberately not done inside `request()`: `meta` carries pagination, and a
|
|
229
|
+
* client that silently discards it leaves callers unable to page. Unwrapping at
|
|
230
|
+
* the call site keeps both halves reachable.
|
|
231
|
+
*
|
|
232
|
+
* A response that is not enveloped is returned unchanged, so this is safe to
|
|
233
|
+
* apply to any endpoint.
|
|
234
|
+
*
|
|
235
|
+
* @param {unknown} body - A parsed response body.
|
|
236
|
+
* @returns {unknown} The payload.
|
|
237
|
+
*/
|
|
238
|
+
export function unwrap(body) {
|
|
239
|
+
if (body && typeof body === 'object' && 'data' in body && 'success' in body) {
|
|
240
|
+
return body.data;
|
|
241
|
+
}
|
|
242
|
+
return body;
|
|
243
|
+
}
|
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
|
+
}
|