@actuarial-ts/agents 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +4 -2
  2. package/dist/advisor.d.ts +2 -1
  3. package/dist/advisor.d.ts.map +1 -1
  4. package/dist/advisor.js +3 -1
  5. package/dist/advisor.js.map +1 -1
  6. package/dist/divergence.d.ts +267 -0
  7. package/dist/divergence.d.ts.map +1 -0
  8. package/dist/divergence.js +414 -0
  9. package/dist/divergence.js.map +1 -0
  10. package/dist/errors.d.ts +1 -1
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +20 -0
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +4 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +4 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/judgment.d.ts +26 -0
  19. package/dist/judgment.d.ts.map +1 -1
  20. package/dist/judgment.js +21 -0
  21. package/dist/judgment.js.map +1 -1
  22. package/dist/mcp.d.ts +165 -0
  23. package/dist/mcp.d.ts.map +1 -0
  24. package/dist/mcp.js +155 -0
  25. package/dist/mcp.js.map +1 -0
  26. package/dist/promotion.d.ts +295 -0
  27. package/dist/promotion.d.ts.map +1 -0
  28. package/dist/promotion.js +824 -0
  29. package/dist/promotion.js.map +1 -0
  30. package/dist/remote.d.ts +221 -0
  31. package/dist/remote.d.ts.map +1 -0
  32. package/dist/remote.js +295 -0
  33. package/dist/remote.js.map +1 -0
  34. package/dist/tools.d.ts +87 -6
  35. package/dist/tools.d.ts.map +1 -1
  36. package/dist/tools.js +182 -15
  37. package/dist/tools.js.map +1 -1
  38. package/package.json +11 -4
  39. package/src/advisor.ts +141 -0
  40. package/src/divergence.ts +642 -0
  41. package/src/errors.ts +62 -0
  42. package/src/evals.ts +162 -0
  43. package/src/index.ts +9 -0
  44. package/src/judgment.ts +458 -0
  45. package/src/mcp.ts +274 -0
  46. package/src/promotion.ts +1240 -0
  47. package/src/remote.ts +371 -0
  48. package/src/tools.ts +561 -0
package/dist/judgment.js CHANGED
@@ -40,12 +40,27 @@ import { createLedger, recordAssumption, } from "@actuarial-ts/compliance";
40
40
  import { AgentsError } from "./errors.js";
41
41
  import { zodObjectShape } from "./tools.js";
42
42
  // ---------------------------------------------------------------------------
43
+ // Public types
44
+ /**
45
+ * The request-context key a host sets (server-side, from its authenticated
46
+ * session — the same trust path as the tenant id) to identify WHO is resuming
47
+ * gates. The resume payload cannot supply it: a payload travels through
48
+ * model-reachable surfaces, and an identity that can be asserted from there
49
+ * is a claim, not a record.
50
+ */
51
+ export const ACTOR_IDENTITY_CONTEXT_KEY = "actorIdentity";
52
+ // ---------------------------------------------------------------------------
43
53
  // Chain state threaded through step outputs
54
+ // Declares EVERY JudgmentTrailEntry field: zod strips undeclared keys on the
55
+ // step-output parse, so an undeclared field here is silently erased between
56
+ // gates (the ledger schema below carries the same warning for the same reason).
44
57
  const trailEntrySchema = z.object({
45
58
  stage: z.string(),
46
59
  decision: z.string(),
47
60
  rationale: z.string(),
48
61
  skipped: z.boolean(),
62
+ actor: z.enum(["default", "actuary", "agent"]).optional(),
63
+ actorIdentity: z.string().optional(),
49
64
  });
50
65
  // Declares EVERY AssumptionEntry field: zod strips undeclared keys on parse,
51
66
  // and losing previousValue/source between steps would corrupt the ledger.
@@ -180,6 +195,10 @@ export function createJudgmentChain(options) {
180
195
  throw new AgentsError("MISSING_RATIONALE", `Gate "${gate.id}" (${gate.stage}) resumed without a rationale; undocumented judgment is exactly what the ledger exists to prevent`);
181
196
  }
182
197
  const actor = actorOf(decision);
198
+ // WHO decided comes from the server-set context, never the payload:
199
+ // the payload's job is the decision and its coarse classification.
200
+ const rawIdentity = requestContext?.get(ACTOR_IDENTITY_CONTEXT_KEY);
201
+ const actorIdentity = typeof rawIdentity === "string" && rawIdentity.length > 0 ? rawIdentity : undefined;
183
202
  const applied = await gate.applyDecision(ctx, decision);
184
203
  // recordAssumption is the single validator/freezer: replay the
185
204
  // threaded entries into a ledger, append, and thread the plain
@@ -200,6 +219,8 @@ export function createJudgmentChain(options) {
200
219
  trail: [
201
220
  ...state.trail,
202
221
  {
222
+ actor,
223
+ ...(actorIdentity !== undefined ? { actorIdentity } : {}),
203
224
  stage: gate.stage,
204
225
  decision: applied.summary ?? describeDecision(decision),
205
226
  rationale,
@@ -1 +1 @@
1
- {"version":3,"file":"judgment.js","sourceRoot":"","sources":["../src/judgment.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,YAAY,EACZ,gBAAgB,GAKjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAsH5C,8EAA8E;AAC9E,4CAA4C;AAE5C,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;IACpB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE;CACrB,CAAC,CAAC;AAEH,6EAA6E;AAC7E,0EAA0E;AAC1E,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACjC,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IAChC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IAC9C,KAAK,EAAE,CAAC,CAA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AC;IAC9B,KAAK,MAAM,IAAI,IAAI,SAAS;QAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3D,OAAO,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,EAA2B,CAAC;AACtE,CAAC"}
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * MCP tenant seam + boot self-test for the governed workspace.
3
+ *
4
+ * When the workspace is exposed over the Model Context Protocol, external AI
5
+ * clients read everything and mutate nothing directly. The one hard guarantee
6
+ * is that EVERY exposed tool resolves its tenant (project id) from the MCP
7
+ * request's auth info, never from the model — the same secureToolWrapper rule
8
+ * the ActNG server proved in production, restated for the MCP transport.
9
+ *
10
+ * @mastra/mcp gives no built-in per-tool authorization outside its EE FGA path,
11
+ * so a missed wire-up FAILS OPEN: a tool that forgets to read authInfo would
12
+ * happily serve an unauthenticated caller. These two helpers close that caveat:
13
+ *
14
+ * 1. requireMcpTenant — the read side. A tool calls it instead of trusting the
15
+ * model; absent auth info it THROWS AgentsError("NO_TENANT_CONTEXT"), which
16
+ * the defineActuarialTool wrapper turns into a { success:false } envelope.
17
+ * A tool built on it fails CLOSED.
18
+ *
19
+ * 2. assertFailClosed — the proof. At server startup, drive a probe read tool
20
+ * through the server WITHOUT auth and assert it fails closed. If the probe
21
+ * SUCCEEDS, the seam is not wired up: this throws MCP_SELF_TEST_FAILED and
22
+ * startup MUST abort.
23
+ *
24
+ * ---------------------------------------------------------------------------
25
+ * VERIFIED against the installed @mastra/mcp 1.14.0 (house rule — types and
26
+ * compiled source, not memory):
27
+ *
28
+ * - MCPServer.executeTool(toolId, args, executionContext?: { messages?,
29
+ * toolCallId?, requestContext? }): Promise<any> returns the tool's execute
30
+ * result VERBATIM (dist/index.js: `const result = await tool.execute(...);
31
+ * return result;`). For a defineActuarialTool with no outputSchema the core
32
+ * tool builder passes the value through untouched, so an executeTool caller
33
+ * sees exactly the { success:false, error:{ code } } envelope the wrapper
34
+ * produced. Argument validation runs FIRST and, on failure, short-circuits
35
+ * to a { error:true, message } object before the tool ever executes — hence
36
+ * assertFailClosed passes minimal VALID probe args.
37
+ *
38
+ * - Auth-context access path. On the real streamable-HTTP call path the SDK
39
+ * copies the transport `extra` (with `authInfo` from `req.auth`) into the
40
+ * tool context TWO ways: directly at `context.mcp.extra`, and — via
41
+ * createProxiedRequestContext — as INDIVIDUAL keys set on a fresh
42
+ * RequestContext (`context.requestContext.get("authInfo")`). NOTE the
43
+ * surprise: the installed 1.14.0 sets each extra key on the RequestContext
44
+ * verbatim, so the tenant lives at `requestContext.get("authInfo")`, NOT
45
+ * under a single `"mcp.extra"` key as the research draft documented. This
46
+ * helper tries all three shapes so it is correct against both the installed
47
+ * package and the documented pattern.
48
+ */
49
+ import type { ActuarialToolContext } from "./tools.js";
50
+ import { type AgentsErrorCode } from "./errors.js";
51
+ /**
52
+ * The MCP auth-info bag: whatever the host's bearer-token middleware set on
53
+ * `req.auth` before delegating to startHTTP (e.g. `{ projectId }`). Values are
54
+ * unknown — requireMcpTenant proves the tenant is a non-empty string.
55
+ */
56
+ export interface McpAuthInfo {
57
+ [key: string]: unknown;
58
+ }
59
+ /**
60
+ * The transport `extra` (MCP SDK RequestHandlerExtra) surfaced to a tool at
61
+ * `context.mcp.extra`. Only `authInfo` is load-bearing here; the rest
62
+ * (sessionId, requestInfo, signal, ...) is carried opaquely.
63
+ */
64
+ export interface McpRequestExtra {
65
+ authInfo?: McpAuthInfo;
66
+ [key: string]: unknown;
67
+ }
68
+ /**
69
+ * The structural slice of a Mastra tool-execution context this seam needs on
70
+ * the MCP path: the tenant-seam `requestContext` (inherited from
71
+ * ActuarialToolContext) plus the MCP-specific `mcp.extra`. Typed structurally
72
+ * so tests exercise the helper with a plain object and no live MCP server.
73
+ */
74
+ export interface McpToolContext extends ActuarialToolContext {
75
+ mcp?: {
76
+ extra?: McpRequestExtra;
77
+ };
78
+ }
79
+ /**
80
+ * Reads the tenant id (default key "projectId") from the MCP execution
81
+ * context's auth info — the server-set identity, never the model. THROWS a
82
+ * typed AgentsError("NO_TENANT_CONTEXT") when the auth info or the key is
83
+ * absent, non-string, or empty. Inside a defineActuarialTool execute the
84
+ * wrapper converts that throw into a { success:false } envelope, so a tool
85
+ * built on requireMcpTenant fails CLOSED for any unauthenticated MCP caller.
86
+ */
87
+ export declare function requireMcpTenant(context: McpToolContext | undefined, key?: string): string;
88
+ /**
89
+ * The structural slice of @mastra/mcp's MCPServer that assertFailClosed drives.
90
+ * A real MCPServer satisfies it; so does a bare `{ executeTool }` stub, so the
91
+ * self-test is unit-testable without booting a transport. Verified against the
92
+ * installed executeTool signature (see the file header).
93
+ */
94
+ export interface McpToolServer {
95
+ executeTool(toolId: string, args: Record<string, unknown>, executionContext?: {
96
+ requestContext?: unknown;
97
+ messages?: unknown[];
98
+ toolCallId?: string;
99
+ }): Promise<unknown>;
100
+ /**
101
+ * Tool enumeration, present on the installed @mastra/mcp MCPServer. The
102
+ * DECLARATION (server.d.ts) types entries by `name` and allows a Promise
103
+ * return; the runtime also carries `id`. Typed from the declaration — a
104
+ * runtime probe is how the first draft of this signature broke assignability.
105
+ * Optional so a bare `{ executeTool }` stub still satisfies the type; the
106
+ * self-test's probe-everything form requires it and says so when absent.
107
+ */
108
+ getToolListInfo?(): {
109
+ tools: Array<{
110
+ name: string;
111
+ id?: string;
112
+ }>;
113
+ } | Promise<{
114
+ tools: Array<{
115
+ name: string;
116
+ id?: string;
117
+ }>;
118
+ }>;
119
+ }
120
+ export interface AssertFailClosedOptions {
121
+ /** The MCP server whose exposed tools are being wired up (typically the workspace MCPServer). */
122
+ server: McpToolServer;
123
+ /**
124
+ * Probe ONE tool instead of every tool. Prefer omitting this: the
125
+ * single-tool form proved exactly one wire-up, and a sibling tool that
126
+ * skipped the tenant seam sailed through boot while serving every tenant's
127
+ * data to unauthenticated callers.
128
+ */
129
+ probeToolId?: string;
130
+ /**
131
+ * Minimal VALID args for the single-tool form. Defaults to `{}`
132
+ * (correct for read tools whose schema is `z.object({})` or all-optional).
133
+ * Args that fail schema validation would short-circuit before the tenant
134
+ * check runs, so pass real minimal args for probes that require input.
135
+ */
136
+ probeArgs?: Record<string, unknown>;
137
+ /**
138
+ * Per-tool minimal valid args for the probe-everything form, keyed by tool
139
+ * id. Any tool not listed is driven with `{}`.
140
+ */
141
+ argsByTool?: Record<string, Record<string, unknown>>;
142
+ /**
143
+ * Tools that are tenant-free BY DESIGN and therefore expected to succeed
144
+ * without auth. The same contract as `tenant: "none"` on the definition:
145
+ * greppable, deliberate, reviewable. A name listed here that is not on the
146
+ * server fails the self-test — a stale exemption is how the next leak hides.
147
+ */
148
+ exempt?: string[];
149
+ /** The failure code every probed tool must fail closed with. Defaults to NO_TENANT_CONTEXT. */
150
+ expectedErrorCode?: AgentsErrorCode;
151
+ }
152
+ /**
153
+ * The boot self-test. Drives EVERY tool on the server WITHOUT any auth info
154
+ * and asserts each fails closed with the tenant error code, reporting every
155
+ * hole at once. THROWS AgentsError("MCP_SELF_TEST_FAILED") loudly for any
156
+ * other outcome — most importantly if a probe SUCCEEDED, which means that tool
157
+ * did not require tenant context and the MCP tenant seam is a fail-open hole.
158
+ * Tenant-free-by-design tools are excused only via the greppable `exempt`
159
+ * list; a single-tool form remains for targeted re-checks.
160
+ *
161
+ * Call this at server startup whenever MCP is enabled, and ABORT startup if it
162
+ * throws: a governed workspace must never accept unauthenticated MCP clients.
163
+ */
164
+ export declare function assertFailClosed(options: AssertFailClosedOptions): Promise<void>;
165
+ //# sourceMappingURL=mcp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH,OAAO,KAAK,EAAE,oBAAoB,EAAuB,MAAM,YAAY,CAAC;AAE5E,OAAO,EAAe,KAAK,eAAe,EAAE,MAAM,aAAa,CAA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ACrB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IACrD;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,+FAA+F;IAC/F,iBAAiB,CAAC,EAAE,eAAe,CAAC;CACrC;AA0BD;;;;;;;;;;;GAWG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,IAAI,CAAC,CAmDtF"}
package/dist/mcp.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * MCP tenant seam + boot self-test for the governed workspace.
3
+ *
4
+ * When the workspace is exposed over the Model Context Protocol, external AI
5
+ * clients read everything and mutate nothing directly. The one hard guarantee
6
+ * is that EVERY exposed tool resolves its tenant (project id) from the MCP
7
+ * request's auth info, never from the model — the same secureToolWrapper rule
8
+ * the ActNG server proved in production, restated for the MCP transport.
9
+ *
10
+ * @mastra/mcp gives no built-in per-tool authorization outside its EE FGA path,
11
+ * so a missed wire-up FAILS OPEN: a tool that forgets to read authInfo would
12
+ * happily serve an unauthenticated caller. These two helpers close that caveat:
13
+ *
14
+ * 1. requireMcpTenant — the read side. A tool calls it instead of trusting the
15
+ * model; absent auth info it THROWS AgentsError("NO_TENANT_CONTEXT"), which
16
+ * the defineActuarialTool wrapper turns into a { success:false } envelope.
17
+ * A tool built on it fails CLOSED.
18
+ *
19
+ * 2. assertFailClosed — the proof. At server startup, drive a probe read tool
20
+ * through the server WITHOUT auth and assert it fails closed. If the probe
21
+ * SUCCEEDS, the seam is not wired up: this throws MCP_SELF_TEST_FAILED and
22
+ * startup MUST abort.
23
+ *
24
+ * ---------------------------------------------------------------------------
25
+ * VERIFIED against the installed @mastra/mcp 1.14.0 (house rule — types and
26
+ * compiled source, not memory):
27
+ *
28
+ * - MCPServer.executeTool(toolId, args, executionContext?: { messages?,
29
+ * toolCallId?, requestContext? }): Promise<any> returns the tool's execute
30
+ * result VERBATIM (dist/index.js: `const result = await tool.execute(...);
31
+ * return result;`). For a defineActuarialTool with no outputSchema the core
32
+ * tool builder passes the value through untouched, so an executeTool caller
33
+ * sees exactly the { success:false, error:{ code } } envelope the wrapper
34
+ * produced. Argument validation runs FIRST and, on failure, short-circuits
35
+ * to a { error:true, message } object before the tool ever executes — hence
36
+ * assertFailClosed passes minimal VALID probe args.
37
+ *
38
+ * - Auth-context access path. On the real streamable-HTTP call path the SDK
39
+ * copies the transport `extra` (with `authInfo` from `req.auth`) into the
40
+ * tool context TWO ways: directly at `context.mcp.extra`, and — via
41
+ * createProxiedRequestContext — as INDIVIDUAL keys set on a fresh
42
+ * RequestContext (`context.requestContext.get("authInfo")`). NOTE the
43
+ * surprise: the installed 1.14.0 sets each extra key on the RequestContext
44
+ * verbatim, so the tenant lives at `requestContext.get("authInfo")`, NOT
45
+ * under a single `"mcp.extra"` key as the research draft documented. This
46
+ * helper tries all three shapes so it is correct against both the installed
47
+ * package and the documented pattern.
48
+ */
49
+ import { resolveTenant } from "./tools.js";
50
+ import { AgentsError } from "./errors.js";
51
+ /**
52
+ * Reads the tenant id (default key "projectId") from the MCP execution
53
+ * context's auth info — the server-set identity, never the model. THROWS a
54
+ * typed AgentsError("NO_TENANT_CONTEXT") when the auth info or the key is
55
+ * absent, non-string, or empty. Inside a defineActuarialTool execute the
56
+ * wrapper converts that throw into a { success:false } envelope, so a tool
57
+ * built on requireMcpTenant fails CLOSED for any unauthenticated MCP caller.
58
+ */
59
+ export function requireMcpTenant(context, key = "projectId") {
60
+ // One seam, one reader: this is resolveTenant with the MCP source pinned.
61
+ // Prefer declaring `tenant: "required", tenantSource: "mcp-auth"` on the
62
+ // tool itself, which makes the wrapper do this before the body runs.
63
+ return resolveTenant(context, { source: "mcp-auth", key });
64
+ }
65
+ /** Structural check for the { success:false, error:{ code } } tool-failure envelope. */
66
+ function isFailureEnvelope(result) {
67
+ if (typeof result !== "object" || result === null)
68
+ return false;
69
+ if (result.success !== false)
70
+ return false;
71
+ const error = result.error;
72
+ return typeof error?.code === "string";
73
+ }
74
+ /** A short, log-safe description of an unexpected probe result for the abort message. */
75
+ function describeResult(result) {
76
+ if (isFailureEnvelope(result)) {
77
+ return `a { success: false } envelope with code "${result.error.code}"`;
78
+ }
79
+ if (typeof result === "object" && result !== null) {
80
+ if (result.error === true) {
81
+ return "an argument-validation error (the probe never reached the tenant check — pass valid probeArgs)";
82
+ }
83
+ if (result.success === true) {
84
+ return "a { success: true } result (the probe SUCCEEDED without tenant context — the seam is not wired up)";
85
+ }
86
+ }
87
+ return "a non-envelope result (the probe did not fail closed on tenant context)";
88
+ }
89
+ /**
90
+ * The boot self-test. Drives EVERY tool on the server WITHOUT any auth info
91
+ * and asserts each fails closed with the tenant error code, reporting every
92
+ * hole at once. THROWS AgentsError("MCP_SELF_TEST_FAILED") loudly for any
93
+ * other outcome — most importantly if a probe SUCCEEDED, which means that tool
94
+ * did not require tenant context and the MCP tenant seam is a fail-open hole.
95
+ * Tenant-free-by-design tools are excused only via the greppable `exempt`
96
+ * list; a single-tool form remains for targeted re-checks.
97
+ *
98
+ * Call this at server startup whenever MCP is enabled, and ABORT startup if it
99
+ * throws: a governed workspace must never accept unauthenticated MCP clients.
100
+ */
101
+ export async function assertFailClosed(options) {
102
+ const { server, probeToolId, probeArgs = {}, expectedErrorCode = "NO_TENANT_CONTEXT" } = options;
103
+ // Single-tool form: kept for hosts that need a targeted re-check, but the
104
+ // probe-everything form below is the one to call at boot.
105
+ if (probeToolId !== undefined) {
106
+ await probeOne(server, probeToolId, probeArgs, expectedErrorCode);
107
+ return;
108
+ }
109
+ if (typeof server.getToolListInfo !== "function") {
110
+ throw new AgentsError("MCP_SELF_TEST_FAILED", "MCP boot self-test cannot enumerate this server's tools (no getToolListInfo); " +
111
+ "pass probeToolId per tool, or upgrade @mastra/mcp. Refusing to certify a server " +
112
+ "whose tool list cannot be inspected.");
113
+ }
114
+ const listing = await server.getToolListInfo();
115
+ const toolIds = listing.tools.map((tool) => tool.id ?? tool.name);
116
+ const exempt = new Set(options.exempt ?? []);
117
+ const failures = [];
118
+ // A stale exemption is a future hole: the tool it excused is gone, and the
119
+ // next tool to take that name inherits a free pass nobody remembers granting.
120
+ for (const name of exempt) {
121
+ if (!toolIds.includes(name)) {
122
+ failures.push(`"${name}" is exempted but not on the server; remove the stale exemption`);
123
+ }
124
+ }
125
+ for (const toolId of toolIds) {
126
+ if (exempt.has(toolId))
127
+ continue;
128
+ try {
129
+ await probeOne(server, toolId, options.argsByTool?.[toolId] ?? {}, expectedErrorCode);
130
+ }
131
+ catch (err) {
132
+ // Collect EVERY hole before reporting: a boot test that stops at the
133
+ // first one hides the second.
134
+ failures.push(err instanceof AgentsError ? err.message : String(err));
135
+ }
136
+ }
137
+ if (failures.length > 0) {
138
+ throw new AgentsError("MCP_SELF_TEST_FAILED", `MCP boot self-test failed on ${failures.length} of ${toolIds.length} tool(s):\n` +
139
+ failures.map((message) => ` - ${message}`).join("\n") +
140
+ "\nAbort startup: a governed workspace must never accept unauthenticated MCP clients.");
141
+ }
142
+ }
143
+ /** Drives one tool with no auth info; it must fail closed with the expected code. */
144
+ async function probeOne(server, toolId, args, expectedErrorCode) {
145
+ // No requestContext, no mcp.extra -> the probe sees no auth info at all.
146
+ const result = await server.executeTool(toolId, args, {});
147
+ if (isFailureEnvelope(result) && result.error.code === expectedErrorCode) {
148
+ return;
149
+ }
150
+ throw new AgentsError("MCP_SELF_TEST_FAILED", `probe tool "${toolId}" did not fail closed without auth. ` +
151
+ `Expected a { success: false, error.code: "${expectedErrorCode}" } envelope but got ${describeResult(result)}. ` +
152
+ `An MCP-exposed tool must either enforce the tenant seam (tenant: "required", tenantSource: "mcp-auth") ` +
153
+ "or be a declared exemption; this outcome means it is neither.");
154
+ }
155
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1 @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