@crediolabs/policy-builder-mcp 0.2.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.
@@ -10,9 +10,9 @@
10
10
  // Stateless: a fresh McpServer is constructed per transport (stdio/HTTP). No
11
11
  // shared mutable state across calls; nothing here caches, queues, or holds
12
12
  // key material.
13
- import { runGetInterpreterInfo, runInstallPolicy, runMergePolicy, runRecordTransaction, runRevokePolicy, runSimulatePolicy, runSynthesizePolicy, runVerifyPolicy, } from '@crediolabs/policy-synth/run';
13
+ import { runGetInterpreterInfo, runInstallPolicy, runRecordTransaction, runRevokePolicy, runSimulatePolicy, runSynthesizePolicy, runVerifyPolicy, } from '@crediolabs/policy-synth/run';
14
14
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
15
- import { GetInterpreterInfoToolShape, InstallPolicyToolShape, MergePolicyToolShape, RecordTransactionToolShape, RevokePolicyToolShape, SimulatePolicyToolShape, SynthesizePolicyToolShape, VerifyPolicyToolShape, } from "./schemas.js";
15
+ import { GetInterpreterInfoToolShape, InstallPolicyToolShape, RecordTransactionToolShape, RevokePolicyToolShape, SimulatePolicyToolShape, SynthesizePolicyToolShape, VerifyPolicyToolShape, } from "./schemas.js";
16
16
  import { mcpResultFromCore } from "./tools/result.js";
17
17
  /** Our envelope types `structuredContent` precisely (T / ToolError); the SDK's
18
18
  * CallToolResult widens it to Record<string, unknown>, so the nominal types
@@ -29,11 +29,10 @@ export function createMcpServer() {
29
29
  /** Idempotent registration of the T1 tool set on the given server. */
30
30
  export function registerTools(server) {
31
31
  server.tool('record_transaction', 'Decode a Soroban transaction (on-chain hash OR base64 envelope XDR) into a RecordedTransaction. Returns a machine-readable ToolError on validation failure.', RecordTransactionToolShape, (args) => runRecordTransaction(args).then(toCallToolResult));
32
- server.tool('synthesize_policy', 'Synthesize a ProposedPolicy from either a deterministic MandateSpec (`source: mandate`) or a RecordedTransaction (`source: recording`). The discriminated `source` field selects the front-end.', SynthesizePolicyToolShape, (args) => runSynthesizePolicy(args).then(toCallToolResult));
33
- server.tool('simulate_policy', 'Replay a RecordedTransaction against a proposed PredicateNode (or null for an OZ-only policy) and emit the SimulationResult envelope (permit verdict + deny-case battery). Returns a SIMULATION_ERROR ToolError on runtime evaluation failure.', SimulatePolicyToolShape, (args) => runSimulatePolicy(args).then(toCallToolResult));
34
- server.tool('verify_policy', 'Run the static minimality check on a proposed PredicateNode against a RecordedTransaction (no conjunct is load-bearing-free). Returns VERIFICATION_FAILED with the dropped-constraint fingerprints when the predicate is over-broad.', VerifyPolicyToolShape, (args) => runVerifyPolicy(args).then(toCallToolResult));
32
+ server.tool('synthesize_policy', 'Synthesize a ProposedPolicy from a RecordedTransaction (`source: recording`).', SynthesizePolicyToolShape, (args) => runSynthesizePolicy(args).then(toCallToolResult));
33
+ server.tool('simulate_policy', 'Evaluate a predicate against one recorded call and report permit/deny with the deny reason. The evaluator is a second implementation of the on-chain semantics, cross-checked against the Rust interpreter by the conformance harness, so a verdict here is a claim about what the contract would do. Pass the `predicate` returned by `synthesize_policy` under `explain`.', SimulatePolicyToolShape, (args) => toCallToolResult(runSimulatePolicy(args)));
34
+ server.tool('verify_policy', 'Check a predicate against the transaction it was synthesised from, plus a generated deny case per dimension. Reports `ok` only when the permit case is permitted AND every deny case is denied - a denied permit case means the policy is too strict, a permitted deny case means it is too loose.', VerifyPolicyToolShape, (args) => toCallToolResult(runVerifyPolicy(args)));
35
35
  server.tool('install_policy', 'Build an UNSIGNED Soroban transaction XDR for `account.add_context_rule(...)` that installs a new policy rule on the given smart account. The wallet signs the returned XDR - the signature IS the user-confirmation step (this server is stateless and holds no key material, so there is no two-call confirm pair). Only CALL 1 is emitted; the interpreter `install` follow-up needs the rule id the account assigns in call 1 and is documented in `followUp` in the response.', InstallPolicyToolShape, (args) => runInstallPolicy(args).then(toCallToolResult));
36
36
  server.tool('revoke_policy', 'Build an UNSIGNED Soroban transaction XDR for `account.remove_context_rule(ruleId)` that removes a policy rule from the given smart account. The smart account handles uninstalling each attached policy itself. Auth is master-only - the source account MUST be the master signer set; delegated signers cannot uninstall.', RevokePolicyToolShape, (args) => runRevokePolicy(args).then(toCallToolResult));
37
- server.tool('merge_policy', "Tighten a rule by replacing its predicate with the conjunction of the installed one and a new one. This is the remedy for the overlap `install_policy` reports between two rules the interpreter polices: because OpenZeppelin enforces only the rule a signer names, adding a second, tighter rule restricts nothing, so the restriction has to become one predicate. TWO transactions, in order: call with step 'detach' to remove the current attachment, wait for it to confirm, then call with step 'reinstall'. Detaching uninstalls the policy, which RESETS every counter on the rule, and the rule is unpoliced in between - both are reported in `warnings`.", MergePolicyToolShape, (args) => runMergePolicy(args).then(toCallToolResult));
38
37
  server.tool('get_interpreter_info', 'Read-only fingerprint lookup for the policy interpreter contract: returns the pinned address, grammar version, and wasm sha256 (from the pinned constants + SELF_VERSION). When `verifyLive=true`, performs an additional `grammar_version()` RPC call against the pinned address and reports whether the deployed contract matches the pin - a live mismatch check is more useful than a fabricated audit field.', GetInterpreterInfoToolShape, (args) => runGetInterpreterInfo(args).then(toCallToolResult));
39
38
  }
@@ -2,13 +2,10 @@
2
2
  //
3
3
  // Streamable HTTP transport (hosted). Uses the Node http module directly so
4
4
  // the package stays thin - no express / hono dep. We run in STATELESS mode
5
- // (no `sessionIdGenerator` option), and the SDK 1.26+ requires a FRESH
6
- // transport per request in stateless mode: reusing one across requests lets
7
- // concurrent clients share internal message-id state, which is exactly the
8
- // cross-client data leak GHSA-345p-7cg4-v4c7 warns about. We therefore build
9
- // a transport inside the request handler, connect it, dispatch the request,
10
- // then close it (close() resets the McpServer's transport slot so the next
11
- // request can reconnect cleanly).
5
+ // (no sessionIdGenerator: the SDK disables session management when it is not
6
+ // provided) so each POST /mcp is its own transaction: this matches the
7
+ // brief's "stateless across calls" invariant. Stateless means a fresh server
8
+ // and transport per request - see the handler for why the SDK requires it.
12
9
  //
13
10
  // Single endpoint: POST /mcp (the SDK also accepts GET for SSE streaming, but
14
11
  // the T1 surface does not emit server-initiated messages so we omit it).
@@ -39,11 +36,6 @@ export async function startHttpServer(opts) {
39
36
  if (!LOOPBACK_HOSTS.has(host) && opts.allowExternalHost !== true) {
40
37
  throw new Error(`startHttpServer: refusing to bind host ${host}: the MCP surface is unauthenticated, so only loopback (127.0.0.1, ::1, localhost) is permitted by default. Pass \`allowExternalHost: true\` to opt in to a non-loopback bind.`);
41
38
  }
42
- // The McpServer is stateless and per-process; we keep ONE instance alive
43
- // for the lifetime of the listener, but each request creates + connects a
44
- // fresh StreamableHTTPServerTransport (SDK 1.26+ refuses to reuse a
45
- // stateless transport across requests).
46
- const server = createMcpServer();
47
39
  const httpServer = createServer(async (req, res) => {
48
40
  if (!req.url) {
49
41
  sendJson(res, 400, { error: 'missing url' });
@@ -89,21 +81,33 @@ export async function startHttpServer(opts) {
89
81
  });
90
82
  return;
91
83
  }
92
- // One transport per request. Omitting `sessionIdGenerator` selects
93
- // stateless mode in SDK 1.26+ (the previous `sessionIdGenerator:
94
- // undefined` form is rejected because the option type no longer
95
- // includes `undefined` under `exactOptionalPropertyTypes`).
96
- //
97
- // The cast `as unknown as Transport` is narrowly scoped to the SDK
98
- // boundary: the Node wrapper exposes `onclose` via getter/setter with
99
- // type `(() => void) | undefined`, while the `Transport` interface
100
- // declares `onclose?: () => void`. Under `exactOptionalPropertyTypes:
101
- // true` those are not structurally assignable. The runtime contract is
102
- // the same (the setter accepts `() => void`), so we cast once here.
84
+ // A stateless transport handles exactly ONE request: the SDK refuses to
85
+ // reuse one ("Stateless transport cannot be reused across requests"),
86
+ // because a shared instance would let concurrent clients collide on
87
+ // JSON-RPC message ids. So the server and its transport are built here,
88
+ // per request, and torn down when the response closes.
89
+ // No `sessionIdGenerator`: the SDK disables session management when the
90
+ // option is absent, which is the stateless mode this surface wants.
91
+ // Passing an explicit `undefined` means the same thing to the SDK but is
92
+ // not assignable under `exactOptionalPropertyTypes`, so omission is both
93
+ // the type-correct and the documented spelling.
94
+ const server = createMcpServer();
103
95
  const transport = new StreamableHTTPServerTransport();
104
- const sdkTransport = transport;
105
- await server.connect(sdkTransport);
96
+ // Registered before dispatch, not after: once the response has closed the
97
+ // event is gone, so a listener attached afterwards would never fire and
98
+ // the pair would leak.
99
+ res.on('close', () => {
100
+ void transport.close().catch(() => { });
101
+ void server.close().catch(() => { });
102
+ });
106
103
  try {
104
+ // The SDK declares `Transport.onclose` as an optional `() => void`, but
105
+ // exposes it on this class as an accessor pair typed `(() => void) |
106
+ // undefined`. Those are not assignable under `exactOptionalPropertyTypes`.
107
+ // The widening is upstream and structural only - the runtime object does
108
+ // satisfy `Transport` - so the assertion is narrowed to this one call
109
+ // rather than relaxing the compiler flag for the whole package.
110
+ await server.connect(transport);
107
111
  // `handleRequest` writes the response and returns once the message has
108
112
  // been dispatched. No shared state across calls in stateless mode.
109
113
  await transport.handleRequest(req, res, body);
@@ -124,14 +128,6 @@ export async function startHttpServer(opts) {
124
128
  sendJson(res, 500, { error });
125
129
  }
126
130
  }
127
- finally {
128
- // Closing the transport fires its `onclose`, which resets
129
- // `server._transport` to undefined so the next request can connect
130
- // a fresh transport. We swallow the close error: a request that
131
- // already wrote its response does not care whether the close path
132
- // threw.
133
- await transport.close().catch(() => { });
134
- }
135
131
  });
136
132
  await new Promise((resolve, reject) => {
137
133
  httpServer.once('error', reject);
@@ -144,9 +140,11 @@ export async function startHttpServer(opts) {
144
140
  port: opts.port,
145
141
  host,
146
142
  path,
143
+ // Nothing outlives a request, so closing the listener is the whole
144
+ // shutdown: each request's server and transport are already torn down by
145
+ // the `close` handler on its own response.
147
146
  close: async () => {
148
147
  await new Promise((resolve) => httpServer.close(() => resolve()));
149
- await server.close().catch(() => { });
150
148
  },
151
149
  };
152
150
  }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,7 @@
1
+ export { type RunRecordTransactionInput, type RunSynthesizePolicyInput, runRecordTransaction, runSynthesizePolicy, } from '@crediolabs/policy-synth/run';
2
+ export { RecordTransactionToolShape, SynthesizePolicyToolShape, } from './schemas.ts';
3
+ export { createMcpServer, registerTools } from './server.ts';
4
+ export type { McpToolError, McpToolResult } from './tools/result.ts';
5
+ export { mcpErrorFromCore, mcpResultFromCore } from './tools/result.ts';
6
+ export { startHttpServer } from './transports/http.ts';
7
+ export { startStdioServer } from './transports/stdio.ts';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ // packages/policy-builder-mcp/src/index.ts - public re-exports for the MCP server package.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.startStdioServer = exports.startHttpServer = exports.mcpResultFromCore = exports.mcpErrorFromCore = exports.registerTools = exports.createMcpServer = exports.SynthesizePolicyToolShape = exports.RecordTransactionToolShape = exports.runSynthesizePolicy = exports.runRecordTransaction = void 0;
5
+ var run_1 = require("@crediolabs/policy-synth/run");
6
+ Object.defineProperty(exports, "runRecordTransaction", { enumerable: true, get: function () { return run_1.runRecordTransaction; } });
7
+ Object.defineProperty(exports, "runSynthesizePolicy", { enumerable: true, get: function () { return run_1.runSynthesizePolicy; } });
8
+ var schemas_ts_1 = require("./schemas.js");
9
+ Object.defineProperty(exports, "RecordTransactionToolShape", { enumerable: true, get: function () { return schemas_ts_1.RecordTransactionToolShape; } });
10
+ Object.defineProperty(exports, "SynthesizePolicyToolShape", { enumerable: true, get: function () { return schemas_ts_1.SynthesizePolicyToolShape; } });
11
+ var server_ts_1 = require("./server.js");
12
+ Object.defineProperty(exports, "createMcpServer", { enumerable: true, get: function () { return server_ts_1.createMcpServer; } });
13
+ Object.defineProperty(exports, "registerTools", { enumerable: true, get: function () { return server_ts_1.registerTools; } });
14
+ var result_ts_1 = require("./tools/result.js");
15
+ Object.defineProperty(exports, "mcpErrorFromCore", { enumerable: true, get: function () { return result_ts_1.mcpErrorFromCore; } });
16
+ Object.defineProperty(exports, "mcpResultFromCore", { enumerable: true, get: function () { return result_ts_1.mcpResultFromCore; } });
17
+ var http_ts_1 = require("./transports/http.js");
18
+ Object.defineProperty(exports, "startHttpServer", { enumerable: true, get: function () { return http_ts_1.startHttpServer; } });
19
+ var stdio_ts_1 = require("./transports/stdio.js");
20
+ Object.defineProperty(exports, "startStdioServer", { enumerable: true, get: function () { return stdio_ts_1.startStdioServer; } });