@agentmesh-md/mcp-server 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/README.md +115 -2
- package/dist/agent-operating-contract.txt +120 -0
- package/dist/client.js +254 -0
- package/dist/config.js +189 -0
- package/dist/connect-bridge.js +62 -0
- package/dist/connect.js +233 -0
- package/dist/context.js +42 -0
- package/dist/contract.js +10 -0
- package/dist/errors.js +117 -0
- package/dist/http.js +347 -0
- package/dist/index.js +24 -0
- package/dist/legacy.js +123 -0
- package/dist/logger.js +36 -0
- package/dist/mentions.cjs +22 -0
- package/dist/node-bridge.js +110 -0
- package/dist/oauth-client.js +165 -0
- package/dist/redact.js +92 -0
- package/dist/schemas.js +413 -0
- package/dist/server.js +163 -0
- package/dist/session.js +43 -0
- package/dist/terminal-diagnostic.js +9 -0
- package/dist/terminal-runtime.js +177 -0
- package/dist/tools.js +528 -0
- package/dist/wake-monitor.js +117 -0
- package/dist/wake-storage.js +68 -0
- package/dist/wake.js +521 -0
- package/package.json +46 -4
- package/schemas/defs.json +121 -0
- package/schemas/tools.json +1344 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
7
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
8
|
+
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
|
|
9
|
+
import { readJson, writeAtomic } from './wake-storage.js';
|
|
10
|
+
export const RESOURCE = 'https://agentmesh.md/mcp';
|
|
11
|
+
export function ownerDirectory(dir) {
|
|
12
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
13
|
+
const stat = fs.lstatSync(dir);
|
|
14
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.())
|
|
15
|
+
throw new Error('OwnerDirectoryRequired');
|
|
16
|
+
fs.chmodSync(dir, 0o700);
|
|
17
|
+
}
|
|
18
|
+
export function credentialFile(file) {
|
|
19
|
+
if (!fs.existsSync(file))
|
|
20
|
+
return undefined;
|
|
21
|
+
const stat = fs.lstatSync(file);
|
|
22
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
|
|
23
|
+
throw new Error('OwnerCredentialsRequired');
|
|
24
|
+
const saved = readJson(file);
|
|
25
|
+
if (saved.resource !== RESOURCE)
|
|
26
|
+
throw new Error('ResourceMismatch');
|
|
27
|
+
return saved;
|
|
28
|
+
}
|
|
29
|
+
// One launcher owns this provider and serializes all remote calls. Its stdio
|
|
30
|
+
// children never receive credentials, including during refresh rotation.
|
|
31
|
+
class Provider {
|
|
32
|
+
file;
|
|
33
|
+
verifier = '';
|
|
34
|
+
secrets = new Set();
|
|
35
|
+
redact(value) {
|
|
36
|
+
let text = JSON.stringify(value);
|
|
37
|
+
for (const secret of this.secrets)
|
|
38
|
+
text = text.split(secret).join('[redacted]');
|
|
39
|
+
return JSON.parse(text);
|
|
40
|
+
}
|
|
41
|
+
remember(tokens) {
|
|
42
|
+
for (const token of [tokens?.access_token, tokens?.refresh_token])
|
|
43
|
+
if (token)
|
|
44
|
+
this.secrets.add(token);
|
|
45
|
+
}
|
|
46
|
+
nonce = randomBytes(32).toString('hex');
|
|
47
|
+
saved;
|
|
48
|
+
redirectUrl;
|
|
49
|
+
authorizationStarted = false;
|
|
50
|
+
constructor(file, redirect) {
|
|
51
|
+
this.file = file;
|
|
52
|
+
this.saved = credentialFile(file) ?? { resource: RESOURCE, redirect };
|
|
53
|
+
this.redirectUrl = this.saved.redirect;
|
|
54
|
+
this.remember(this.saved.tokens);
|
|
55
|
+
}
|
|
56
|
+
get clientMetadata() {
|
|
57
|
+
return { client_name: 'AgentMesh terminal Connect', redirect_uris: [this.redirectUrl],
|
|
58
|
+
grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none',
|
|
59
|
+
scope: 'mesh:read mesh:write offline_access' };
|
|
60
|
+
}
|
|
61
|
+
state() { return this.nonce; }
|
|
62
|
+
validState(value) { return value === this.nonce; }
|
|
63
|
+
clientInformation() { return this.saved.client; }
|
|
64
|
+
saveClientInformation(value) { this.saved.client = value; this.save(); }
|
|
65
|
+
tokens() { return this.saved.tokens; }
|
|
66
|
+
saveTokens(value) { this.remember(value); this.saved.tokens = value; this.save(); }
|
|
67
|
+
saveCodeVerifier(value) { this.verifier = value; }
|
|
68
|
+
codeVerifier() { return this.verifier; }
|
|
69
|
+
async validateResourceURL(server, resource) {
|
|
70
|
+
if (String(server) !== RESOURCE || (resource !== undefined && resource !== RESOURCE))
|
|
71
|
+
throw new Error('ResourceMismatch');
|
|
72
|
+
return new URL(RESOURCE);
|
|
73
|
+
}
|
|
74
|
+
async redirectToAuthorization(url) {
|
|
75
|
+
if (url.origin !== new URL(RESOURCE).origin || url.pathname !== '/authorize')
|
|
76
|
+
throw new Error('AuthorizationOriginMismatch');
|
|
77
|
+
this.authorizationStarted = true;
|
|
78
|
+
process.stderr.write('Approve the connection as your AgentMesh agent in the browser.\n');
|
|
79
|
+
// Never echo the authorization request/response. This URL contains only
|
|
80
|
+
// client ID, state and PKCE challenge; never bearer/refresh/code/verifier.
|
|
81
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';
|
|
82
|
+
const child = spawn(command, process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url.href] : [url.href], { stdio: 'ignore' });
|
|
83
|
+
await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', code => code === 0 ? resolve() : reject(new Error('BrowserOpenFailed'))); });
|
|
84
|
+
}
|
|
85
|
+
invalidateCredentials(scope) {
|
|
86
|
+
if (scope === 'all' || scope === 'client')
|
|
87
|
+
delete this.saved.client;
|
|
88
|
+
if (scope === 'all' || scope === 'tokens')
|
|
89
|
+
delete this.saved.tokens;
|
|
90
|
+
if (scope === 'all' || scope === 'verifier')
|
|
91
|
+
this.verifier = '';
|
|
92
|
+
this.save();
|
|
93
|
+
}
|
|
94
|
+
save() { writeAtomic(this.file, this.saved); fs.chmodSync(this.file, 0o600); }
|
|
95
|
+
}
|
|
96
|
+
// OAuth discovery/token requests stay on the canonical first-party origin;
|
|
97
|
+
// response redirects cannot exfiltrate Authorization or form credentials.
|
|
98
|
+
const safeFetch = async (input, init) => {
|
|
99
|
+
const url = new URL(input instanceof Request ? input.url : String(input));
|
|
100
|
+
if (url.origin !== new URL(RESOURCE).origin)
|
|
101
|
+
throw new Error('OAuthOriginMismatch');
|
|
102
|
+
return fetch(input, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000) });
|
|
103
|
+
};
|
|
104
|
+
export async function openOAuth(profile) {
|
|
105
|
+
ownerDirectory(profile);
|
|
106
|
+
const file = path.join(profile, 'credentials.json');
|
|
107
|
+
const saved = credentialFile(file);
|
|
108
|
+
const server = http.createServer();
|
|
109
|
+
// Reuse the registered loopback port. An occupied port fails visibly;
|
|
110
|
+
// silently changing redirect URI would invalidate the registered client.
|
|
111
|
+
const savedURL = saved ? new URL(saved.redirect) : undefined;
|
|
112
|
+
if (savedURL && (savedURL.hostname !== '127.0.0.1' || savedURL.protocol !== 'http:' || savedURL.pathname !== '/callback'))
|
|
113
|
+
throw new Error('CallbackMismatch');
|
|
114
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(savedURL ? Number(savedURL.port) : 0, '127.0.0.1', resolve); });
|
|
115
|
+
const address = server.address();
|
|
116
|
+
if (!address || typeof address === 'string')
|
|
117
|
+
throw new Error('CallbackUnavailable');
|
|
118
|
+
const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback`);
|
|
119
|
+
let timer;
|
|
120
|
+
const code = new Promise((resolve, reject) => {
|
|
121
|
+
timer = setTimeout(() => reject(new Error('ApprovalTimeout')), 180_000);
|
|
122
|
+
server.on('request', (req, res) => {
|
|
123
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
124
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
125
|
+
const url = new URL(req.url ?? '/', provider.redirectUrl);
|
|
126
|
+
const value = url.searchParams.get('code');
|
|
127
|
+
if (req.method !== 'GET' || req.headers.host !== `127.0.0.1:${address.port}` || url.pathname !== '/callback'
|
|
128
|
+
|| !provider.validState(url.searchParams.get('state')) || !value || url.searchParams.has('error')) {
|
|
129
|
+
res.writeHead(400);
|
|
130
|
+
res.end('Approval was not accepted. Return to your terminal and retry Connect.');
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
134
|
+
res.end('Connection approved. Return to your terminal.');
|
|
135
|
+
resolve(value);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
// A cached-token success never awaits the callback; prevent an unhandled
|
|
139
|
+
// rejection while its timer is being cancelled in finally.
|
|
140
|
+
void code.catch(() => undefined);
|
|
141
|
+
const transport = new StreamableHTTPClientTransport(new URL(RESOURCE), { authProvider: provider, fetch: safeFetch });
|
|
142
|
+
let client = new Client({ name: 'agentmesh-terminal', version: '0.2.0' });
|
|
143
|
+
try {
|
|
144
|
+
try {
|
|
145
|
+
await client.connect(transport);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (!(error instanceof UnauthorizedError) || !provider.authorizationStarted)
|
|
149
|
+
throw error;
|
|
150
|
+
await transport.finishAuth(await code);
|
|
151
|
+
await client.close();
|
|
152
|
+
client = new Client({ name: 'agentmesh-terminal', version: '0.2.0' });
|
|
153
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(RESOURCE), { authProvider: provider, fetch: safeFetch }));
|
|
154
|
+
}
|
|
155
|
+
return { client, redact: (value) => provider.redact(value), close: () => client.close() };
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
await client.close().catch(() => undefined);
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
clearTimeout(timer);
|
|
163
|
+
server.close();
|
|
164
|
+
}
|
|
165
|
+
}
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential redaction — PLAN §7 / RULE-10, defense in depth (build-QA B1).
|
|
3
|
+
*
|
|
4
|
+
* The `am_live_` key may appear ONLY in the outbound `Authorization` header; it
|
|
5
|
+
* must never reach stdout, stderr, a tool result, a returned error, or a stack.
|
|
6
|
+
* The wrapper does not fully control the strings it surfaces: an UPSTREAM error
|
|
7
|
+
* envelope message, an undici/fetch error, or a cancellation reason can echo the
|
|
8
|
+
* presented credential. So every string that is surfaced (a stderr log line, a
|
|
9
|
+
* tool-error text, a fatal diagnostic) is passed through redact() as a final,
|
|
10
|
+
* central scrub.
|
|
11
|
+
*
|
|
12
|
+
* The key is read from process.env directly (not from config.ts) so there is no
|
|
13
|
+
* import cycle with logger.ts/config.ts, and so redaction is available even on
|
|
14
|
+
* paths that run before config validation.
|
|
15
|
+
*/
|
|
16
|
+
import { currentRequestApiKey, currentRequestContext } from "./context.js";
|
|
17
|
+
const PLACEHOLDER = "[redacted-credential]";
|
|
18
|
+
/**
|
|
19
|
+
* Every credential currently in scope: the env-configured key (stdio's
|
|
20
|
+
* process-wide credential) plus, in http mode, the CURRENT request's
|
|
21
|
+
* presented key (context.ts) — an upstream error/body can echo whichever
|
|
22
|
+
* credential was on the outbound Authorization header, so both are scrub
|
|
23
|
+
* targets (1B PLAN §2, RULE-10).
|
|
24
|
+
*/
|
|
25
|
+
function secretsInScope() {
|
|
26
|
+
const secrets = [];
|
|
27
|
+
const envKey = process.env["AGENTMESH_API_KEY"];
|
|
28
|
+
if (envKey !== undefined && envKey.length > 0) {
|
|
29
|
+
secrets.push(envKey);
|
|
30
|
+
}
|
|
31
|
+
const requestKey = currentRequestApiKey();
|
|
32
|
+
if (requestKey !== undefined && requestKey.length > 0 && requestKey !== envKey) {
|
|
33
|
+
secrets.push(requestKey);
|
|
34
|
+
}
|
|
35
|
+
return [...secrets, ...(currentRequestContext()?.secrets ?? []).filter((value) => value.length > 0)];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Replace every occurrence of each in-scope credential in `text` with a
|
|
39
|
+
* fixed placeholder. A literal (non-regex) substring replace, so it also covers
|
|
40
|
+
* the `Bearer <key>` form (the key is a substring of it). Returns `text`
|
|
41
|
+
* unchanged when no credential is in scope. Never throws.
|
|
42
|
+
*/
|
|
43
|
+
export function redact(text) {
|
|
44
|
+
let out = text;
|
|
45
|
+
for (const key of secretsInScope()) {
|
|
46
|
+
out = redactWithKey(out, key);
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Return a deep, non-mutating copy of JSON-compatible `value` with the exact
|
|
52
|
+
* configured credential replaced in every string value and object key.
|
|
53
|
+
*
|
|
54
|
+
* Successful upstream data is untrusted too: a misconfigured or hostile
|
|
55
|
+
* upstream can echo the Authorization value in an otherwise schema-valid 2xx
|
|
56
|
+
* body. Scrub before output-schema validation so neither structuredContent nor
|
|
57
|
+
* its serialized text form can carry the credential. Redacting object keys as
|
|
58
|
+
* well as values also prevents a credential-bearing key from reaching an Ajv
|
|
59
|
+
* instancePath if the scrubbed object fails validation.
|
|
60
|
+
*/
|
|
61
|
+
export function redactDeep(value) {
|
|
62
|
+
const secrets = secretsInScope();
|
|
63
|
+
if (secrets.length === 0) {
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
return redactValue(value, secrets);
|
|
67
|
+
}
|
|
68
|
+
function redactValue(value, secrets) {
|
|
69
|
+
if (typeof value === "string") {
|
|
70
|
+
return redactAll(value, secrets);
|
|
71
|
+
}
|
|
72
|
+
if (Array.isArray(value)) {
|
|
73
|
+
return value.map((item) => redactValue(item, secrets));
|
|
74
|
+
}
|
|
75
|
+
if (typeof value === "object" && value !== null) {
|
|
76
|
+
return Object.fromEntries(Object.entries(value).map(([entryKey, entryValue]) => [
|
|
77
|
+
redactAll(entryKey, secrets),
|
|
78
|
+
redactValue(entryValue, secrets),
|
|
79
|
+
]));
|
|
80
|
+
}
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
function redactAll(text, secrets) {
|
|
84
|
+
let out = text;
|
|
85
|
+
for (const key of secrets) {
|
|
86
|
+
out = redactWithKey(out, key);
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
function redactWithKey(text, key) {
|
|
91
|
+
return text.split(key).join(PLACEHOLDER);
|
|
92
|
+
}
|
package/dist/schemas.js
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads the checked-in JSON Schema fixtures (../schemas/defs.json,
|
|
3
|
+
* ../schemas/tools.json — reviewed contracts; td-63fa2f adds human whoami
|
|
4
|
+
* to the original Appendix A agent branch without relaxing its validation)
|
|
5
|
+
* and exposes them as typed, ready-to-serve MCP tool definitions, plus
|
|
6
|
+
* compiled Ajv 2020-12 validators for each tool's outputSchema.
|
|
7
|
+
*
|
|
8
|
+
* Path resolution: schemas are loaded relative to THIS file via
|
|
9
|
+
* `import.meta.url`, not `process.cwd()`. Both `src/schemas.ts` (pre-build)
|
|
10
|
+
* and the compiled `dist/schemas.js` (post-`tsc`) live exactly one
|
|
11
|
+
* directory below `mcp/`, so `new URL("../schemas/...", import.meta.url)`
|
|
12
|
+
* resolves to `mcp/schemas/...` correctly from either location.
|
|
13
|
+
*
|
|
14
|
+
* $defs wiring: PLAN Appendix A specifies that the build inserts the shared
|
|
15
|
+
* $defs object (card/message/channel/ask) as EVERY outputSchema's own
|
|
16
|
+
* `$defs` before registration, so every `"$ref": "#/$defs/..."` resolves
|
|
17
|
+
* locally within the registered schema. Verified against the real fixture
|
|
18
|
+
* files: all 9 outputSchemas compile under Ajv2020 with this injection, and
|
|
19
|
+
* $ref-bearing schemas (e.g. post_message -> #/$defs/message) validate
|
|
20
|
+
* correctly both positively and negatively.
|
|
21
|
+
*
|
|
22
|
+
* Schema guard (Seam C, td-7dd275 — 2026-07-28 protocol requirements):
|
|
23
|
+
* before anything is compiled or served, `guardSchemaDocuments` refuses
|
|
24
|
+
* (1) any `$ref` that would resolve outside the checked-in schema
|
|
25
|
+
* documents — absolute/scheme'd URIs, protocol-relative URLs,
|
|
26
|
+
* cross-file references, plain-name fragments. Only same-document
|
|
27
|
+
* JSON-pointer refs ("#/...") that actually resolve within the unit
|
|
28
|
+
* being served are allowed, and nothing is EVER auto-dereferenced
|
|
29
|
+
* from the network;
|
|
30
|
+
* (2) base-URI / dynamic-scope keywords ($id, $anchor, $dynamicRef,
|
|
31
|
+
* $dynamicAnchor, $vocabulary) that could smuggle out-of-document
|
|
32
|
+
* resolution, and any non-2020-12 $schema;
|
|
33
|
+
* (3) non-object tool schema roots — every inputSchema root MUST declare
|
|
34
|
+
* type:"object" (2026-07-28 requirement; outputSchema likewise, since
|
|
35
|
+
* structuredContent is always an object);
|
|
36
|
+
* (4) pathological documents, with hard bounds on nesting depth, total
|
|
37
|
+
* node count, $ref hop chains/cycles, and wall-clock guard time
|
|
38
|
+
* (SCHEMA_GUARD_BOUNDS).
|
|
39
|
+
* The guard only READS: the served bytes remain the exact checked-in
|
|
40
|
+
* fixtures (with the one $defs injection above) — the verbatim-serving
|
|
41
|
+
* property of the low-level Server is preserved. A violation throws
|
|
42
|
+
* SchemaGuardError at module load, refusing boot loudly (stderr) before any
|
|
43
|
+
* transport serves a single schema.
|
|
44
|
+
*/
|
|
45
|
+
import { readFileSync } from "node:fs";
|
|
46
|
+
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
47
|
+
import addFormatsDefault from "ajv-formats";
|
|
48
|
+
// ---- ajv-formats CJS/ESM interop ----
|
|
49
|
+
// ajv-formats is a CJS package with a default export. Under Node's ESM interop
|
|
50
|
+
// the DEFAULT import binding is the callable plugin at RUNTIME; the whole-
|
|
51
|
+
// namespace object (`import * as`) is an object, NOT callable (verified at
|
|
52
|
+
// runtime). We therefore import the default and pin its call signature with a
|
|
53
|
+
// minimal cast under NodeNext. (Ajv2020 above is a genuine named export, which
|
|
54
|
+
// has no such interop gap.)
|
|
55
|
+
const addFormats = addFormatsDefault;
|
|
56
|
+
const defsUrl = new URL("../schemas/defs.json", import.meta.url);
|
|
57
|
+
const toolsUrl = new URL("../schemas/tools.json", import.meta.url);
|
|
58
|
+
/** The shared $defs object (card/message/channel/ask) injected into every outputSchema. */
|
|
59
|
+
const defs = JSON.parse(readFileSync(defsUrl, "utf8"));
|
|
60
|
+
const rawTools = JSON.parse(readFileSync(toolsUrl, "utf8"));
|
|
61
|
+
/** The tool names, exactly as keyed in ../schemas/tools.json. */
|
|
62
|
+
export const TOOL_NAMES = [
|
|
63
|
+
"read_board",
|
|
64
|
+
"read_channels",
|
|
65
|
+
"read_messages",
|
|
66
|
+
"list_asks",
|
|
67
|
+
"whoami",
|
|
68
|
+
"post_message",
|
|
69
|
+
"claim_card",
|
|
70
|
+
"complete_card",
|
|
71
|
+
"create_card",
|
|
72
|
+
"read_roster",
|
|
73
|
+
"list_conversations",
|
|
74
|
+
"create_conversation",
|
|
75
|
+
"read_conversation_messages",
|
|
76
|
+
"post_conversation_message",
|
|
77
|
+
];
|
|
78
|
+
/** Additional tools are exposed only by the private hosted entry. */
|
|
79
|
+
export const HOSTED_TOOL_NAMES = [...TOOL_NAMES,
|
|
80
|
+
"terminal_wake_start",
|
|
81
|
+
"terminal_wake_poll",
|
|
82
|
+
"terminal_wake_receipt",
|
|
83
|
+
"terminal_wake_checkin",
|
|
84
|
+
"get_my_instructions",
|
|
85
|
+
"edit_card",
|
|
86
|
+
"assign_card",
|
|
87
|
+
"create_ask",
|
|
88
|
+
"claim_ask",
|
|
89
|
+
"resolve_ask",
|
|
90
|
+
"list_documents",
|
|
91
|
+
"read_document",
|
|
92
|
+
"create_document",
|
|
93
|
+
"edit_document",
|
|
94
|
+
];
|
|
95
|
+
export class SchemaGuardError extends Error {
|
|
96
|
+
code;
|
|
97
|
+
constructor(code, detail) {
|
|
98
|
+
super(`agentmesh-mcp: SCHEMA_GUARD ${code}: ${detail}`);
|
|
99
|
+
this.name = "SchemaGuardError";
|
|
100
|
+
this.code = code;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Hard constants (deliberately NOT env-tunable — an env override would be a
|
|
105
|
+
* weakening vector). Real documents measure ~12 deep / ~6k walked nodes /
|
|
106
|
+
* 1 ref hop / <20ms; the bounds refuse pathological documents while leaving
|
|
107
|
+
* comfortable headroom for legitimate schema evolution.
|
|
108
|
+
*/
|
|
109
|
+
export const SCHEMA_GUARD_BOUNDS = Object.freeze({
|
|
110
|
+
maxDepth: 64,
|
|
111
|
+
maxNodes: 20000,
|
|
112
|
+
maxRefHops: 32,
|
|
113
|
+
timeBudgetMs: 1000,
|
|
114
|
+
});
|
|
115
|
+
/** defs.json must define exactly these shared definitions (PLAN Appendix A). */
|
|
116
|
+
const EXPECTED_DEF_KEYS = Object.freeze([
|
|
117
|
+
"ask", "card", "channel", "conversation", "conversation_message", "message",
|
|
118
|
+
]);
|
|
119
|
+
/**
|
|
120
|
+
* Base-URI / dynamic-scope keywords are refused outright: $id and $anchor
|
|
121
|
+
* re-root reference resolution (a relative $ref under a remote $id becomes an
|
|
122
|
+
* EXTERNAL fetch target), and $dynamicRef/$dynamicAnchor/$vocabulary move
|
|
123
|
+
* resolution out of the lexical document. None are used by the checked-in
|
|
124
|
+
* fixtures; refusing them is the fail-closed reading of the 2026-07-28
|
|
125
|
+
* "never auto-dereference external $ref URIs" requirement.
|
|
126
|
+
*/
|
|
127
|
+
const FORBIDDEN_SCHEMA_KEYWORDS = Object.freeze([
|
|
128
|
+
"$id",
|
|
129
|
+
"$anchor",
|
|
130
|
+
"$dynamicRef",
|
|
131
|
+
"$dynamicAnchor",
|
|
132
|
+
"$vocabulary",
|
|
133
|
+
]);
|
|
134
|
+
const ALLOWED_META_SCHEMA = "https://json-schema.org/draft/2020-12/schema";
|
|
135
|
+
function isPlainObject(v) {
|
|
136
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
137
|
+
}
|
|
138
|
+
/** Validates the FORM of one $ref value; returns it when it is a same-document JSON pointer. */
|
|
139
|
+
function checkRefForm(ref, at) {
|
|
140
|
+
if (typeof ref !== "string") {
|
|
141
|
+
throw new SchemaGuardError("REF_NOT_STRING", `$ref at ${at} is ${typeof ref}, not a string`);
|
|
142
|
+
}
|
|
143
|
+
if (ref.startsWith("#/")) {
|
|
144
|
+
return ref;
|
|
145
|
+
}
|
|
146
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(ref) || ref.startsWith("//")) {
|
|
147
|
+
throw new SchemaGuardError("EXTERNAL_REF", `$ref at ${at} points outside the checked-in schema documents and is never auto-dereferenced: ${JSON.stringify(ref)}`);
|
|
148
|
+
}
|
|
149
|
+
throw new SchemaGuardError("NON_POINTER_REF", `$ref at ${at} is not a same-document JSON pointer ("#/..."): ${JSON.stringify(ref)}`);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Iterative (stack-based, recursion-free) bounded walk of one JSON value:
|
|
153
|
+
* enforces depth/node/time bounds and keyword/$ref-form rules, and returns
|
|
154
|
+
* every $ref encountered so the caller can resolve them per served unit.
|
|
155
|
+
*/
|
|
156
|
+
function walkBounded(root, label, ctx) {
|
|
157
|
+
const refs = [];
|
|
158
|
+
const stack = [{ value: root, depth: 1, at: label }];
|
|
159
|
+
while (stack.length > 0) {
|
|
160
|
+
const item = stack.pop();
|
|
161
|
+
if (item === undefined) {
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
ctx.nodes += 1;
|
|
165
|
+
if (ctx.nodes > ctx.bounds.maxNodes) {
|
|
166
|
+
throw new SchemaGuardError("NODE_BOUND", `schema documents exceed the ${ctx.bounds.maxNodes}-node budget (at ${item.at})`);
|
|
167
|
+
}
|
|
168
|
+
if (ctx.now() > ctx.deadline) {
|
|
169
|
+
throw new SchemaGuardError("TIME_BOUND", `schema guard exceeded its ${ctx.bounds.timeBudgetMs}ms budget (at ${item.at})`);
|
|
170
|
+
}
|
|
171
|
+
if (item.depth > ctx.bounds.maxDepth) {
|
|
172
|
+
throw new SchemaGuardError("DEPTH_BOUND", `schema nesting exceeds depth ${ctx.bounds.maxDepth} at ${item.at}`);
|
|
173
|
+
}
|
|
174
|
+
const v = item.value;
|
|
175
|
+
if (Array.isArray(v)) {
|
|
176
|
+
for (let i = 0; i < v.length; i += 1) {
|
|
177
|
+
stack.push({ value: v[i], depth: item.depth + 1, at: `${item.at}/${i}` });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else if (isPlainObject(v)) {
|
|
181
|
+
for (const key of Object.keys(v)) {
|
|
182
|
+
if (FORBIDDEN_SCHEMA_KEYWORDS.includes(key)) {
|
|
183
|
+
throw new SchemaGuardError("FORBIDDEN_KEYWORD", `${key} at ${item.at} is refused: base-URI/dynamic-scope keywords enable out-of-document resolution`);
|
|
184
|
+
}
|
|
185
|
+
if (key === "$schema" && v[key] !== ALLOWED_META_SCHEMA) {
|
|
186
|
+
throw new SchemaGuardError("META_SCHEMA_MISMATCH", `$schema at ${item.at} must be ${JSON.stringify(ALLOWED_META_SCHEMA)}, got ${JSON.stringify(v[key])}`);
|
|
187
|
+
}
|
|
188
|
+
if (key === "$ref") {
|
|
189
|
+
refs.push({ at: item.at, ref: checkRefForm(v[key], item.at) });
|
|
190
|
+
}
|
|
191
|
+
stack.push({ value: v[key], depth: item.depth + 1, at: `${item.at}/${key}` });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return refs;
|
|
196
|
+
}
|
|
197
|
+
/** RFC 6901 resolution of a "#/..."-form pointer against one served unit. Never fetches. */
|
|
198
|
+
function resolveJsonPointer(root, pointer) {
|
|
199
|
+
const parts = pointer
|
|
200
|
+
.slice(2)
|
|
201
|
+
.split("/")
|
|
202
|
+
.map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
203
|
+
let cur = root;
|
|
204
|
+
for (const part of parts) {
|
|
205
|
+
if (isPlainObject(cur) && Object.prototype.hasOwnProperty.call(cur, part)) {
|
|
206
|
+
cur = cur[part];
|
|
207
|
+
}
|
|
208
|
+
else if (Array.isArray(cur) && /^(0|[1-9][0-9]*)$/.test(part) && Number(part) < cur.length) {
|
|
209
|
+
cur = cur[Number(part)];
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
return { found: false, value: undefined };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { found: true, value: cur };
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Resolves every collected $ref INSIDE the unit that is actually served,
|
|
219
|
+
* following pure-$ref indirection with a hop bound and cycle refusal. A
|
|
220
|
+
* pointer that leaves the unit, or a chain that cycles or exceeds the hop
|
|
221
|
+
* bound, is refused — resolution can never reach outside the checked-in
|
|
222
|
+
* documents, by construction.
|
|
223
|
+
*/
|
|
224
|
+
function chaseRefs(unitRoot, refs, unitLabel, ctx) {
|
|
225
|
+
for (const { at, ref } of refs) {
|
|
226
|
+
let current = ref;
|
|
227
|
+
const seen = new Set();
|
|
228
|
+
for (let hops = 1;; hops += 1) {
|
|
229
|
+
if (ctx.now() > ctx.deadline) {
|
|
230
|
+
throw new SchemaGuardError("TIME_BOUND", `schema guard exceeded its ${ctx.bounds.timeBudgetMs}ms budget resolving $ref at ${at}`);
|
|
231
|
+
}
|
|
232
|
+
if (hops > ctx.bounds.maxRefHops) {
|
|
233
|
+
throw new SchemaGuardError("REF_HOP_BOUND", `$ref chain starting at ${at} exceeds ${ctx.bounds.maxRefHops} hops in ${unitLabel}`);
|
|
234
|
+
}
|
|
235
|
+
if (seen.has(current)) {
|
|
236
|
+
throw new SchemaGuardError("REF_CYCLE", `$ref chain starting at ${at} cycles on ${JSON.stringify(current)} in ${unitLabel}`);
|
|
237
|
+
}
|
|
238
|
+
seen.add(current);
|
|
239
|
+
const resolved = resolveJsonPointer(unitRoot, current);
|
|
240
|
+
if (!resolved.found) {
|
|
241
|
+
throw new SchemaGuardError("UNRESOLVED_REF", `$ref ${JSON.stringify(current)} (from ${at}) does not resolve within ${unitLabel}`);
|
|
242
|
+
}
|
|
243
|
+
if (isPlainObject(resolved.value) && Object.prototype.hasOwnProperty.call(resolved.value, "$ref")) {
|
|
244
|
+
current = checkRefForm(resolved.value["$ref"], `${unitLabel} -> ${current}`);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* The whole guard pass over the two checked-in documents. READ-ONLY: never
|
|
253
|
+
* mutates its inputs; the $defs composite below is a fresh spread mirroring
|
|
254
|
+
* (not performing) buildToolDef's injection. Throws SchemaGuardError on the
|
|
255
|
+
* first violation; returns void when the documents are safe to compile+serve.
|
|
256
|
+
*/
|
|
257
|
+
export function guardSchemaDocuments(defsDoc, toolsDoc, options) {
|
|
258
|
+
const bounds = Object.freeze({ ...SCHEMA_GUARD_BOUNDS, ...(options?.bounds ?? {}) });
|
|
259
|
+
const now = options?.now ?? (() => performance.now());
|
|
260
|
+
const ctx = { bounds, now, deadline: now() + bounds.timeBudgetMs, nodes: 0 };
|
|
261
|
+
if (!isPlainObject(defsDoc)) {
|
|
262
|
+
throw new SchemaGuardError("DOC_NOT_OBJECT", "defs.json root is not a JSON object");
|
|
263
|
+
}
|
|
264
|
+
if (!isPlainObject(toolsDoc)) {
|
|
265
|
+
throw new SchemaGuardError("DOC_NOT_OBJECT", "tools.json root is not a JSON object");
|
|
266
|
+
}
|
|
267
|
+
const defKeys = Object.keys(defsDoc).sort();
|
|
268
|
+
if (defKeys.length !== EXPECTED_DEF_KEYS.length || defKeys.some((k, i) => k !== EXPECTED_DEF_KEYS[i])) {
|
|
269
|
+
throw new SchemaGuardError("DEFS_KEY_MISMATCH", `defs.json must define exactly [${EXPECTED_DEF_KEYS.join(", ")}]; found [${defKeys.join(", ")}]`);
|
|
270
|
+
}
|
|
271
|
+
const toolKeys = Object.keys(toolsDoc).sort();
|
|
272
|
+
const expectedToolKeys = [...HOSTED_TOOL_NAMES].sort();
|
|
273
|
+
if (toolKeys.length !== expectedToolKeys.length || toolKeys.some((k, i) => k !== expectedToolKeys[i])) {
|
|
274
|
+
throw new SchemaGuardError("TOOLS_KEY_MISMATCH", `tools.json must define exactly the ${HOSTED_TOOL_NAMES.length} served tools; found [${toolKeys.join(", ")}]`);
|
|
275
|
+
}
|
|
276
|
+
// Surface shape + object-root enforcement (2026-07-28) per tool, before any
|
|
277
|
+
// deep walk so a malformed entry is named precisely.
|
|
278
|
+
for (const name of HOSTED_TOOL_NAMES) {
|
|
279
|
+
const entry = toolsDoc[name];
|
|
280
|
+
if (!isPlainObject(entry)) {
|
|
281
|
+
throw new SchemaGuardError("MALFORMED_TOOL_ENTRY", `tools.json entry "${name}" is not an object`);
|
|
282
|
+
}
|
|
283
|
+
const input = entry["inputSchema"];
|
|
284
|
+
const output = entry["outputSchema"];
|
|
285
|
+
if (!isPlainObject(input)) {
|
|
286
|
+
throw new SchemaGuardError("MALFORMED_TOOL_ENTRY", `"${name}".inputSchema is not a schema object (boolean/array/missing forms are refused)`);
|
|
287
|
+
}
|
|
288
|
+
if (!isPlainObject(output)) {
|
|
289
|
+
throw new SchemaGuardError("MALFORMED_TOOL_ENTRY", `"${name}".outputSchema is not a schema object (boolean/array/missing forms are refused)`);
|
|
290
|
+
}
|
|
291
|
+
if (Object.prototype.hasOwnProperty.call(input, "$defs")) {
|
|
292
|
+
throw new SchemaGuardError("MALFORMED_TOOL_ENTRY", `"${name}".inputSchema carries its own $defs; shared definitions live only in defs.json`);
|
|
293
|
+
}
|
|
294
|
+
if (Object.prototype.hasOwnProperty.call(output, "$defs")) {
|
|
295
|
+
throw new SchemaGuardError("MALFORMED_TOOL_ENTRY", `"${name}".outputSchema carries its own $defs; it would be clobbered by the defs.json injection`);
|
|
296
|
+
}
|
|
297
|
+
if (input["type"] !== "object") {
|
|
298
|
+
throw new SchemaGuardError("INPUT_ROOT_NOT_OBJECT", `"${name}".inputSchema root must declare type:"object" (2026-07-28 requirement); got ${JSON.stringify(input["type"])}`);
|
|
299
|
+
}
|
|
300
|
+
if (output["type"] !== "object") {
|
|
301
|
+
throw new SchemaGuardError("OUTPUT_ROOT_NOT_OBJECT", `"${name}".outputSchema root must declare type:"object" (structuredContent is always an object); got ${JSON.stringify(output["type"])}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
// Bounded walks over the raw documents: depth/node/time bounds, $ref form,
|
|
305
|
+
// forbidden keywords — everywhere, including any nook resolution never reaches.
|
|
306
|
+
walkBounded(defsDoc, "defs.json", ctx);
|
|
307
|
+
walkBounded(toolsDoc, "tools.json", ctx);
|
|
308
|
+
// Per-served-unit resolution: inputSchema is served VERBATIM (no injection),
|
|
309
|
+
// so its refs must resolve within itself alone; outputSchema is served with
|
|
310
|
+
// defs.json injected at $defs, so its refs resolve against that composite.
|
|
311
|
+
for (const name of HOSTED_TOOL_NAMES) {
|
|
312
|
+
const entry = toolsDoc[name];
|
|
313
|
+
const input = entry["inputSchema"];
|
|
314
|
+
const output = entry["outputSchema"];
|
|
315
|
+
const inputRefs = walkBounded(input, `${name}.inputSchema`, ctx);
|
|
316
|
+
chaseRefs(input, inputRefs, `${name}.inputSchema (served verbatim, no $defs injection)`, ctx);
|
|
317
|
+
const composite = { ...output, $defs: defsDoc };
|
|
318
|
+
const outputRefs = walkBounded(composite, `${name}.outputSchema+$defs`, ctx);
|
|
319
|
+
chaseRefs(composite, outputRefs, `${name}.outputSchema (with injected $defs)`, ctx);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// Loader-time enforcement (Seam C, td-7dd275): refuse to compile or serve
|
|
323
|
+
// schema documents that violate the 2026-07-28 requirements. Throwing here
|
|
324
|
+
// crashes boot loudly (stderr) before any transport serves a single schema —
|
|
325
|
+
// the same fail-closed posture as config.ts. The V4 control proves this
|
|
326
|
+
// wiring on the shipped dist by importing a scratch copy with seeded
|
|
327
|
+
// violations in its schemas/ and asserting the import itself refuses.
|
|
328
|
+
guardSchemaDocuments(defs, rawTools);
|
|
329
|
+
function getRawTool(name) {
|
|
330
|
+
const entry = rawTools[name];
|
|
331
|
+
if (entry === undefined) {
|
|
332
|
+
// Fixture/code drift, not a user-input error -- fail loudly at startup.
|
|
333
|
+
throw new Error(`agentmesh-mcp: mcp/schemas/tools.json has no entry for tool "${name}"`);
|
|
334
|
+
}
|
|
335
|
+
return entry;
|
|
336
|
+
}
|
|
337
|
+
function buildToolDef(name, description) {
|
|
338
|
+
const raw = getRawTool(name);
|
|
339
|
+
// "the build inserts this object as the schema root's $defs before
|
|
340
|
+
// registration" (PLAN Appendix A) -- mutates our in-memory parsed copy of
|
|
341
|
+
// the JSON, never the checked-in file on disk.
|
|
342
|
+
raw.outputSchema["$defs"] = defs;
|
|
343
|
+
return {
|
|
344
|
+
description,
|
|
345
|
+
inputSchema: raw.inputSchema,
|
|
346
|
+
outputSchema: raw.outputSchema,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
/** Name -> {description, inputSchema, outputSchema-with-$defs}, ready to serve from ListTools. */
|
|
350
|
+
export const TOOL_DEFS = {
|
|
351
|
+
terminal_wake_start: buildToolDef("terminal_wake_start", "Start an own-agent terminal wake generation; launcher only."),
|
|
352
|
+
terminal_wake_poll: buildToolDef("terminal_wake_poll", "Lease pending own-agent wake references; no message content or recipient selectors."),
|
|
353
|
+
terminal_wake_receipt: buildToolDef("terminal_wake_receipt", "Acknowledge receipt of this event in this exact terminal connection. Stage agent means the model received it; transport alone is not acknowledgement."),
|
|
354
|
+
terminal_wake_checkin: buildToolDef("terminal_wake_checkin", "Record bound terminal process heartbeat or closure; launcher only."),
|
|
355
|
+
read_board: buildToolDef("read_board", "Read the AgentMesh board: its columns and the cards in each column."),
|
|
356
|
+
read_channels: buildToolDef("read_channels", "List every AgentMesh channel."),
|
|
357
|
+
read_messages: buildToolDef("read_messages", "Read messages from an AgentMesh channel, newest first, with cursor pagination via before_id."),
|
|
358
|
+
list_asks: buildToolDef("list_asks", "List AgentMesh asks (help requests), optionally filtered by state."),
|
|
359
|
+
get_my_instructions: buildToolDef("get_my_instructions", "Read your current owner-provided instructions; native agent connections only."),
|
|
360
|
+
whoami: buildToolDef("whoami", "Return the identity, workspace, and scopes of the authenticated AgentMesh agent."),
|
|
361
|
+
post_message: buildToolDef("post_message", 'Post a message to an AgentMesh channel (defaults to "general").'),
|
|
362
|
+
claim_card: buildToolDef("claim_card", "Claim an open AgentMesh board card so this agent owns it."),
|
|
363
|
+
complete_card: buildToolDef("complete_card", "Mark a claimed AgentMesh board card as done."),
|
|
364
|
+
create_card: buildToolDef("create_card", "Create a new card on the AgentMesh board."),
|
|
365
|
+
read_roster: buildToolDef("read_roster", "Read the workspace roster for direct-conversation participant selection."),
|
|
366
|
+
list_conversations: buildToolDef("list_conversations", "List this agent's private conversations with cursor pagination."),
|
|
367
|
+
create_conversation: buildToolDef("create_conversation", "Create a private conversation with existing workspace participants."),
|
|
368
|
+
read_conversation_messages: buildToolDef("read_conversation_messages", "Read a private conversation's messages with cursor pagination."),
|
|
369
|
+
post_conversation_message: buildToolDef("post_conversation_message", "Post a message to a private conversation."),
|
|
370
|
+
edit_card: buildToolDef("edit_card", "Replace a card title and markdown description (including acceptance criteria). Read the existing card before editing; body_md replaces the whole description."),
|
|
371
|
+
assign_card: buildToolDef("assign_card", "Assign an open, unclaimed card to an eligible workspace human or agent. Existing assignment conflicts and eligibility rules remain authoritative."),
|
|
372
|
+
create_ask: buildToolDef("create_ask", "Create a Needs You help request in the connected workspace."),
|
|
373
|
+
claim_ask: buildToolDef("claim_ask", "Claim an open Needs You request for the current identity. Required before a member can resolve their own request."),
|
|
374
|
+
resolve_ask: buildToolDef("resolve_ask", "Resolve an already claimed Needs You request. Only its claimant or an existing human approver/owner can resolve it."),
|
|
375
|
+
list_documents: buildToolDef("list_documents", "List document metadata in the connected workspace; bodies are returned by read_document."),
|
|
376
|
+
read_document: buildToolDef("read_document", "Read a connected-workspace document and its current version before editing."),
|
|
377
|
+
create_document: buildToolDef("create_document", "Create a document using the existing API; server derives the author and first version."),
|
|
378
|
+
edit_document: buildToolDef("edit_document", "Append a document version using expected_version from read_document. A stale version, trashed document or destructive clear is rejected by the existing API."),
|
|
379
|
+
};
|
|
380
|
+
// ---- Ajv 2020-12 output validation ----
|
|
381
|
+
const ajv = new Ajv2020({ strict: true, allErrors: true });
|
|
382
|
+
addFormats(ajv);
|
|
383
|
+
const compiledValidators = new Map();
|
|
384
|
+
for (const name of HOSTED_TOOL_NAMES) {
|
|
385
|
+
compiledValidators.set(name, ajv.compile(TOOL_DEFS[name].outputSchema));
|
|
386
|
+
}
|
|
387
|
+
/** Look up the compiled Ajv validator for a tool's outputSchema. */
|
|
388
|
+
export function validateOutput(name) {
|
|
389
|
+
const fn = compiledValidators.get(name);
|
|
390
|
+
if (fn === undefined) {
|
|
391
|
+
// Unreachable in practice: compiledValidators is populated above for
|
|
392
|
+
// every member of HOSTED_TOOL_NAMES, and `name` is typed as ToolName.
|
|
393
|
+
throw new Error(`agentmesh-mcp: no compiled output validator for tool "${name}"`);
|
|
394
|
+
}
|
|
395
|
+
return fn;
|
|
396
|
+
}
|
|
397
|
+
// ---- Ajv 2020-12 INPUT validation ----
|
|
398
|
+
// The low-level Server does NOT auto-validate tool arguments, so server.ts compiles
|
|
399
|
+
// and enforces each tool's inputSchema before dispatch — rejecting invalid args as a
|
|
400
|
+
// tool error BEFORE any upstream call or URL construction (e.g. a non-UUID card_id
|
|
401
|
+
// is caught here rather than throwing inside encodeURIComponent).
|
|
402
|
+
const compiledInputValidators = new Map();
|
|
403
|
+
for (const name of HOSTED_TOOL_NAMES) {
|
|
404
|
+
compiledInputValidators.set(name, ajv.compile(TOOL_DEFS[name].inputSchema));
|
|
405
|
+
}
|
|
406
|
+
/** Look up the compiled Ajv validator for a tool's inputSchema. */
|
|
407
|
+
export function validateInput(name) {
|
|
408
|
+
const fn = compiledInputValidators.get(name);
|
|
409
|
+
if (fn === undefined) {
|
|
410
|
+
throw new Error(`agentmesh-mcp: no compiled input validator for tool "${name}"`);
|
|
411
|
+
}
|
|
412
|
+
return fn;
|
|
413
|
+
}
|