Repository navigation
feat: add pre-execution tool policy interface - #377
Closed
barryroodt wants to merge 19 commits into
Closed
barryroodt wants to merge 19 commits into
barryroodt wants to merge 19 commits into
Conversation
Coverage Report for CI Build 33064113501Coverage remained the same at 96.52%Details
Uncovered ChangesNo uncovered changes found. Coverage RegressionsNo coverage regressions found. Coverage Stats
💛 - Coveralls |
Absorbs the plan's `feat: normalize MCP structured tool results` boundary. Structured result normalization and the policy seam cannot be split into two byte-safe commits. A policy-free tool must keep its `tools/list` and `tools/call` bytes identical to fc54ea2 on every serving path, and on the frozen public surface an attached `policy` is the only thing that can activate normalization: `formatResult` must never change byte shape, no new normalization toggle may be added, and `outputSchema` stays required on `Tool` so its presence cannot discriminate. A commit introducing normalization before the policy seam existed would therefore either normalize unconditionally, breaking policy-free bytes, or carry no observable normalization contract at all. Landing both together keeps every commit individually byte-safe with its own tests green.
Guard the decision before the audit record is built, so an unrecognized decision can no longer reach the sink as a raw string outside the declared union, and a nullish decision no longer throws before any record exists. The union narrows first; the fire-and-forget callback is then scheduled exactly once per request, ahead of all three branches. `decision` widens to 'execute' | 'result' | 'rejected', where 'rejected' is this package's own outcome for a decision it could not recognize. Also correct two JSDoc claims: the audit callback is not awaited and its completion is neither ordered before the response nor guaranteed, and `resolveParameters` guarantees one shared hook call, not identical advertised and enforced schemas, since `.strict()` applies at parse only.
Assert the 'rejected' audit record on both fail-closed shapes, an unknown decision type and a nullish decision, and that a never-settling audit sink cannot delay the tool result. Repair the widening fixture so it demonstrates a servable pattern: the resolution carries the era and execute satisfies the schema the request advertised. The added modern call pins the hook-supplied input schema on the call path, and a legacy call pins that a contextually hidden tool stays callable while absent from tools/list. Drop the racing negative console assertion from the no-telemetry test; the positive record assertion carries that invariant.
`resolveParameters` returned the hook's schema unmodified while the call path appended `.strict()` before parsing, so a policy returning a loose or catchall object advertised unknown keys as acceptable and then rejected them. Apply `.strict()` inside `resolveParameters` instead: both paths now serialize and parse the identical schema object, which is what the function's own contract claims. Policy-free tools have no hook and already advertised `additionalProperties: false`, so the measured base byte fixtures pin that this changes nothing on that lane.
A normalized request advertised an output schema and then emitted whatever `execute` returned, so a widening policy hook could ship `structuredContent` its own advertised schema rejects. The obligation is the server's, not the client's, so check it at emission. Three checks, each independent of the others: - Discovery requires the resolved output schema to be object-rooted, which is MCP's restriction on structured output. A non-object root is an authoring error, so it throws and fails the whole `tools/list` response: dropping only the `outputSchema` key would advertise the suppressed shape while the call path still emits `structuredContent`, and dropping the entry would silently hide a tool on a policy bug. - Emission requires a plain object. The hook may resolve a non-object schema, under which `null` or a scalar parses successfully and is still output MCP does not permit at the root. - Emission parses the business result against the resolved schema and answers `isError` naming the offending fields on a mismatch. Policy-free and suppressed requests advertise nothing and are untouched, including their empty answer to a nullish result. Policy `result` decisions stay verbatim pass-through.
…s-is
The emission check parsed the business result and then emitted the result
itself, but a successful parse is not agreement. A zod object strips
undeclared keys while reporting success, and the advertised JSON for that
same schema says `additionalProperties: false`, so an extra key was
mismatched output that shipped anyway. Emitting the parsed value instead
would have been just as wrong in the other direction: it silently drops a
field the tool meant to return.
Require the schema to have accepted the result as-is, by comparing the
parsed value against the raw one as JSON values, and answer `isError`
naming the mismatch when they differ. On agreement the raw result is
emitted, so `structuredContent` equals the business result literally.
The plain-object check is now prototype-exact. A `Date`, or anything else
carrying `toJSON`, serializes to a non-object root, and a `Map` or `Set`
serializes to `{}` and drops its contents, both of which a `typeof` check
admits. Reachable whenever a hook resolves a permissive schema, which is
the case the check exists for independently of the parse.
Consequence documented on the hook: a transforming or coercing output
schema is unsupported by construction, since conformance is identity.
The JSON-value precondition behind the emission guard was enforced at the root only, but the equality walk recurses past it. Under a permissive leaf (z.any(), z.unknown()) zod returns its input by identity, so the walk's a === b fast path fired and a Map, Set, Date, Infinity or class instance one level down reached the wire mangled by serialization. NaN failed, but only because NaN !== NaN, and reported the wrong cause. Parse the JSON round trip of the result instead of the raw result. Anything JSON cannot represent faithfully now either fails that parse or diverges from the raw result in the equality walk, which still compares against, and still emits, the untouched business result. Both doc comments claimed a precondition the code never enforced; they now describe divergence as the mechanism.
The conforming-result test gates the choice to emit the business result rather than parsed.data, which is what keeps the validation lane byte-transparent. Its fixture declared its keys in the same order as the schema, and zod rebuilds a parsed object in schema-declaration order, so switching the emission to parsed.data kept the test green. Declare the schema fields in the opposite order from the fixture. The correct implementation still passes, because the equality walk is key-order-insensitive by design; the parsed.data mutant now fails on key order. Every existing assertion is unchanged.
barryroodt
force-pushed
the
barryroodt/ai-1091-tool-policy-foundation
branch
from
August 27, 2026 10:41
ee1f4e1 to
9ecf0bd
Compare
Contributor
Author
|
Closing this as superseded by #391, which replaces the broader |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR A of three for AI-1091. This targets
main; PR B stacks on it.What
ToolPolicy,ToolPolicyDecision,ToolRequestContext, andToolPolicyTelemetrycontracts.hidden, input, and output hooks. Hidden tools remain callable by name. Known fields normalize before strict parsing, so advertised input matches enforced input.rejected.formatResultreceives a copy and cannot mutate it.requestStatethrough exactly. Policy-free behavior and bytes remain unchanged.Why
This is the product-neutral foundation for #378 and #379, aligned with AI-1091 and the RFC. It adds no user-visible elicitation or Supabase-specific policy.
#378 uses contextual
outputSchemafor terminal variants. #379 usesinputSchema,outputSchema, andnormalizeArgumentsfor cost routing; its directconfirm_costmigration uses contextualhiddenafter restacking.How to Review
Confirm the public surface
packages/mcp-utils/src/index.tsRead the policy contract
packages/mcp-utils/src/tool-policy.tsToolRequestContext,ToolPolicyDecision, required telemetry fields, and policy hooks.Follow the request flow
packages/mcp-utils/src/server.tsToolandMcpServerOptions, thentools/listandtools/call. Check contextualhidden, normalization before strict parsing, fail-closed decisions, exact(args, resolution)execution, output validation, request-state pass-through, and non-blocking telemetry.Read the contract tests
packages/mcp-utils/src/tool-policy.test.tsandpackages/mcp-utils/src/server.test.tsReview questions
Verification
Passed:
CI=1 mise exec -- pnpm --filter @supabase/mcp-utils test runCI=1 mise exec -- pnpm --filter @supabase/mcp-server-supabase test run --project unitmise exec -- pnpm buildmise exec -- pnpm format:checkThe
mcp-server-postgrestbase/head differential reproduced the same failure set with identical normalized received values. The diff remains five files underpackages/mcp-utils.