Skip to content

feat: add pre-execution tool policy interface - #377

Closed
barryroodt wants to merge 19 commits into
mainfrom
barryroodt/ai-1091-tool-policy-foundation
Closed

barryroodt wants to merge 19 commits into
mainfrom
barryroodt/ai-1091-tool-policy-foundation

Conversation

@barryroodt

@barryroodt barryroodt commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

PR A of three for AI-1091. This targets main; PR B stacks on it.

What

  • Adds public ToolPolicy, ToolPolicyDecision, ToolRequestContext, and ToolPolicyTelemetry contracts.
  • Adds contextual hidden, input, and output hooks. Hidden tools remain callable by name. Known fields normalize before strict parsing, so advertised input matches enforced input.
  • Fails closed on unknown or nullish decisions and audits them as rejected.
  • Requires object-rooted, JSON-faithful structured output whose advertised and enforced schemas agree without transform, coercion, or stripping. The wire result is the validated snapshot; formatResult receives a copy and cannot mutate it.
  • Makes policy telemetry non-blocking, with required policy identity and outcome. Passes requestState through 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 outputSchema for terminal variants. #379 uses inputSchema, outputSchema, and normalizeArguments for cost routing; its direct confirm_cost migration uses contextual hidden after restacking.

How to Review

  1. Confirm the public surface

    • packages/mcp-utils/src/index.ts
    • Verify the intended public exports and nothing more.
  2. Read the policy contract

    • packages/mcp-utils/src/tool-policy.ts
    • Check ToolRequestContext, ToolPolicyDecision, required telemetry fields, and policy hooks.
  3. Follow the request flow

    • packages/mcp-utils/src/server.ts
    • Follow Tool and McpServerOptions, then tools/list and tools/call. Check contextual hidden, normalization before strict parsing, fail-closed decisions, exact (args, resolution) execution, output validation, request-state pass-through, and non-blocking telemetry.
  4. Read the contract tests

    • packages/mcp-utils/src/tool-policy.test.ts and packages/mcp-utils/src/server.test.ts
    • Check policy ordering, decisions, telemetry, structured results, request state, and policy-free bytes.

Review questions

  • Is the public API product-neutral and minimal?
  • Do discovery and execution advertise and enforce the same contracts?
  • Does every failure avoid business execution?
  • Do policy-free tools remain unchanged?

Verification

Passed:

  • CI=1 mise exec -- pnpm --filter @supabase/mcp-utils test run
  • CI=1 mise exec -- pnpm --filter @supabase/mcp-server-supabase test run --project unit
  • mise exec -- pnpm build
  • mise exec -- pnpm format:check

The mcp-server-postgrest base/head differential reproduced the same failure set with identical normalized received values. The diff remains five files under packages/mcp-utils.

@coveralls

coveralls commented Aug 25, 2026 •

Copy link
Copy Markdown

Coverage Report for CI Build 33064113501

Coverage remained the same at 96.52%

Details

  • Coverage remained the same as the base build.
  • Patch coverage: No coverable lines changed in this PR.
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 3036
Covered Lines: 2951
Line Coverage: 97.2%
Relevant Branches: 384
Covered Branches: 350
Branch Coverage: 91.15%
Branches in Coverage %: Yes
Coverage Strength: 50.92 hits per line

💛 - Coveralls

@barryroodt barryroodt self-assigned this Aug 25, 2026
@barryroodt
barryroodt marked this pull request as ready for review August 26, 2026 10:35
@barryroodt
barryroodt requested a review from a team as a code owner August 26, 2026 10:35
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
barryroodt force-pushed the barryroodt/ai-1091-tool-policy-foundation branch from ee1f4e1 to 9ecf0bd Compare August 27, 2026 10:41
@barryroodt

Copy link
Copy Markdown
Contributor Author

Closing this as superseded by #391, which replaces the broader ToolPolicy foundation with the narrow SDK context/result seam needed for project cost confirmation.

@barryroodt barryroodt closed this Aug 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants