@crediolabs/policy-builder-mcp 0.1.17 → 0.2.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.
@@ -1,130 +0,0 @@
1
- "use strict";
2
- // apps/policy-builder-mcp/src/schemas.ts
3
- //
4
- // MCP-only tool shapes. The CORE input/output schemas and the MCP server
5
- // registrations all live on `@crediolabs/policy-synth` (the tool-body glue
6
- // sits at `@crediolabs/policy-synth/run`; the underlying Zod input schemas
7
- // live at `@crediolabs/policy-synth/run`). What stays here is just the flat
8
- // `ZodRawShape` needed by `@modelcontextprotocol/sdk`'s `tool()` registration
9
- // API, which does not accept the strict discriminated union `synthesize_policy`
10
- // needs.
11
- //
12
- // The body of every tool call re-validates against the strict schemas via
13
- // `runRecordTransaction` / `runSynthesizePolicy`, so wire inputs still
14
- // fail closed. The mutual-exclusion rules (e.g. exactly-one-of hash/xdr)
15
- // live on the strict schemas, NOT on the tool shape; the SDK does not
16
- // invoke `.refine()` at registration time, so any refined rule must be
17
- // re-checked in the body.
18
- //
19
- // The tool-shape fields below are hand-rolled simple types rather than
20
- // references into the refined strict schemas (`.refine()` returns
21
- // `ZodEffects`, which has no `.shape`). They MUST stay in lockstep with
22
- // the strict schemas - a drift in field type or optionality breaks the
23
- // SDK's emitted JSON Schema.
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.GetInterpreterInfoToolShape = exports.RevokePolicyToolShape = exports.InstallPolicyToolShape = exports.VerifyPolicyToolShape = exports.SimulatePolicyToolShape = exports.SynthesizePolicyToolShape = exports.RecordTransactionToolShape = exports.VerifyPolicyInputSchema = exports.ToolErrorSchema = exports.SynthesizePolicyInputSchema = exports.SimulatePolicyInputSchema = exports.RevokePolicyInputSchema = exports.RecordTransactionInputSchema = exports.RecordedTransactionSchema = exports.PredicateNodeSchema = exports.OzAdapterConfigSchema = exports.OraclePriceFixtureSchema = exports.NetworkSchema = exports.MandateSpecSchema = exports.InterpreterOptionsSchema = exports.InstallPolicyInputSchema = exports.GetInterpreterInfoInputSchema = exports.ComposeUserResponsesSchema = void 0;
26
- const run_1 = require("@crediolabs/policy-synth/run");
27
- Object.defineProperty(exports, "ComposeUserResponsesSchema", { enumerable: true, get: function () { return run_1.ComposeUserResponsesSchema; } });
28
- Object.defineProperty(exports, "GetInterpreterInfoInputSchema", { enumerable: true, get: function () { return run_1.GetInterpreterInfoInputSchema; } });
29
- Object.defineProperty(exports, "InstallPolicyInputSchema", { enumerable: true, get: function () { return run_1.InstallPolicyInputSchema; } });
30
- Object.defineProperty(exports, "InterpreterOptionsSchema", { enumerable: true, get: function () { return run_1.InterpreterOptionsSchema; } });
31
- Object.defineProperty(exports, "MandateSpecSchema", { enumerable: true, get: function () { return run_1.MandateSpecSchema; } });
32
- Object.defineProperty(exports, "NetworkSchema", { enumerable: true, get: function () { return run_1.NetworkSchema; } });
33
- Object.defineProperty(exports, "OraclePriceFixtureSchema", { enumerable: true, get: function () { return run_1.OraclePriceFixtureSchema; } });
34
- Object.defineProperty(exports, "OzAdapterConfigSchema", { enumerable: true, get: function () { return run_1.OzAdapterConfigSchema; } });
35
- Object.defineProperty(exports, "PredicateNodeSchema", { enumerable: true, get: function () { return run_1.PredicateNodeSchema; } });
36
- Object.defineProperty(exports, "RecordedTransactionSchema", { enumerable: true, get: function () { return run_1.RecordedTransactionSchema; } });
37
- Object.defineProperty(exports, "RecordTransactionInputSchema", { enumerable: true, get: function () { return run_1.RecordTransactionInputSchema; } });
38
- Object.defineProperty(exports, "RevokePolicyInputSchema", { enumerable: true, get: function () { return run_1.RevokePolicyInputSchema; } });
39
- Object.defineProperty(exports, "SimulatePolicyInputSchema", { enumerable: true, get: function () { return run_1.SimulatePolicyInputSchema; } });
40
- Object.defineProperty(exports, "SynthesizePolicyInputSchema", { enumerable: true, get: function () { return run_1.SynthesizePolicyInputSchema; } });
41
- Object.defineProperty(exports, "ToolErrorSchema", { enumerable: true, get: function () { return run_1.ToolErrorSchema; } });
42
- Object.defineProperty(exports, "VerifyPolicyInputSchema", { enumerable: true, get: function () { return run_1.VerifyPolicyInputSchema; } });
43
- const zod_1 = require("zod");
44
- /** Flat ZodRawShape used for the MCP SDK tool registration. The body
45
- * re-validates against `RecordTransactionInputSchema` so the mutual-exclusion
46
- * rule still fires (the SDK does not invoke `.refine()` at registration time). */
47
- exports.RecordTransactionToolShape = {
48
- hash: zod_1.z.string().min(1).optional(),
49
- xdr: zod_1.z.string().min(1).optional(),
50
- network: run_1.NetworkSchema,
51
- confidenceOverride: zod_1.z.number().min(0).max(1).optional(),
52
- };
53
- /** Flat ZodRawShape used for MCP tool registration. Every field is optional
54
- * so the JSON-Schema the SDK exposes to clients does not forbid either
55
- * front-end; the body re-validates against the discriminated union. */
56
- exports.SynthesizePolicyToolShape = {
57
- source: zod_1.z.enum(['mandate', 'recording']).optional(),
58
- mandate: run_1.MandateSpecSchema.optional(),
59
- recordedTx: run_1.RecordedTransactionSchema.optional(),
60
- network: run_1.NetworkSchema.optional(),
61
- userResponses: run_1.ComposeUserResponsesSchema.optional(),
62
- confidenceOverride: zod_1.z.object({ threshold: zod_1.z.number().min(0).max(1) }).optional(),
63
- interpreter: run_1.InterpreterOptionsSchema.optional(),
64
- ozConfig: run_1.OzAdapterConfigSchema.optional(),
65
- // Without this the tool chain has no join. A ProposedPolicy carries
66
- // `policyDocuments[].encodedPredicate` (canonical ScVal bytes), while
67
- // `simulate_policy` and `verify_policy` both want the PredicateNode TREE,
68
- // and the tree is only returned under `explain`. Omitting it here left an
69
- // MCP client able to synthesize a policy and then unable to prove anything
70
- // about it - the two checks were reachable only with `predicate: null`,
71
- // which skips the interpreter predicate entirely.
72
- explain: zod_1.z.boolean().optional(),
73
- };
74
- /** Flat ZodRawShape for `simulate_policy`. The `predicate` is typed as
75
- * `z.unknown()` at the tool boundary because the recursive
76
- * `PredicateNodeSchema` is a `z.lazy()` union (the SDK does not accept
77
- * unions at the tool-registration boundary); the body re-validates
78
- * against `SimulatePolicyInputSchema`, which fails closed on a
79
- * malformed predicate. `predicate` is nullable here (vs required for
80
- * verify_policy) so the SDK-emitted JSON Schema mirrors the engine's
81
- * "OZ-only / no interpreter predicate" contract. */
82
- exports.SimulatePolicyToolShape = {
83
- predicate: zod_1.z.unknown().nullable().optional(),
84
- permitTx: run_1.RecordedTransactionSchema,
85
- validUntilLedger: zod_1.z.number().int().positive().optional(),
86
- oraclePricesByAsset: zod_1.z.record(zod_1.z.string(), run_1.OraclePriceFixtureSchema).optional(),
87
- };
88
- /** Flat ZodRawShape for `verify_policy`. Same `z.unknown()` boundary
89
- * trick for `predicate` as `SimulatePolicyToolShape`; `predicate` is
90
- * required at the strict-schema level (`VerifyPolicyInputSchema`) so
91
- * the body fails closed on a missing predicate. */
92
- exports.VerifyPolicyToolShape = {
93
- predicate: zod_1.z.unknown(),
94
- permitTx: run_1.RecordedTransactionSchema,
95
- validUntilLedger: zod_1.z.number().int().positive().optional(),
96
- oraclePricesByAsset: zod_1.z.record(zod_1.z.string(), run_1.OraclePriceFixtureSchema).optional(),
97
- };
98
- /** Flat ZodRawShape for `install_policy`. `rule` is typed as `z.unknown()`
99
- * at the tool boundary because the rule schema is a discriminated union
100
- * the SDK does not accept at registration; the body re-validates
101
- * against `InstallPolicyInputSchema`. `encodedPredicate` /
102
- * `predicateHash` live INSIDE `rule.policies[].predicateBlobBase64`
103
- * (the policy already carries the encoded predicate); the run-layer
104
- * extracts them from there. */
105
- exports.InstallPolicyToolShape = {
106
- smartAccount: zod_1.z.string().min(1).optional(),
107
- sourceAccount: zod_1.z.string().min(1).optional(),
108
- rule: zod_1.z.unknown().optional(),
109
- installNonce: zod_1.z.number().int().positive().optional(),
110
- interpreterAddress: zod_1.z.string().optional(),
111
- rpcUrl: zod_1.z.string().url().optional(),
112
- baseFee: zod_1.z.number().int().positive().optional(),
113
- };
114
- /** Flat ZodRawShape for `revoke_policy`. */
115
- exports.RevokePolicyToolShape = {
116
- smartAccount: zod_1.z.string().min(1).optional(),
117
- sourceAccount: zod_1.z.string().min(1).optional(),
118
- ruleId: zod_1.z.number().int().nonnegative().optional(),
119
- interpreterAddress: zod_1.z.string().optional(),
120
- rpcUrl: zod_1.z.string().url().optional(),
121
- baseFee: zod_1.z.number().int().positive().optional(),
122
- };
123
- /** Flat ZodRawShape for `get_interpreter_info`. `verifyLive` triggers an
124
- * optional RPC `grammar_version()` call so the caller can verify the
125
- * deployed contract matches the pin. */
126
- exports.GetInterpreterInfoToolShape = {
127
- network: zod_1.z.enum(['mainnet', 'testnet']).optional(),
128
- verifyLive: zod_1.z.boolean().optional(),
129
- rpcUrl: zod_1.z.string().url().optional(),
130
- };
@@ -1,6 +0,0 @@
1
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- /** Build a fresh, stateless MCP server. The caller owns the returned object
3
- * and connects it to a single transport (stdio or Streamable HTTP). */
4
- export declare function createMcpServer(): McpServer;
5
- /** Idempotent registration of the T1 tool set on the given server. */
6
- export declare function registerTools(server: McpServer): void;
@@ -1,62 +0,0 @@
1
- "use strict";
2
- // apps/policy-builder-mcp/src/server.ts
3
- //
4
- // Registers the T1 tool surface on a fresh McpServer instance. The
5
- // registration uses the official MCP SDK's `tool()` API with ZodRawShape
6
- // schemas (the SDK does not accept ZodEffects / discriminated unions at the
7
- // tool registration boundary - the known gotcha). The body re-validates
8
- // against the strict discriminated union in `@crediolabs/policy-synth/run`
9
- // so wire inputs still fail closed.
10
- //
11
- // Stateless: a fresh McpServer is constructed per transport (stdio/HTTP). No
12
- // shared mutable state across calls; nothing here caches, queues, or holds
13
- // key material.
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.createMcpServer = createMcpServer;
16
- exports.registerTools = registerTools;
17
- const run_1 = require("@crediolabs/policy-synth/run");
18
- const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
19
- const schemas_ts_1 = require("./schemas.js");
20
- const result_ts_1 = require("./tools/result.js");
21
- /** Build a fresh, stateless MCP server. The caller owns the returned object
22
- * and connects it to a single transport (stdio or Streamable HTTP). */
23
- function createMcpServer() {
24
- const server = new mcp_js_1.McpServer({ name: 'policy-builder-mcp', version: '0.0.0' }, { capabilities: { tools: {} } });
25
- registerTools(server);
26
- return server;
27
- }
28
- /** Idempotent registration of the T1 tool set on the given server. */
29
- function registerTools(server) {
30
- 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.', schemas_ts_1.RecordTransactionToolShape, async (args) => {
31
- const res = await (0, run_1.runRecordTransaction)(args);
32
- // Our envelope types `structuredContent` precisely (T / ToolError); the
33
- // SDK's CallToolResult widens it to Record<string, unknown>, so the
34
- // nominal types do not overlap. The runtime shapes match, so assert
35
- // through `unknown` at this transport boundary.
36
- return (0, result_ts_1.mcpResultFromCore)(res);
37
- });
38
- 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.', schemas_ts_1.SynthesizePolicyToolShape, async (args) => {
39
- const res = await (0, run_1.runSynthesizePolicy)(args);
40
- return (0, result_ts_1.mcpResultFromCore)(res);
41
- });
42
- 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.', schemas_ts_1.SimulatePolicyToolShape, async (args) => {
43
- const res = await (0, run_1.runSimulatePolicy)(args);
44
- return (0, result_ts_1.mcpResultFromCore)(res);
45
- });
46
- 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.', schemas_ts_1.VerifyPolicyToolShape, async (args) => {
47
- const res = await (0, run_1.runVerifyPolicy)(args);
48
- return (0, result_ts_1.mcpResultFromCore)(res);
49
- });
50
- 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.', schemas_ts_1.InstallPolicyToolShape, async (args) => {
51
- const res = await (0, run_1.runInstallPolicy)(args);
52
- return (0, result_ts_1.mcpResultFromCore)(res);
53
- });
54
- 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.', schemas_ts_1.RevokePolicyToolShape, async (args) => {
55
- const res = await (0, run_1.runRevokePolicy)(args);
56
- return (0, result_ts_1.mcpResultFromCore)(res);
57
- });
58
- server.tool('get_interpreter_info', 'Read-only fingerprint lookup for the policy interpreter contract: returns the pinned address, grammar version, and wasm sha256 (from DEPLOYMENTS.md + 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.', schemas_ts_1.GetInterpreterInfoToolShape, async (args) => {
59
- const res = await (0, run_1.runGetInterpreterInfo)(args);
60
- return (0, result_ts_1.mcpResultFromCore)(res);
61
- });
62
- }
@@ -1,24 +0,0 @@
1
- import type { ToolError, ToolResponse } from '@crediolabs/policy-synth';
2
- export interface McpToolSuccess<T> {
3
- isError: false;
4
- content: Array<{
5
- type: 'text';
6
- text: string;
7
- }>;
8
- structuredContent: T;
9
- }
10
- export interface McpToolError {
11
- isError: true;
12
- content: Array<{
13
- type: 'text';
14
- text: string;
15
- }>;
16
- structuredContent: ToolError;
17
- }
18
- export type McpToolResult<T> = McpToolSuccess<T> | McpToolError;
19
- /** Map a core ToolResponse<T> to the MCP result envelope. The handler in
20
- * src/server.ts wraps this in the SDK's `{ content, isError }` shape. */
21
- export declare function mcpResultFromCore<T>(res: ToolResponse<T>): McpToolResult<T>;
22
- /** Map a core ToolError directly (for inputs that already failed validation
23
- * inside the handler). */
24
- export declare function mcpErrorFromCore(err: ToolError): McpToolError;
@@ -1,39 +0,0 @@
1
- "use strict";
2
- // apps/policy-builder-mcp/src/tools/result.ts
3
- //
4
- // Transport-layer mapping between the core's ToolResponse<T> envelope and the
5
- // MCP result envelope. This is the ONLY place the two envelopes meet; no
6
- // business logic lives here. The shapes follow the MCP spec for the
7
- // `CallToolResult` type:
8
- //
9
- // success: { content: [{ type: 'text', text: JSON.stringify(data) }], isError: false }
10
- // failure: { content: [{ type: 'text', text: JSON.stringify(error) }], isError: true }
11
- //
12
- // Both branches carry the structured content as a single JSON-encoded text
13
- // block so clients that do not parse `structuredContent` still see a usable
14
- // payload. The shape is intentionally tiny - any extra keys belong in the
15
- // core, not here.
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.mcpResultFromCore = mcpResultFromCore;
18
- exports.mcpErrorFromCore = mcpErrorFromCore;
19
- /** Map a core ToolResponse<T> to the MCP result envelope. The handler in
20
- * src/server.ts wraps this in the SDK's `{ content, isError }` shape. */
21
- function mcpResultFromCore(res) {
22
- if (res.ok) {
23
- return {
24
- isError: false,
25
- content: [{ type: 'text', text: JSON.stringify(res.data) }],
26
- structuredContent: res.data,
27
- };
28
- }
29
- return mcpErrorFromCore(res.error);
30
- }
31
- /** Map a core ToolError directly (for inputs that already failed validation
32
- * inside the handler). */
33
- function mcpErrorFromCore(err) {
34
- return {
35
- isError: true,
36
- content: [{ type: 'text', text: JSON.stringify(err) }],
37
- structuredContent: err,
38
- };
39
- }
@@ -1,15 +0,0 @@
1
- export interface StartHttpServerOptions {
2
- port: number;
3
- host?: string;
4
- /** Path the server mounts the MCP endpoint at. Default `/mcp`. */
5
- path?: string;
6
- }
7
- export interface RunningHttpServer {
8
- port: number;
9
- host: string;
10
- path: string;
11
- close: () => Promise<void>;
12
- }
13
- /** Stateless Streamable HTTP server. Resolves once the server is listening.
14
- * The returned handle exposes `close()` for tests + clean shutdown. */
15
- export declare function startHttpServer(opts: StartHttpServerOptions): Promise<RunningHttpServer>;
@@ -1,140 +0,0 @@
1
- "use strict";
2
- // apps/policy-builder-mcp/src/transports/http.ts
3
- //
4
- // Streamable HTTP transport (hosted). Uses the Node http module directly so
5
- // the package stays thin - no express / hono dep. We run in STATELESS mode
6
- // (sessionIdGenerator: undefined) so each POST /mcp is its own transaction:
7
- // this matches the brief's "stateless across calls" invariant.
8
- //
9
- // Single endpoint: POST /mcp (the SDK also accepts GET for SSE streaming, but
10
- // the T1 surface does not emit server-initiated messages so we omit it).
11
- // Listens on 127.0.0.1 by default; pass `host: '0.0.0.0'` to expose.
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.startHttpServer = startHttpServer;
14
- const node_http_1 = require("node:http");
15
- const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
16
- const server_ts_1 = require("../server.js");
17
- /** Stateless Streamable HTTP server. Resolves once the server is listening.
18
- * The returned handle exposes `close()` for tests + clean shutdown. */
19
- async function startHttpServer(opts) {
20
- const host = opts.host ?? '127.0.0.1';
21
- const path = opts.path ?? '/mcp';
22
- const server = (0, server_ts_1.createMcpServer)();
23
- // One transport per server (the SDK reuses the transport for every request
24
- // in stateless mode). We connect it once at startup and reuse it.
25
- const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
26
- sessionIdGenerator: undefined,
27
- });
28
- await server.connect(transport);
29
- const httpServer = (0, node_http_1.createServer)(async (req, res) => {
30
- if (!req.url) {
31
- sendJson(res, 400, { error: 'missing url' });
32
- return;
33
- }
34
- const url = new URL(req.url, `http://${host}`);
35
- if (url.pathname !== path) {
36
- sendJson(res, 404, { error: 'not found', path: url.pathname });
37
- return;
38
- }
39
- if (req.method !== 'POST') {
40
- // The SDK ignores non-POST in stateless mode (no GET/SSE needed in T1).
41
- sendJson(res, 405, { error: 'method not allowed', method: req.method ?? null });
42
- return;
43
- }
44
- // Reject an over-cap body fast via Content-Length; the streaming reader is
45
- // the backstop for chunked/unknown-length requests.
46
- const declaredLength = Number(req.headers['content-length']);
47
- if (Number.isFinite(declaredLength) && declaredLength > MAX_BODY_BYTES) {
48
- sendJson(res, 413, { error: 'request body too large' });
49
- return;
50
- }
51
- // Read the JSON-RPC body. The SDK accepts a pre-parsed body, so we parse
52
- // it here rather than the SDK trying to re-stream the raw req.
53
- let body;
54
- try {
55
- body = await readJsonBody(req);
56
- }
57
- catch (e) {
58
- if (e instanceof BodyTooLargeError) {
59
- sendJson(res, 413, { error: 'request body too large' });
60
- }
61
- else {
62
- sendJson(res, 400, { error: 'invalid JSON body' });
63
- }
64
- return;
65
- }
66
- // The T1 surface is one request per call. A JSON-RPC batch (array) is
67
- // rejected explicitly rather than silently dropping the extra calls.
68
- if (Array.isArray(body)) {
69
- sendJson(res, 400, {
70
- error: 'JSON-RPC batch requests are not supported; send one request per call',
71
- });
72
- return;
73
- }
74
- try {
75
- // `handleRequest` writes the response and returns once the message has
76
- // been dispatched. No shared state across calls in stateless mode.
77
- await transport.handleRequest(req, res, body);
78
- }
79
- catch {
80
- // The SDK normally writes structured errors itself; this is a belt +
81
- // braces guard so a thrown error does not leave the socket hanging.
82
- if (!res.headersSent) {
83
- const error = {
84
- code: 'SYNTHESIS_ERROR',
85
- message: 'internal server error',
86
- severity: 'error',
87
- retryable: false,
88
- };
89
- sendJson(res, 500, { error });
90
- }
91
- else
92
- res.end();
93
- }
94
- });
95
- await new Promise((resolve, reject) => {
96
- httpServer.once('error', reject);
97
- httpServer.listen(opts.port, host, () => {
98
- httpServer.off('error', reject);
99
- resolve();
100
- });
101
- });
102
- return {
103
- port: opts.port,
104
- host,
105
- path,
106
- close: async () => {
107
- await new Promise((resolve) => httpServer.close(() => resolve()));
108
- await transport.close().catch(() => { });
109
- await server.close().catch(() => { });
110
- },
111
- };
112
- }
113
- function sendJson(res, status, body) {
114
- res.statusCode = status;
115
- res.setHeader('content-type', 'application/json');
116
- res.end(JSON.stringify(body));
117
- }
118
- /** Reject bodies larger than this before buffering the whole payload - a
119
- * recorded transaction is far smaller, so this only stops abusive requests. */
120
- const MAX_BODY_BYTES = 1_048_576;
121
- /** Distinguishes an over-cap body from a malformed one so the handler can send
122
- * a 413 rather than a misleading 400. */
123
- class BodyTooLargeError extends Error {
124
- }
125
- async function readJsonBody(req) {
126
- const chunks = [];
127
- let total = 0;
128
- for await (const chunk of req) {
129
- total += chunk.length;
130
- if (total > MAX_BODY_BYTES)
131
- throw new BodyTooLargeError('request body too large');
132
- chunks.push(chunk);
133
- }
134
- if (chunks.length === 0)
135
- return {};
136
- const raw = Buffer.concat(chunks).toString('utf8');
137
- if (!raw)
138
- return {};
139
- return JSON.parse(raw);
140
- }
@@ -1 +0,0 @@
1
- export declare function startStdioServer(): Promise<void>;
@@ -1,18 +0,0 @@
1
- "use strict";
2
- // apps/policy-builder-mcp/src/transports/stdio.ts
3
- //
4
- // stdio transport (Claude Desktop / local agents). The MCP SDK reads JSON-RPC
5
- // from stdin and writes to stdout. Each process serves ONE client and exits
6
- // when the client closes the stream. No key custody, no global state; the
7
- // per-call state lives entirely in the McpServer instance.
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.startStdioServer = startStdioServer;
10
- const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
11
- const server_ts_1 = require("../server.js");
12
- async function startStdioServer() {
13
- const server = (0, server_ts_1.createMcpServer)();
14
- const transport = new stdio_js_1.StdioServerTransport();
15
- await server.connect(transport);
16
- // The transport owns the process from here; no shutdown signal handling -
17
- // SIGPIPE / EOF on stdin terminates the loop naturally.
18
- }