-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.ts
More file actions
438 lines (395 loc) · 14.9 KB
/
Copy pathtypes.ts
File metadata and controls
438 lines (395 loc) · 14.9 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
/*! MCP Trust Checker · https://mcptrustchecker.com · support@mcptrustchecker.com · © 2026 Illia Haidar · MIT */
/**
* MCP Trust Checker core type model.
*
* Everything in the engine is expressed against a single normalized, transport-
* agnostic view of a server — the {@link ServerSurface}. Acquisition adapters
* (stdio / HTTP / static JSON / client config) all produce a `ServerSurface`;
* every detector consumes one and emits {@link Finding}s; the scorer turns
* findings into an auditable {@link Score}. Keeping this model small and pure is
* what makes the whole tool deterministic and offline-capable.
*/
// ---------------------------------------------------------------------------
// Surface model — the normalized security surface of an MCP server
// ---------------------------------------------------------------------------
/** Where a surface was acquired from (drives which detectors have signal). */
export type SurfaceSourceKind =
| 'stdio' // spawned a local command and spoke MCP over stdio
| 'http' // connected to a Streamable-HTTP / SSE endpoint
| 'manifest' // read a pre-generated tools.json (offline)
| 'client-config' // extracted from a client config (claude_desktop_config.json, etc.)
| 'package'; // resolved package metadata only (no live surface)
export interface SurfaceSource {
kind: SurfaceSourceKind;
/** Human-readable origin: a path, URL, or package spec. */
origin: string;
}
/** A JSON-Schema-ish object as advertised by a tool's `inputSchema`. */
export interface JsonSchema {
type?: string | string[];
properties?: Record<string, JsonSchema>;
items?: JsonSchema | JsonSchema[];
required?: string[];
enum?: unknown[];
description?: string;
title?: string;
format?: string;
[k: string]: unknown;
}
/**
* Tool behavior hints as advertised by the server.
*
* SECURITY NOTE: these are attacker-controllable and MUST NOT be trusted for
* security decisions. MCP Trust Checker reads them only to flag when they *contradict*
* a tool's derived capabilities (annotation-vs-behavior mismatch).
*/
export interface ToolAnnotations {
title?: string;
readOnlyHint?: boolean;
destructiveHint?: boolean;
idempotentHint?: boolean;
openWorldHint?: boolean;
[k: string]: unknown;
}
export interface ToolDef {
name: string;
title?: string;
description?: string;
inputSchema?: JsonSchema;
outputSchema?: JsonSchema;
annotations?: ToolAnnotations;
}
export interface PromptArgument {
name: string;
description?: string;
required?: boolean;
}
export interface PromptDef {
name: string;
title?: string;
description?: string;
arguments?: PromptArgument[];
}
export interface ResourceDef {
uri?: string;
uriTemplate?: string;
name?: string;
title?: string;
description?: string;
mimeType?: string;
}
export interface TransportInfo {
kind: 'stdio' | 'http' | 'sse' | 'unknown';
/** For HTTP/SSE transports. */
url?: string;
/** For stdio transports. */
command?: string;
args?: string[];
/**
* True when the spawned `command`/`args` originate from untrusted metadata
* without an executable allowlist — the systemic stdio-RCE class.
*/
userControlledCommand?: boolean;
/** Execution-hijacking env vars that were stripped before spawning, if any. */
droppedEnv?: string[];
}
/** Package/provenance metadata, if the target maps to a known package. */
export interface PackageMeta {
registry?: 'npm' | 'pypi' | 'unknown';
name?: string;
version?: string;
/** Raw install/lifecycle scripts, if known. */
scripts?: Record<string, string>;
dependencies?: string[];
repositoryUrl?: string | null;
license?: string | null;
weeklyDownloads?: number | null;
/** ISO 8601 publish timestamp of the resolved version, if known. */
publishedAt?: string | null;
/** Whether the install spec pins an exact version (false = @latest/floating). */
pinned?: boolean;
/** The raw version token from the install spec, if any (e.g. "latest", "^1.2.0"). */
requestedSpec?: string;
}
/** The single normalized object every detector operates on. */
export interface ServerSurface {
/** Stable identity used for lockfile pinning (package spec, url, or path). */
id: string;
source: SurfaceSource;
server: {
name?: string;
version?: string;
title?: string;
/** Free-text server instructions — a first-class line-jumping surface. */
instructions?: string;
protocolVersion?: string;
capabilities?: Record<string, unknown>;
};
tools: ToolDef[];
prompts: PromptDef[];
resources: ResourceDef[];
transport?: TransportInfo;
packageMeta?: PackageMeta;
/**
* Server implementation source, when available (a local package directory or
* an extracted tarball). Enables implementation-level analysis — reading what
* the code *does*, not only what the tool metadata *claims*.
*/
sourceFiles?: SourceFile[];
}
export interface SourceFile {
/** Path relative to the package root. */
path: string;
content: string;
}
// ---------------------------------------------------------------------------
// Findings
// ---------------------------------------------------------------------------
export type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';
/**
* How sure we are — the "severity ≠ risk" split: a heuristic
* keyword hit and a decoded hidden-instruction payload can share a severity
* but must not carry the same weight — and only `confirmed` findings can fire
* a hard grade gate.
*/
export type Confidence = 'confirmed' | 'strong' | 'heuristic' | 'speculative';
export type Category =
| 'injection' // prompt-injection / tool-poisoning / line-jumping
| 'exfiltration' // secrets & data-exfiltration (incl. toxic-flow)
| 'permissions' // over-broad scope / dangerous capabilities
| 'supply-chain' // typosquat / install scripts / provenance / known CVEs
| 'network' // transport & host posture
| 'hygiene'; // metadata / documentation / minor issues
export interface FindingLocation {
kind: 'tool' | 'prompt' | 'resource' | 'server' | 'package' | 'transport' | 'flow';
/** Name of the tool/prompt/resource, when applicable. */
name?: string;
/** Field within the object, e.g. `description` or `inputSchema.properties.path.description`. */
field?: string;
}
export interface Finding {
/** Stable rule id, e.g. `MTC-UNI-001`. Used for docs, baselines and SARIF. */
ruleId: string;
title: string;
category: Category;
severity: Severity;
confidence: Confidence;
/** What was found and why it matters. */
description: string;
remediation?: string;
location?: FindingLocation;
/** Concrete evidence: a decoded payload, matched snippet, offending name, etc. */
evidence?: string;
/** External references (OWASP, CVE, blog posts, spec sections). */
references?: string[];
/** OWASP MCP Top 10 / LLM Top 10 mapping id, when available. */
owasp?: string;
/** Structured extras for machine consumers. */
data?: Record<string, unknown>;
}
// ---------------------------------------------------------------------------
// Capabilities & toxic flows
// ---------------------------------------------------------------------------
export type CapabilityTag =
| 'untrusted-input' // ingests attacker-controllable content (web, issues, email…)
| 'sensitive-source' // reads private/local data (files, env, secrets, db…)
| 'external-sink' // can send data out / act externally (http, email, publish…)
| 'code-exec' // runs shell commands or evaluates code (a severe sink)
| 'file-write'; // writes or deletes files
export interface ToolCapability {
tool: string;
tags: CapabilityTag[];
/** Why each tag was assigned (keyword/schema evidence), for explainability. */
reasons: Partial<Record<CapabilityTag, string[]>>;
}
/** How much a server could do if the model driving it were manipulated. */
export type CapabilityLevel = 'minimal' | 'moderate' | 'high' | 'critical';
export interface CapabilityProfile {
level: CapabilityLevel;
/** Human-readable reasons the level was assigned. */
reasons: string[];
/** The union of capability tags observed across the server's tools. */
tags: CapabilityTag[];
}
export interface ToxicFlow {
id: string;
severity: Severity;
confidence: Confidence;
/** Tool(s) that supply the untrusted input, if any. */
untrustedInput: string[];
/** Tool(s) that read sensitive data, if any. */
sensitiveSource: string[];
/** Tool(s) that can exfiltrate / act externally. */
externalSink: string[];
/** True when a single tool holds more than one role (self-contained primitive). */
selfContained: boolean;
/** The concrete attack chain of tools (e.g. ["fetch_url","read_file","http_request"]). */
path?: string[];
/** True when at least one leg of the path is a direct schema wire (higher plausibility). */
pathWired?: boolean;
description: string;
}
// ---------------------------------------------------------------------------
// Scoring
// ---------------------------------------------------------------------------
export type Grade = 'A' | 'B' | 'C' | 'D' | 'F';
export interface ScoreVectorItem {
ruleId: string;
category: Category;
severity: Severity;
confidence: Confidence;
/** Base weight for the severity. */
rawWeight: number;
confidenceMult: number;
/** Diminishing-returns multiplier for the Nth finding of this rule. */
diminishingFactor: number;
/** rawWeight × confidenceMult × diminishingFactor, rounded to 2dp. */
appliedPenalty: number;
}
export interface Score {
/** 0–100, higher is safer. */
score: number;
/** Final grade after gates. */
grade: Grade;
/** Grade implied by the raw number, before hard gates. */
band: Grade;
/** Strictest grade cap forced by a hard gate, if any. */
gateCap?: Grade;
/** Points subtracted per category (after per-category caps). */
categorySubtotals: Record<Category, number>;
/** Fully itemized, reconstructable penalty vector. */
vector: ScoreVectorItem[];
/** Human-readable descriptions of every gate that fired. */
gatesFired: string[];
methodologyVersion: string;
}
// ---------------------------------------------------------------------------
// Integrity (rug-pull / TOFU)
// ---------------------------------------------------------------------------
export type IntegrityStatus = 'first-seen' | 'unchanged' | 'drift';
export interface SurfaceChange {
kind: 'tool-added' | 'tool-removed' | 'tool-changed' | 'instructions-changed';
name?: string;
detail: string;
}
export interface IntegrityResult {
status: IntegrityStatus;
currentDigest: string;
previousDigest?: string;
/** Populated when status is `drift`. */
changes?: SurfaceChange[];
}
// ---------------------------------------------------------------------------
// Report
// ---------------------------------------------------------------------------
export interface ScanReport {
tool: {
name: string;
version: string;
methodologyVersion: string;
};
target: {
id: string;
source: SurfaceSource;
server?: { name?: string; version?: string };
};
/** ISO timestamp. Omitted for reproducible (deterministic) reports. */
scannedAt?: string;
findings: Finding[];
score: Score;
capabilities: ToolCapability[];
/** The server's blast-radius rating (independent of the trust grade). */
capabilityProfile: CapabilityProfile;
toxicFlows: ToxicFlow[];
integrity?: IntegrityResult;
/** SHA-256 of the canonicalized surface — the rug-pull fingerprint. */
surfaceDigest: string;
stats: {
tools: number;
prompts: number;
resources: number;
findingsBySeverity: Record<Severity, number>;
};
}
// ---------------------------------------------------------------------------
// Detector contract
// ---------------------------------------------------------------------------
export interface DetectorContext {
surface: ServerSurface;
config: ResolvedConfig;
/** Per-tool capability tags, computed once by the engine and shared. */
capabilities: ToolCapability[];
/**
* Tool names exposed by OTHER servers in the same scan, for cross-server
* name-collision / shadowing detection. Empty when scanning a single target.
*/
siblingTools?: { server: string; name: string }[];
}
export interface Detector {
id: string;
/** Pipeline stage number (see docs/architecture.md). */
stage: number;
title: string;
run(ctx: DetectorContext): Finding[] | Promise<Finding[]>;
}
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
export interface McpTrustCheckerConfig {
/** Rule ids to disable entirely. */
disabledRules?: string[];
/** Rule ids whose findings are allowed (suppressed) — an explicit waiver list. */
allowlist?: string[];
/** Fail CI when the score is below this threshold (0–100). */
failUnder?: number;
/** Fail CI when the grade is worse than this (e.g. "B"). */
minGrade?: Grade;
/** Path to the integrity lockfile. */
lockfile?: string;
/**
* When true, the toxic-flow graph assumes the client also exposes generic
* built-in tools (web-fetch as untrusted input, file/network as sinks), which
* can complete a trifecta on their own.
*/
includeBuiltins?: boolean;
/** Additional package names to hard-protect against typosquatting. */
protectedPackages?: string[];
/** Zero-width character count above which a string is treated as an encoded payload. */
invisibleCharThreshold?: number;
/**
* Location-scoped waivers (a baseline). Unlike `allowlist` (which silences a
* whole rule everywhere), each entry silences a specific finding on a specific
* tool/field — with a justification that stays in the config for audit.
* Also loadable from a standalone `.mtcignore` JSON file next to the config.
*/
suppress?: Suppression[];
/** Organisational policy the scan is gated against (see {@link Policy}). */
policy?: Policy;
}
/** A single baseline waiver. `rule` is required; the rest narrow the match. */
export interface Suppression {
rule: string;
/** Only suppress on this tool/prompt/resource name (location.name). */
tool?: string;
/** Only suppress on this field (location.field). */
field?: string;
/** Why the waiver is safe — kept for audit, never affects matching. */
reason?: string;
}
/** Policy-as-code: declarative rules a server must satisfy, gated in CI. */
export interface Policy {
/** Fail if the Trust grade is worse than this. */
minGrade?: Grade;
/** Fail if the Capability blast-radius exceeds this level. */
maxCapability?: CapabilityLevel;
/** Fail if any of these rule ids fired. */
denyRules?: string[];
/** Fail if the server exposes any of these capability tags. */
denyCapabilities?: CapabilityTag[];
}
/** Config with all defaults resolved — what detectors actually see. */
export interface ResolvedConfig extends Required<Omit<McpTrustCheckerConfig, 'minGrade' | 'lockfile' | 'policy'>> {
minGrade?: Grade;
lockfile?: string;
policy?: Policy;
}