Repository navigation
Expand file tree
/
Copy pathcapability-probe.server.ts
More file actions
516 lines (485 loc) · 19.2 KB
/
Copy pathcapability-probe.server.ts
File metadata and controls
516 lines (485 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/**
* Capability probes — the layer above a plain liveness ping.
*
* An HTTP 200 only proves a host answers. A capability probe tries to prove the
* interface actually exposes what it claims: MCP servers are asked for their
* tool list over JSON-RPC, HTTP APIs must answer with a machine-readable
* contract (JSON) or an explicit auth challenge, which is the correct behaviour
* for a gated endpoint.
*/
const TIMEOUT_MS = 10_000;
export type CapabilityProbe = {
probeable: boolean;
ok: boolean | null;
detail: string;
tools: string[];
/** MCP protocol version the server agreed to in initialize. */
protocolVersion?: string | null;
/** Declared input/output schema per tool, as returned by tools/list. */
toolSchemas?: Record<string, ToolSchema>;
/** True when a nextCursor was returned but a later page could not be read: the tool list is partial. */
paginationTruncated?: boolean;
};
export type ToolSchema = { input: unknown; output: unknown };
const notProbeable = (detail: string): CapabilityProbe => ({
probeable: false,
ok: null,
detail,
tools: [],
});
function isHttp(endpoint: string) {
return /^https?:\/\//i.test(endpoint.trim());
}
/**
* A probe runs from our own server, so a listed endpoint pointing at a loopback,
* private, link-local or cloud-metadata address would turn the probe into an
* internal-network request (SSRF) whose response is echoed into a public entry.
* Only public, name-or-public-IP http(s) targets are probeable.
*/
export function isPublicHttpTarget(url: string): boolean {
let parsed: URL;
try {
parsed = new URL(url.trim());
} catch {
return false;
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
// Embedded credentials are never needed for a probe and are a classic way to
// confuse host parsing.
if (parsed.username || parsed.password) return false;
let host = parsed.hostname.toLowerCase();
if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
if (
host === "localhost" ||
host.endsWith(".localhost") ||
host.endsWith(".local") ||
host.endsWith(".internal") ||
host.endsWith(".lan") ||
host.endsWith(".home.arpa") ||
host === "metadata.google.internal" ||
host === "instance-data"
) {
return false;
}
// IPv4 literal
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
if (v4) {
const [a, b] = [Number(v4[1]), Number(v4[2])];
if ([a, Number(v4[3]), Number(v4[4])].some((n) => n > 255) || b > 255) return false;
if (a === 0 || a === 10 || a === 127) return false; // this-network, private, loopback
if (a === 169 && b === 254) return false; // link-local incl. cloud metadata 169.254.169.254
if (a === 172 && b >= 16 && b <= 31) return false; // private
if (a === 192 && b === 168) return false; // private
if (a === 192 && b === 0) return false; // 192.0.0.0/24 protocol assignments
if (a === 100 && b >= 64 && b <= 127) return false; // carrier-grade NAT
if (a === 198 && (b === 18 || b === 19)) return false; // benchmarking
if (a >= 224) return false; // multicast + reserved
return true;
}
// Any other numeric / IPv6-ish literal: allow only clearly public IPv6.
if (host.includes(":")) {
if (
host === "::" ||
host === "::1" ||
host.startsWith("fe80") ||
host.startsWith("fc") ||
host.startsWith("fd") ||
host.startsWith("::ffff:") ||
host.startsWith("64:ff9b:")
) {
return false;
}
return true;
}
// Decimal/octal/hex-encoded IPv4 forms (e.g. 2130706433) bypass the checks above.
if (/^[0-9]+$/.test(host) || /^0x[0-9a-f]+$/.test(host)) return false;
// Must look like a real DNS name.
return host.includes(".") && !host.endsWith(".");
}
/** `{baseId}` / `<project-ref>` style endpoints are templates, not callable URLs. */
export function hasPlaceholder(endpoint: string) {
return /[{<][^{}<>\s]+[}>]/.test(endpoint);
}
async function withTimeout<T>(run: (signal: AbortSignal) => Promise<T>): Promise<T> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
return await run(controller.signal);
} finally {
clearTimeout(timer);
}
}
export function readNextCursor(payload: unknown): string | null {
const c = (payload as { result?: { nextCursor?: unknown } } | null)?.result?.nextCursor;
return typeof c === "string" && c.length > 0 ? c : null;
}
/** JSON-RPC `tools/list` against a streamable-HTTP or SSE MCP endpoint. */
async function probeMcp(endpoint: string): Promise<CapabilityProbe> {
const call = (body: unknown, signal: AbortSignal) =>
fetch(endpoint, {
method: "POST",
// No redirect following: a hop could land on an internal address.
redirect: "manual",
signal,
headers: {
"content-type": "application/json",
accept: "application/json, text/event-stream",
"user-agent": "AgentNexus-CapabilityProbe/1.0",
},
body: JSON.stringify(body),
});
try {
return await withTimeout(async (signal) => {
const init = await call(
{
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "agent-nexus-probe", version: "1.0" },
},
},
signal,
).catch(() => null);
let protocolVersion: string | null = null;
if (init && init.ok) {
const initPayload = parseJsonRpc((await init.text().catch(() => "")).slice(0, 50_000));
protocolVersion = readProtocolVersion(initPayload);
}
const response = await call({ jsonrpc: "2.0", id: 2, method: "tools/list" }, signal);
const text = (await response.text()).slice(0, 200_000);
if (response.status === 401 || response.status === 403) {
return {
probeable: true,
ok: true,
detail: `Reachable, authentication required (HTTP ${response.status})`,
tools: [],
};
}
const payload = parseJsonRpc(text);
const tools = extractToolNames(payload);
const toolSchemas: Record<string, ToolSchema> = extractToolSchemas(payload);
if (tools.length > 0) {
// MCP 2025-06-18: tools/list is paginated. Follow nextCursor to the end
// (bounded) so a tool on page two never looks like capability loss.
let pages = 1;
let cursor = readNextCursor(payload);
const seen = new Set<string>();
let truncated = false;
while (cursor && pages < 20 && !seen.has(cursor)) {
seen.add(cursor);
const next = await call(
{ jsonrpc: "2.0", id: 2 + pages, method: "tools/list", params: { cursor } },
signal,
).catch(() => null);
if (!next || !next.ok) { truncated = true; break; }
const nextPayload = parseJsonRpc((await next.text().catch(() => "")).slice(0, 200_000));
if (!nextPayload || (typeof nextPayload === "object" && "error" in nextPayload)) { truncated = true; break; }
for (const name of extractToolNames(nextPayload)) {
if (!tools.includes(name)) tools.push(name);
}
Object.assign(toolSchemas, extractToolSchemas(nextPayload));
pages += 1;
cursor = readNextCursor(nextPayload);
}
// A cursor still pending after the loop (page cap or repeated cursor) is also a partial check.
if (cursor) truncated = true;
if (truncated) {
return {
probeable: true,
ok: true,
detail: `PARTIAL: only ${pages} page${pages > 1 ? "s" : ""} of tools/list checked (pagination failed); ${tools.length} tool${tools.length > 1 ? "s" : ""} seen${protocolVersion ? ` (protocol ${protocolVersion})` : ""}`,
tools,
protocolVersion,
toolSchemas,
paginationTruncated: true,
};
}
return {
probeable: true,
ok: true,
detail: `tools/list returned ${tools.length} tool${tools.length > 1 ? "s" : ""}${pages > 1 ? ` across ${pages} pages` : ""}${protocolVersion ? ` (protocol ${protocolVersion})` : ""}`,
tools,
protocolVersion,
toolSchemas,
};
}
if (payload && typeof payload === "object" && "error" in payload) {
const message = String(
(payload as { error?: { message?: string } }).error?.message ?? "unknown",
);
// A session/initialize requirement is correct MCP behaviour, not a failure.
if (/session|initialize|not initialized/i.test(message)) {
return {
probeable: true,
ok: true,
detail: "Reachable, MCP session handshake required before tools/list",
tools: [],
};
}
return {
probeable: true,
ok: false,
detail: `JSON-RPC error: ${message.slice(0, 160)}`,
tools: [],
};
}
if (response.status === 404 || response.status === 405) {
return {
probeable: true,
ok: null,
detail: `Endpoint answered HTTP ${response.status} to tools/list — transport may differ (SSE vs streamable HTTP)`,
tools: [],
};
}
return {
probeable: true,
ok: false,
detail: `No tool list in response (HTTP ${response.status})`,
tools: [],
};
});
} catch (error) {
return {
probeable: true,
ok: false,
detail: error instanceof Error ? error.message.slice(0, 200) : "Probe failed",
tools: [],
};
}
}
/** Accepts a plain JSON body or an SSE `data:` framed JSON-RPC response. */
function parseJsonRpc(text: string): unknown {
const trimmed = text.trim();
if (!trimmed) return null;
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
try {
return JSON.parse(trimmed);
} catch {
return null;
}
}
for (const line of trimmed.split("\n")) {
const value = line.trim();
if (!value.startsWith("data:")) continue;
try {
return JSON.parse(value.slice(5).trim());
} catch {
// keep scanning further SSE frames
}
}
return null;
}
function extractToolNames(payload: unknown): string[] {
const tools = (payload as { result?: { tools?: unknown } } | null)?.result?.tools;
if (!Array.isArray(tools)) return [];
return tools
.map((tool) => (tool as { name?: unknown })?.name)
.filter((name): name is string => typeof name === "string" && name.length > 0)
.slice(0, 60);
}
export function readProtocolVersion(payload: unknown): string | null {
const v = (payload as { result?: { protocolVersion?: unknown } } | null)?.result?.protocolVersion;
return typeof v === "string" && v.length > 0 && v.length < 40 ? v : null;
}
export function extractToolSchemas(payload: unknown): Record<string, ToolSchema> {
const tools = (payload as { result?: { tools?: unknown } } | null)?.result?.tools;
const out: Record<string, ToolSchema> = {};
if (!Array.isArray(tools)) return out;
for (const tool of tools.slice(0, 200)) {
const t = tool as { name?: unknown; inputSchema?: unknown; outputSchema?: unknown };
if (typeof t?.name !== "string" || !t.name) continue;
out[t.name] = { input: t.inputSchema ?? null, output: t.outputSchema ?? null };
}
return out;
}
type Props = { properties?: Record<string, { type?: unknown; enum?: unknown[] }>; required?: string[] };
function diffSide(tool: string, side: string, before: unknown, after: unknown, out: string[]) {
const b = (before ?? {}) as Props;
const a = (after ?? {}) as Props;
const bp = b.properties ?? {};
const ap = a.properties ?? {};
for (const key of Object.keys(bp)) {
if (!(key in ap)) { out.push(`${tool}.${side}.${key} removed`); continue; }
const bt = JSON.stringify(bp[key]?.type ?? null);
const at = JSON.stringify(ap[key]?.type ?? null);
if (bt !== at) out.push(`${tool}.${side}.${key} type ${bt} -> ${at}`);
if (Array.isArray(bp[key]?.enum)) {
const next = new Set((ap[key]?.enum ?? []).map((v) => JSON.stringify(v)));
for (const v of bp[key]!.enum!) {
if (!next.has(JSON.stringify(v))) out.push(`${tool}.${side}.${key} enum lost ${JSON.stringify(v)}`);
}
}
}
if (side === "input") {
const wasRequired = new Set(b.required ?? []);
for (const key of a.required ?? []) {
if (!wasRequired.has(key)) out.push(`${tool}.input.${key} became required`);
}
}
}
/**
* Breaking changes between two declared tool schema snapshots, without calling
* any tool: removed tools, removed/retyped fields, lost enum members, and new
* required inputs. Additive changes are not breaking and are not reported.
*/
export function diffToolSchemas(
before: Record<string, ToolSchema> | null | undefined,
after: Record<string, ToolSchema>,
): string[] {
if (!before) return [];
const out: string[] = [];
for (const tool of Object.keys(before)) {
if (!(tool in after)) { out.push(`${tool} removed`); continue; }
diffSide(tool, "input", before[tool]?.input, after[tool]?.input, out);
diffSide(tool, "output", before[tool]?.output, after[tool]?.output, out);
}
return out.slice(0, 50);
}
/**
* Non-breaking (additive) changes between two declared snapshots: new tools,
* new optional fields, gained enum members and inputs that stopped being
* required. Labeled compatible by default; the consumer still decides.
*/
export function diffAdditiveToolSchemas(
before: Record<string, ToolSchema> | null | undefined,
after: Record<string, ToolSchema>,
): string[] {
if (!before) return [];
const out: string[] = [];
for (const tool of Object.keys(after)) {
if (!(tool in before)) { out.push(`${tool} added`); continue; }
for (const side of ["input", "output"] as const) {
const b = (before[tool]?.[side] ?? {}) as Props;
const a = (after[tool]?.[side] ?? {}) as Props;
const bp = b.properties ?? {};
const ap = a.properties ?? {};
const req = new Set(a.required ?? []);
for (const key of Object.keys(ap)) {
if (!(key in bp)) { if (side === "output" || !req.has(key)) out.push(`${tool}.${side}.${key} added (optional)`); continue; }
if (Array.isArray(ap[key]?.enum) && Array.isArray(bp[key]?.enum)) {
const prev = new Set(bp[key]!.enum!.map((v) => JSON.stringify(v)));
for (const v of ap[key]!.enum!) if (!prev.has(JSON.stringify(v))) out.push(`${tool}.${side}.${key} enum gained ${JSON.stringify(v)}`);
}
}
if (side === "input") for (const key of b.required ?? []) if (!req.has(key) && key in ap) out.push(`${tool}.input.${key} became optional`);
}
}
return out.slice(0, 50);
}
/** An HTTP API is "capability ok" when it answers a machine contract or an auth challenge. */
async function probeHttpApi(endpoint: string): Promise<CapabilityProbe> {
try {
return await withTimeout(async (signal) => {
// Redirects are followed by hand so each hop is re-checked: `follow` would
// let a public host bounce the probe onto an internal address.
let current = endpoint;
let response: Response | null = null;
for (let hop = 0; hop < 5; hop += 1) {
if (!isPublicHttpTarget(current)) {
return {
probeable: false,
ok: null,
detail: "Endpoint resolves to a non-public address — not probed",
tools: [],
};
}
response = await fetch(current, {
method: "GET",
redirect: "manual",
signal,
headers: { accept: "application/json", "user-agent": "AgentNexus-CapabilityProbe/1.0" },
});
if (response.status < 300 || response.status >= 400) break;
const location = response.headers.get("location");
if (!location) break;
current = new URL(location, current).toString();
response = null;
}
if (!response) {
return { probeable: true, ok: null, detail: "Too many redirects to verify", tools: [] };
}
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
if (response.status === 401 || response.status === 403) {
return {
probeable: true,
ok: true,
detail: `Auth-gated as documented (HTTP ${response.status})`,
tools: [],
};
}
if (response.status >= 500) {
return { probeable: true, ok: false, detail: `Server error HTTP ${response.status}`, tools: [] };
}
// A REST base path commonly has no GET handler: the host answered, so the
// interface is reachable, but the contract itself stays unverified.
if (response.status === 404 || response.status === 405) {
return {
probeable: true,
ok: null,
detail: `Base path answered HTTP ${response.status} — no GET contract at the root, call a documented operation`,
tools: [],
};
}
if (contentType.includes("json")) {
return {
probeable: true,
ok: true,
detail: `JSON contract confirmed (HTTP ${response.status})`,
tools: [],
};
}
// Plenty of legitimate machine interfaces answer XML, CSV, NDJSON or plain
// text (arXiv, Stack Exchange, GTFS feeds, OpenStreetMap...). Demanding
// JSON flagged them as broken while they served their documented contract,
// so any structured, non-HTML payload counts as a confirmed contract.
if (/(xml|csv|ndjson|jsonl|yaml|text\/plain|application\/x-ndjson|rss|atom|protobuf|octet-stream)/.test(contentType)) {
return {
probeable: true,
ok: true,
detail: `Non-JSON machine contract confirmed (HTTP ${response.status}, ${contentType.split(";")[0]})`,
tools: [],
};
}
// HTML (or an unlabelled body) is not a machine contract, but it does prove
// the host answers: unverified rather than failed, so the entry is not
// reported as an outage on a documentation or landing response.
return {
probeable: true,
ok: null,
detail: `Answered HTTP ${response.status} with ${contentType.split(";")[0] || "no content type"} — human-readable response, contract not machine-verified`,
tools: [],
};
});
} catch (error) {
return {
probeable: true,
ok: false,
detail: error instanceof Error ? error.message.slice(0, 200) : "Probe failed",
tools: [],
};
}
}
export async function probeCapabilities(entry: {
category: string;
endpoint: string;
}): Promise<CapabilityProbe> {
const endpoint = entry.endpoint.trim();
if (entry.category === "cli") {
return notProbeable("CLI interfaces are validated locally, not over the network");
}
if (hasPlaceholder(endpoint)) {
return notProbeable("Templated endpoint (placeholders) — resolved per call, not probeable");
}
if (!isHttp(endpoint)) {
return notProbeable("Locally launched interface (stdio) — not remotely probeable");
}
// Never let a listed endpoint aim our own server at loopback, private or
// cloud-metadata addresses.
if (!isPublicHttpTarget(endpoint)) {
return notProbeable("Non-public address (loopback/private/link-local) — not probed");
}
return entry.category === "mcp" ? probeMcp(endpoint) : probeHttpApi(endpoint);
}