@mwillbanks/ast-mcp 0.6.6 → 0.7.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.
Files changed (55) hide show
  1. package/CONTRIBUTING.md +6 -0
  2. package/dist/ast-mcp.js +358 -337
  3. package/dist/ast-mcp.js.map +45 -32
  4. package/dist/workers/sql-postgres-worker.js +5 -0
  5. package/dist/workers/sql-postgres-worker.js.map +10 -0
  6. package/package.json +3 -2
  7. package/src/cli/doctor.ts +103 -0
  8. package/src/cli/index.ts +9 -1
  9. package/src/config/index.ts +61 -6
  10. package/src/config/registry.ts +209 -67
  11. package/src/config/v2-schema.ts +2 -0
  12. package/src/helpers/installer.ts +10 -1
  13. package/src/http/index.ts +12 -5
  14. package/src/installer/codex.ts +237 -0
  15. package/src/installer/diagnostics.ts +387 -0
  16. package/src/installer/directory-ancestry.ts +55 -0
  17. package/src/installer/index.ts +386 -119
  18. package/src/installer/ownership.ts +165 -0
  19. package/src/installer/service-state.ts +151 -0
  20. package/src/installer/service.ts +131 -7
  21. package/src/installer/transaction.ts +342 -0
  22. package/src/installer/transport.ts +22 -31
  23. package/src/intelligence/mutation/locks.ts +4 -1
  24. package/src/patch/engine.ts +157 -11
  25. package/src/runtime/approval.ts +427 -66
  26. package/src/runtime/config-write.ts +27 -1
  27. package/src/runtime/diagnostics.ts +115 -0
  28. package/src/runtime/file-capabilities.ts +2 -0
  29. package/src/runtime/hosts/codex.ts +16 -0
  30. package/src/runtime/path-policy.ts +2 -0
  31. package/src/runtime/release.ts +220 -0
  32. package/src/runtime/sql-assistance.ts +439 -0
  33. package/src/runtime/sql-options-schema.ts +31 -0
  34. package/src/runtime/sql-postgres-worker.ts +72 -0
  35. package/src/runtime/sql-postgres.ts +245 -0
  36. package/src/server/index.ts +35 -5
  37. package/src/server/lifecycle.ts +1 -1
  38. package/src/tools/configuration.ts +2 -0
  39. package/src/tools/diagnostics.ts +85 -0
  40. package/src/tools/files.ts +2 -0
  41. package/src/tools/index.ts +9 -0
  42. package/templates/skills/ast-mcp/SKILL.md +20 -1
  43. package/templates/skills/ast-mcp/evals/evals.json +274 -0
  44. package/templates/skills/ast-mcp/evals/semantic.ts +2 -0
  45. package/templates/skills/ast-mcp/evals/trigger-queries.json +4 -1
  46. package/templates/skills/ast-mcp/references/cli.md +97 -0
  47. package/templates/skills/ast-mcp/references/configuration.md +11 -3
  48. package/templates/skills/ast-mcp/references/diagnostics.md +106 -0
  49. package/templates/skills/ast-mcp/references/host-context.md +85 -0
  50. package/templates/skills/ast-mcp/references/installation.md +37 -0
  51. package/templates/skills/ast-mcp/references/issue-reporting.md +80 -0
  52. package/templates/skills/ast-mcp/references/patch-state-machine.md +10 -0
  53. package/templates/skills/ast-mcp/references/tool-catalog.md +120 -50
  54. package/templates/skills/ast-mcp/scripts/check-install.ts +223 -24
  55. package/templates/skills/ast-mcp/scripts/release.ts +220 -0
@@ -26,6 +26,7 @@ import {
26
26
  canonicalConfigPath,
27
27
  withConfigTransaction,
28
28
  } from "../config/transaction";
29
+ import { codexApprovalMetadata } from "./hosts/codex";
29
30
  import type { PolicyDecision } from "./path-policy";
30
31
  import { canonicalizePathSync } from "./path-utils";
31
32
 
@@ -41,9 +42,149 @@ const activeApproval = new AsyncLocalStorage<ApprovalScope>();
41
42
  const sessionGrants = new Set<string>();
42
43
  const serverIdentities = new WeakMap<McpServer, string>();
43
44
  interface ApprovalChallenge {
45
+ createdAt: number;
44
46
  expiresAt: number;
45
47
  responseKey: string;
46
48
  sessionId: string;
49
+ serverId: string;
50
+ server: McpServer;
51
+ decision: PolicyDecision;
52
+ tool: string;
53
+ }
54
+
55
+ export type ApprovalOutcome =
56
+ | "accepted"
57
+ | "declined"
58
+ | "denied"
59
+ | "cancelled"
60
+ | "malformed"
61
+ | "unsupported"
62
+ | "timeout"
63
+ | "transport_error";
64
+
65
+ export interface ApprovalObservation {
66
+ at: string;
67
+ outcome: ApprovalOutcome;
68
+ actor: "unknown";
69
+ operation: PolicyDecision["operation"];
70
+ source: PolicyDecision["source"];
71
+ rule: "filesystem" | "path" | "probe";
72
+ }
73
+
74
+ let observations = new WeakMap<McpServer, Map<string, ApprovalObservation>>();
75
+ const MAX_OBSERVED_SESSIONS = 256;
76
+
77
+ function serverId(server?: McpServer): string {
78
+ if (!server) return "local";
79
+ let identity = serverIdentities.get(server);
80
+ if (!identity) {
81
+ identity = randomUUID();
82
+ serverIdentities.set(server, identity);
83
+ }
84
+ return identity;
85
+ }
86
+
87
+ function observe(
88
+ scope: ApprovalScope,
89
+ decision: PolicyDecision,
90
+ outcome: ApprovalOutcome,
91
+ ): void {
92
+ if (!scope.server) return;
93
+ let sessions = observations.get(scope.server);
94
+ if (!sessions) {
95
+ sessions = new Map();
96
+ observations.set(scope.server, sessions);
97
+ }
98
+ const session = scope.context?.sessionId ?? "connection";
99
+ sessions.delete(session);
100
+ sessions.set(session, {
101
+ at: new Date().toISOString(),
102
+ outcome,
103
+ actor: "unknown",
104
+ operation: decision.operation,
105
+ source: decision.source,
106
+ rule:
107
+ decision.approvalKind === "probe"
108
+ ? "probe"
109
+ : decision.approvalKind === "filesystem"
110
+ ? "filesystem"
111
+ : "path",
112
+ });
113
+ if (sessions.size > MAX_OBSERVED_SESSIONS)
114
+ sessions.delete(sessions.keys().next().value!);
115
+ }
116
+
117
+ export function approvalClient(server?: McpServer, context?: ServerContext) {
118
+ const envelope = context?.mcpReq?.envelope as
119
+ | Record<string, unknown>
120
+ | undefined;
121
+ const capabilities = (envelope?.[
122
+ "io.modelcontextprotocol/clientCapabilities"
123
+ ] ?? server?.server.getClientCapabilities()) as
124
+ | { elicitation?: unknown; roots?: unknown; sampling?: unknown }
125
+ | undefined;
126
+ const client = (envelope?.["io.modelcontextprotocol/clientInfo"] ??
127
+ server?.server.getClientVersion?.()) as
128
+ | { name?: unknown; version?: unknown }
129
+ | undefined;
130
+ const protocol =
131
+ envelope?.["io.modelcontextprotocol/protocolVersion"] ??
132
+ server?.server.getNegotiatedProtocolVersion?.();
133
+ return {
134
+ capabilities,
135
+ client,
136
+ protocol: typeof protocol === "string" ? protocol : "unknown",
137
+ };
138
+ }
139
+
140
+ export function supportsApprovalForm(
141
+ capabilities: { elicitation?: unknown } | undefined,
142
+ ): boolean {
143
+ const elicitation = capabilities?.elicitation;
144
+ if (
145
+ !elicitation ||
146
+ typeof elicitation !== "object" ||
147
+ Array.isArray(elicitation)
148
+ )
149
+ return false;
150
+ // An empty capability is the legacy declaration of form support.
151
+ return (
152
+ Object.keys(elicitation).length === 0 ||
153
+ (Object.hasOwn(elicitation, "form") &&
154
+ typeof (elicitation as { form?: unknown }).form === "object" &&
155
+ (elicitation as { form?: unknown }).form !== null &&
156
+ !Array.isArray((elicitation as { form?: unknown }).form))
157
+ );
158
+ }
159
+
160
+ export function approvalDiagnostics(
161
+ server?: McpServer,
162
+ context?: ServerContext,
163
+ ) {
164
+ pruneApprovalChallenges();
165
+ const session = context?.sessionId ?? "connection";
166
+ const identity = serverId(server);
167
+ const pending = [...issuedChallenges.values()].filter(
168
+ (challenge) =>
169
+ challenge.sessionId === session && challenge.serverId === identity,
170
+ );
171
+ const prefix = `${session}\u0000${identity}\u0000`;
172
+ return {
173
+ pendingCount: pending.length,
174
+ oldestPendingAgeMs: pending.length
175
+ ? Math.max(
176
+ 0,
177
+ Date.now() -
178
+ Math.min(...pending.map((challenge) => challenge.createdAt)),
179
+ )
180
+ : null,
181
+ sessionGrantPresent: [...sessionGrants].some((grant) =>
182
+ grant.startsWith(prefix),
183
+ ),
184
+ lastOutcome: server
185
+ ? (observations.get(server)?.get(session) ?? null)
186
+ : null,
187
+ };
47
188
  }
48
189
 
49
190
  const APPROVAL_CHALLENGE_TTL_MS = 5 * 60 * 1000;
@@ -79,22 +220,69 @@ function persistentConfig(globalPath: string): string {
79
220
  interface StoredPersistentRule {
80
221
  id?: string;
81
222
  path?: string;
223
+ follow_symlinks?: boolean;
224
+ includes?: string[];
225
+ excludes?: string[];
82
226
  policies?: Partial<
83
227
  Record<PolicyDecision["operation"], "allow" | "deny" | "request">
84
228
  >;
85
229
  }
86
230
 
231
+ function persistenceConflict(): Error {
232
+ return Object.assign(
233
+ new Error(
234
+ "Persistent approval conflicts with customized path rules; use allow once or session approval, or explicitly update the user-global rule",
235
+ ),
236
+ {
237
+ code: "approval_persistence_conflict",
238
+ retryable: true,
239
+ suggestedNextCall: "config_status",
240
+ },
241
+ );
242
+ }
243
+
244
+ function ownedPersistentRule(
245
+ rule: StoredPersistentRule,
246
+ canonicalPath: string,
247
+ ): boolean {
248
+ const operations = ["read", "write", "delete"] as const;
249
+ return (
250
+ rule.path === canonicalPath &&
251
+ Object.keys(rule).sort().join(",") ===
252
+ "excludes,follow_symlinks,id,includes,path,policies" &&
253
+ rule.follow_symlinks === false &&
254
+ Array.isArray(rule.includes) &&
255
+ rule.includes.length === 1 &&
256
+ rule.includes[0] === "**/*" &&
257
+ Array.isArray(rule.excludes) &&
258
+ rule.excludes.length === 0 &&
259
+ rule.policies !== undefined &&
260
+ Object.keys(rule.policies).sort().join(",") === "delete,read,write" &&
261
+ operations.every(
262
+ (operation) =>
263
+ rule.policies?.[operation] === "allow" ||
264
+ rule.policies?.[operation] === "deny",
265
+ ) &&
266
+ operations.some(
267
+ (operation) =>
268
+ rule.id === persistentId({ canonicalPath, operation }) &&
269
+ rule.policies?.[operation] === "allow",
270
+ )
271
+ );
272
+ }
273
+
87
274
  function storedPersistentApprovals(
88
275
  existing: string,
89
276
  canonicalPath: string,
90
277
  ): StoredPersistentRule[] {
91
278
  if (!existing) return [];
92
- const parsed = Bun.TOML.parse(existing) as {
93
- paths?: StoredPersistentRule[];
94
- };
95
- return (parsed.paths ?? []).filter(
96
- (rule) => rule.id?.startsWith("approval-") && rule.path === canonicalPath,
279
+ const parsed = Bun.TOML.parse(existing) as { paths?: StoredPersistentRule[] };
280
+ const matching = (parsed.paths ?? []).filter(
281
+ (rule) => rule.path === canonicalPath,
97
282
  );
283
+ if (matching.some((rule) => !ownedPersistentRule(rule, canonicalPath)))
284
+ throw persistenceConflict();
285
+ return matching;
98
286
  }
99
287
 
100
288
  function persistentPolicy(
@@ -125,17 +313,37 @@ function mergePersistentPolicies(
125
313
  ): string {
126
314
  const ids = new Set(rules.flatMap((rule) => (rule.id ? [rule.id] : [])));
127
315
  const policyLine = persistentPolicyLine(policy);
128
- return source
316
+ let merged = 0;
317
+ const result = source
129
318
  .split(/(?=^\[\[paths\]\]\s*$)/m)
130
- .map((block) =>
131
- [...ids].some((id) => block.includes(`id = ${JSON.stringify(id)}`))
132
- ? block.replace(/^policies = \{.*\}$/m, policyLine)
133
- : block,
134
- )
319
+ .map((block) => {
320
+ if (!block.startsWith("[[paths]]")) return block;
321
+ let rule: StoredPersistentRule | undefined;
322
+ try {
323
+ rule = (Bun.TOML.parse(block) as { paths?: StoredPersistentRule[] })
324
+ .paths?.[0];
325
+ } catch {
326
+ throw persistenceConflict();
327
+ }
328
+ if (
329
+ !rule?.id ||
330
+ !ids.has(rule.id) ||
331
+ !rule.path ||
332
+ !ownedPersistentRule(rule, rule.path)
333
+ )
334
+ return block;
335
+ if (!/^policies = \{.*\}$/m.test(block)) throw persistenceConflict();
336
+ merged++;
337
+ return block.replace(/^policies = \{.*\}$/m, policyLine);
338
+ })
135
339
  .join("");
340
+ if (merged !== rules.length) throw persistenceConflict();
341
+ return result;
136
342
  }
137
343
 
138
- function persistentId(decision: PolicyDecision): string {
344
+ function persistentId(
345
+ decision: Pick<PolicyDecision, "operation" | "canonicalPath">,
346
+ ): string {
139
347
  return `approval-${createHash("sha256")
140
348
  .update(`${decision.operation}\u0000${decision.canonicalPath}`)
141
349
  .digest("hex")
@@ -235,15 +443,11 @@ function key(
235
443
  scope: ApprovalScope,
236
444
  generation: number,
237
445
  ): string {
238
- let serverIdentity = scope.server && serverIdentities.get(scope.server);
239
- if (scope.server && !serverIdentity) {
240
- serverIdentity = randomUUID();
241
- serverIdentities.set(scope.server, serverIdentity);
242
- }
243
- const filesystem = decision.ruleId?.startsWith("filesystem:");
446
+ const serverIdentity = serverId(scope.server);
447
+ const filesystem = decision.approvalKind === "filesystem";
244
448
  return [
245
449
  scope.context?.sessionId ?? "connection",
246
- filesystem ? (serverIdentity ?? "local") : "session",
450
+ serverIdentity,
247
451
  filesystem ? 0 : generation,
248
452
  filesystem ? "filesystem" : scope.tool,
249
453
  decision.ruleId ?? decision.source,
@@ -288,7 +492,9 @@ function acceptResponse(
288
492
  invocationGrants: Set<string>,
289
493
  ): boolean | undefined {
290
494
  if (response?.action !== "accept") return undefined;
291
- if (decision.ruleId?.startsWith("filesystem:")) {
495
+ if (decision.approvalKind === "probe")
496
+ return response.content?.decision === "allow_once" ? true : undefined;
497
+ if (decision.approvalKind === "filesystem") {
292
498
  if (response.content?.decision !== "allow_session") return undefined;
293
499
  sessionGrants.add(grantKey);
294
500
  return true;
@@ -309,37 +515,117 @@ function acceptResponse(
309
515
  }
310
516
  }
311
517
 
312
- function deniedResponse(response: ApprovalResponse | undefined): boolean {
313
- return (
314
- response?.action === "decline" ||
315
- response?.action === "cancel" ||
316
- response?.content?.decision === "deny"
317
- );
518
+ function responseOutcome(
519
+ response: ApprovalResponse | undefined,
520
+ ): ApprovalOutcome {
521
+ if (response?.action === "cancel") return "cancelled";
522
+ if (response?.action === "decline") return "declined";
523
+ if (response?.action === "accept" && response.content?.decision === "deny")
524
+ return "denied";
525
+ return "malformed";
318
526
  }
319
527
 
320
528
  function approvalRequired(decision: PolicyDecision): Error {
321
529
  return Object.assign(
322
530
  new Error(
323
- `Approval required for ${decision.operation} ${decision.canonicalPath}; this client has no elicitation capability. Add a narrow user-global [[paths]] rule or use a capable client.`,
531
+ `Approval required for ${decision.operation}; this client cannot provide a stable form approval. Use diagnostics to inspect capabilities and policy. Add an authorized narrow user-global rule or use an elicitation-capable session.`,
324
532
  ),
325
533
  {
326
534
  code: "approval_required",
327
- details: decision,
535
+ details: {
536
+ operation: decision.operation,
537
+ source: decision.source,
538
+ policy: decision.policy,
539
+ reason: "A stable host form approval is required",
540
+ rule: decision.approvalKind === "filesystem" ? "filesystem" : "path",
541
+ outcome: "unsupported",
542
+ actor: "unknown",
543
+ },
328
544
  retryable: true,
329
- suggestedNextCall: "policy_check",
545
+ suggestedNextCall: "diagnostics",
330
546
  },
331
547
  );
332
548
  }
333
549
 
334
- function approvalDenied(decision: PolicyDecision): Error {
550
+ function approvalResponseError(
551
+ decision: PolicyDecision,
552
+ outcome: ApprovalOutcome,
553
+ ): Error {
554
+ const code =
555
+ outcome === "cancelled"
556
+ ? "approval_cancelled"
557
+ : outcome === "malformed"
558
+ ? "approval_response_invalid"
559
+ : "approval_denied";
335
560
  return Object.assign(
336
561
  new Error(
337
- `User denied ${decision.operation} for ${decision.canonicalPath}`,
562
+ `Client returned ${outcome} for ${decision.operation} approval; the actor is unknown. Inspect diagnostics before retrying. Host session policy may override disk settings.`,
338
563
  ),
339
- { code: "approval_denied", retryable: false },
564
+ {
565
+ code,
566
+ details: {
567
+ outcome,
568
+ actor: "unknown",
569
+ operation: decision.operation,
570
+ source: decision.source,
571
+ policy: decision.policy,
572
+ reason:
573
+ decision.approvalKind === "filesystem"
574
+ ? "Project unrestricted filesystem access requires session approval"
575
+ : "The selected path policy requires approval",
576
+ rule:
577
+ decision.approvalKind === "filesystem"
578
+ ? "filesystem"
579
+ : decision.approvalKind === "probe"
580
+ ? "probe"
581
+ : "path",
582
+ },
583
+ retryable: outcome === "cancelled" || outcome === "malformed",
584
+ suggestedNextCall: "diagnostics",
585
+ },
340
586
  );
341
587
  }
342
588
 
589
+ function approvalMessage(tool: string, decision: PolicyDecision): string {
590
+ return [
591
+ `${tool} requests ${decision.operation} access.`,
592
+ `Path: ${decision.canonicalPath}`,
593
+ `Policy: ${decision.reason}`,
594
+ "Choose the narrowest approval that is appropriate.",
595
+ ].join("\n");
596
+ }
597
+
598
+ export function recordApprovalTransportFailure(
599
+ server: McpServer,
600
+ responseKey: unknown,
601
+ error: unknown,
602
+ ): void {
603
+ if (typeof responseKey !== "string") return;
604
+ const value = error as { name?: string; code?: unknown; message?: string };
605
+ const outcome: ApprovalOutcome =
606
+ value?.name === "TimeoutError" ||
607
+ value?.code === -32001 ||
608
+ /timeout|timed out/i.test(value?.message ?? "")
609
+ ? "timeout"
610
+ : value?.name === "AbortError"
611
+ ? "cancelled"
612
+ : "transport_error";
613
+ for (const [grantKey, challenge] of issuedChallenges) {
614
+ if (challenge.server !== server || challenge.responseKey !== responseKey)
615
+ continue;
616
+ observe(
617
+ {
618
+ server,
619
+ tool: challenge.tool,
620
+ context: { sessionId: challenge.sessionId } as ServerContext,
621
+ },
622
+ challenge.decision,
623
+ outcome,
624
+ );
625
+ issuedChallenges.delete(grantKey);
626
+ }
627
+ }
628
+
343
629
  function requestApproval(
344
630
  scope: ApprovalScope,
345
631
  decision: PolicyDecision,
@@ -350,21 +636,27 @@ function requestApproval(
350
636
  inputRequests: {
351
637
  [responseKey]: inputRequired.elicit({
352
638
  _meta: {
353
- codex_approval_kind: "mcp_tool_call",
354
- persist: decision.ruleId?.startsWith("filesystem:")
355
- ? ["session"]
356
- : ["session", "always"],
639
+ ...codexApprovalMetadata(
640
+ approvalClient(scope.server, scope.context).client,
641
+ decision.approvalKind === "filesystem",
642
+ decision.approvalKind === "probe",
643
+ ),
644
+ "io.ast-mcp/approvalChallenge": responseKey,
645
+ "io.ast-mcp/probe": decision.approvalKind === "probe",
357
646
  },
358
- message: [
359
- `${scope.tool} requests ${decision.operation} access.`,
360
- `Path: ${decision.canonicalPath}`,
361
- `Policy: ${decision.reason}`,
362
- "Choose the narrowest approval that is appropriate.",
363
- ].join("\n"),
647
+ message: approvalMessage(scope.tool, decision),
364
648
  requestedSchema: z.object({
365
- decision: decision.ruleId?.startsWith("filesystem:")
366
- ? z.enum(["deny", "allow_session"])
367
- : z.enum(["deny", "allow_once", "allow_session", "always_allow"]),
649
+ decision:
650
+ decision.approvalKind === "probe"
651
+ ? z.enum(["deny", "allow_once"])
652
+ : decision.approvalKind === "filesystem"
653
+ ? z.enum(["deny", "allow_session"])
654
+ : z.enum([
655
+ "deny",
656
+ "allow_once",
657
+ "allow_session",
658
+ "always_allow",
659
+ ]),
368
660
  }),
369
661
  }),
370
662
  },
@@ -374,18 +666,32 @@ function requestApproval(
374
666
 
375
667
  function pruneApprovalChallenges(now = Date.now()): void {
376
668
  for (const [grantKey, challenge] of issuedChallenges)
377
- if (challenge.expiresAt <= now) issuedChallenges.delete(grantKey);
669
+ if (challenge.expiresAt <= now) {
670
+ observe(
671
+ {
672
+ server: challenge.server,
673
+ tool: challenge.tool,
674
+ context: { sessionId: challenge.sessionId } as ServerContext,
675
+ },
676
+ challenge.decision,
677
+ "timeout",
678
+ );
679
+ issuedChallenges.delete(grantKey);
680
+ }
378
681
  }
379
682
 
380
683
  function storeApprovalChallenge(
381
684
  grantKey: string,
382
685
  scope: ApprovalScope,
383
686
  responseKey: string,
687
+ decision: PolicyDecision,
384
688
  ): void {
385
689
  pruneApprovalChallenges();
386
690
  const sessionId = scope.context?.sessionId ?? "connection";
387
691
  const sessionChallenges = [...issuedChallenges.values()].filter(
388
- (challenge) => challenge.sessionId === sessionId,
692
+ (challenge) =>
693
+ challenge.sessionId === sessionId &&
694
+ challenge.serverId === serverId(scope.server),
389
695
  ).length;
390
696
  if (
391
697
  issuedChallenges.size >= MAX_APPROVAL_CHALLENGES ||
@@ -398,9 +704,16 @@ function storeApprovalChallenge(
398
704
  { code: "approval_challenge_limit", retryable: true },
399
705
  );
400
706
  issuedChallenges.set(grantKey, {
401
- expiresAt: Date.now() + APPROVAL_CHALLENGE_TTL_MS,
707
+ createdAt: Date.now(),
708
+ expiresAt:
709
+ Date.now() +
710
+ (decision.approvalKind === "probe" ? 5000 : APPROVAL_CHALLENGE_TTL_MS),
402
711
  responseKey,
403
712
  sessionId,
713
+ serverId: serverId(scope.server),
714
+ server: scope.server!,
715
+ decision,
716
+ tool: scope.tool,
404
717
  });
405
718
  }
406
719
 
@@ -410,7 +723,10 @@ export function authorizeRequestedDecision(
410
723
  ): boolean {
411
724
  const scope = activeApproval.getStore();
412
725
  if (!scope?.context || !scope.server) return false;
413
- if (scope.requestScoped) throw approvalRequired(decision);
726
+ if (scope.requestScoped) {
727
+ observe(scope, decision, "unsupported");
728
+ throw approvalRequired(decision);
729
+ }
414
730
  pruneApprovalChallenges();
415
731
  const grantKey = key(decision, scope, generation);
416
732
  const invocationGrants = scope.invocationGrants ?? new Set<string>();
@@ -431,22 +747,23 @@ export function authorizeRequestedDecision(
431
747
  );
432
748
  if (accepted !== undefined) {
433
749
  issuedChallenges.delete(grantKey);
750
+ observe(scope, decision, "accepted");
434
751
  return accepted;
435
752
  }
436
- if (deniedResponse(response)) {
753
+ if (response !== undefined) {
754
+ const outcome = responseOutcome(response);
437
755
  issuedChallenges.delete(grantKey);
438
- throw approvalDenied(decision);
756
+ observe(scope, decision, outcome);
757
+ throw approvalResponseError(decision, outcome);
758
+ }
759
+ const { capabilities } = approvalClient(scope.server, scope.context);
760
+ if (!supportsApprovalForm(capabilities)) {
761
+ observe(scope, decision, "unsupported");
762
+ throw approvalRequired(decision);
439
763
  }
440
- const envelope = scope.context.mcpReq.envelope as
441
- | Record<string, unknown>
442
- | undefined;
443
- const capabilities =
444
- (envelope?.["io.modelcontextprotocol/clientCapabilities"] as
445
- | { elicitation?: unknown }
446
- | undefined) ?? scope.server.server.getClientCapabilities();
447
- if (!capabilities?.elicitation) throw approvalRequired(decision);
448
764
  const nextResponseKey = responseKey ?? approvalResponseKey();
449
- if (!challenge) storeApprovalChallenge(grantKey, scope, nextResponseKey);
765
+ if (!challenge)
766
+ storeApprovalChallenge(grantKey, scope, nextResponseKey, decision);
450
767
  throw requestApproval(scope, decision, nextResponseKey);
451
768
  }
452
769
 
@@ -467,6 +784,7 @@ function filesystemDecision(config: ResolvedConfig): PolicyDecision {
467
784
  policy: "request",
468
785
  reason:
469
786
  "Project configuration requests unrestricted access to the entire filesystem for this session",
787
+ approvalKind: "filesystem",
470
788
  ruleId: `filesystem:${fingerprint}`,
471
789
  source: "project",
472
790
  specificity: Number.MAX_SAFE_INTEGER,
@@ -510,15 +828,58 @@ export function approvalSessionId(): string {
510
828
  return activeApproval.getStore()?.context?.sessionId ?? "local";
511
829
  }
512
830
 
513
- export function clearSessionApprovals(sessionId?: string): void {
514
- if (!sessionId) {
831
+ export function clearSessionApprovals(
832
+ sessionId?: string,
833
+ server?: McpServer,
834
+ ): void {
835
+ const identity = server ? serverId(server) : undefined;
836
+ if (!sessionId && !server) {
515
837
  sessionGrants.clear();
516
838
  issuedChallenges.clear();
839
+ observations = new WeakMap();
517
840
  return;
518
841
  }
519
- const prefix = `${sessionId}\u0000`;
520
- for (const grantKey of sessionGrants)
521
- if (grantKey.startsWith(prefix)) sessionGrants.delete(grantKey);
842
+ for (const grantKey of sessionGrants) {
843
+ const [session, instance] = grantKey.split("\u0000");
844
+ if (
845
+ (!sessionId || session === sessionId) &&
846
+ (!identity || instance === identity)
847
+ )
848
+ sessionGrants.delete(grantKey);
849
+ }
522
850
  for (const [grantKey, challenge] of issuedChallenges)
523
- if (challenge.sessionId === sessionId) issuedChallenges.delete(grantKey);
851
+ if (
852
+ (!sessionId || challenge.sessionId === sessionId) &&
853
+ (!identity || challenge.serverId === identity)
854
+ )
855
+ issuedChallenges.delete(grantKey);
856
+ if (server) {
857
+ if (sessionId) observations.get(server)?.delete(sessionId);
858
+ else observations.delete(server);
859
+ }
860
+ }
861
+
862
+ export function runApprovalProbe(): { outcome: ApprovalOutcome } {
863
+ const decision: PolicyDecision = {
864
+ canonicalPath: "approval probe",
865
+ operation: "read",
866
+ policy: "request",
867
+ reason: "Diagnostic confirmation only. Acceptance grants no file access.",
868
+ approvalKind: "probe",
869
+ ruleId: "diagnostic-probe",
870
+ source: "baseline",
871
+ specificity: 0,
872
+ symlinks: false,
873
+ };
874
+ try {
875
+ if (!authorizeRequestedDecision(decision, 0))
876
+ return { outcome: "unsupported" };
877
+ return { outcome: "accepted" };
878
+ } catch (error) {
879
+ if (error instanceof InputRequiredSignal) throw error;
880
+ const details = (error as { details?: { outcome?: ApprovalOutcome } })
881
+ .details;
882
+ if (details?.outcome) return { outcome: details.outcome };
883
+ throw error;
884
+ }
524
885
  }