@crediolabs/policy-builder-mcp 0.1.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.
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ // apps/policy-builder-mcp/src/index.ts - public re-exports for the MCP server package.
2
+
3
+ export {
4
+ RecordTransactionInputSchema,
5
+ RecordTransactionToolShape,
6
+ SynthesizePolicyInputSchema,
7
+ SynthesizePolicyMandateInputSchema,
8
+ SynthesizePolicyRecordingInputSchema,
9
+ SynthesizePolicyToolShape,
10
+ } from './schemas.ts'
11
+ export { createMcpServer, registerTools } from './server.ts'
12
+ export type { McpToolError, McpToolResult } from './tools/result.ts'
13
+ export { mcpErrorFromCore, mcpResultFromCore } from './tools/result.ts'
14
+ export {
15
+ type RunRecordTransactionInput,
16
+ type RunSynthesizePolicyInput,
17
+ runRecordTransaction,
18
+ runSynthesizePolicy,
19
+ } from './tools/run.ts'
20
+ export { startHttpServer } from './transports/http.ts'
21
+ export { startStdioServer } from './transports/stdio.ts'
package/src/schemas.ts ADDED
@@ -0,0 +1,249 @@
1
+ // apps/policy-builder-mcp/src/schemas.ts
2
+ //
3
+ // Zod schemas mirroring the policy-synth core domain types. These are the
4
+ // public input / output shapes exposed over MCP and the CLI. They are kept
5
+ // hand-written (rather than derived) because the MCP SDK needs a runtime
6
+ // Zod object at the transport boundary; a drift test asserts they stay in
7
+ // step with the TS source of truth.
8
+ //
9
+ // i128 amounts and other large integers are carried as base-10 decimal strings
10
+ // end-to-end (no JS number coercion). Networks are pinned to the same closed
11
+ // set the core defines. The discriminated union on `source` exposes BOTH
12
+ // synthesize_policy front-ends through a single tool input.
13
+
14
+ import { z } from 'zod'
15
+
16
+ /** Soroban `valid_until` is a u32 ledger sequence; a value above this cannot be
17
+ * installed on-chain, so reject it at the boundary (fail-closed). */
18
+ const U32_MAX = 4294967295
19
+ /** Upper bound on top-level invocations in a recorded transaction. A real
20
+ * Stellar tx caps operations well below this; the bound stops a hand-crafted
21
+ * payload from turning one request into an unbounded synthesis (DoS). */
22
+ const MAX_INVOCATIONS = 512
23
+
24
+ export const NetworkSchema = z.enum(['mainnet', 'testnet'])
25
+ export type Network = z.infer<typeof NetworkSchema>
26
+
27
+ /** ScVal subset - normalised subset the synth consumes. Mirrors
28
+ * `ScVal` in packages/policy-synth/src/types.ts. */
29
+ export const ScValSchema: z.ZodType<unknown> = z.lazy(() =>
30
+ z.union([
31
+ z.object({ type: z.literal('address'), value: z.string() }),
32
+ // i128 is SIGNED: real events carry negatives (e.g. a fee-adjustment/refund),
33
+ // so the recorder's own output must round-trip through this schema. u64/u32
34
+ // are unsigned and stay non-negative.
35
+ z.object({ type: z.literal('i128'), value: z.string().regex(/^-?[0-9]+$/) }),
36
+ z.object({ type: z.literal('u64'), value: z.string().regex(/^[0-9]+$/) }),
37
+ z.object({ type: z.literal('u32'), value: z.string().regex(/^[0-9]+$/) }),
38
+ z.object({ type: z.literal('symbol'), value: z.string() }),
39
+ z.object({ type: z.literal('vec'), value: z.array(ScValSchema) }),
40
+ z.object({ type: z.literal('bytes'), value: z.string() }),
41
+ z.object({ type: z.literal('other'), value: z.string() }),
42
+ ])
43
+ )
44
+
45
+ /** ContractInvocation mirrors the core. Annotated with an explicit
46
+ * `z.ZodType<unknown>` (like ScValSchema above) so the self-referential
47
+ * `subInvocations` field does not trip TS's circular type inference. */
48
+ export const ContractInvocationSchema: z.ZodType<unknown> = z.object({
49
+ contract: z.string(),
50
+ fn: z.string(),
51
+ args: z.array(ScValSchema),
52
+ subInvocations: z.array(z.lazy(() => ContractInvocationSchema)),
53
+ })
54
+
55
+ export const TokenMovementSchema = z.object({
56
+ token: z.string(),
57
+ from: z.string(),
58
+ to: z.string(),
59
+ // The recorder reads the amount straight from the signed i128 event value
60
+ // (record/movements.ts readAmount), so a non-standard token that emits a
61
+ // negative transfer/mint/burn amount round-trips as a negative string. Mirror
62
+ // that here; the synth gate, not the wire schema, decides what to do with it.
63
+ amount: z.string().regex(/^-?[0-9]+$/),
64
+ })
65
+
66
+ export const OnChainEventSchema = z.object({
67
+ contract: z.string(),
68
+ topics: z.array(z.string()),
69
+ data: ScValSchema,
70
+ })
71
+
72
+ export const ParseConfidenceSchema = z.object({
73
+ overall: z.number().min(0).max(1),
74
+ knownContracts: z.array(z.string()),
75
+ unknownContracts: z.array(
76
+ z.object({
77
+ contract: z.string(),
78
+ reason: z.enum(['no-abi', 'version-mismatch', 'opaque-result']),
79
+ })
80
+ ),
81
+ opaqueScVals: z.array(z.object({ path: z.string(), type: z.string() })),
82
+ thresholdUsed: z.number().min(0).max(1),
83
+ })
84
+
85
+ /** RecordedTransaction mirrors the core RecordedTransaction. The output shape
86
+ * is referenced by name in the tool result structured content; we deliberately
87
+ * type it loosely (`z.unknown()`) on the success path so the core remains the
88
+ * single source of truth for the wire payload. */
89
+ export const RecordedTransactionSchema = z
90
+ .object({
91
+ network: NetworkSchema,
92
+ signers: z.array(z.string()),
93
+ invocations: z.array(ContractInvocationSchema).max(MAX_INVOCATIONS),
94
+ tokenMovements: z.array(TokenMovementSchema),
95
+ events: z.array(OnChainEventSchema),
96
+ authEntries: z.array(z.unknown()),
97
+ ledgerSequence: z.number().int().nonnegative(),
98
+ fetchedAt: z.number().int().nonnegative(),
99
+ parseConfidence: ParseConfidenceSchema,
100
+ sourceAccount: z.string(),
101
+ })
102
+ .passthrough()
103
+
104
+ /** MandateSpec mirrors the core MandateSpec. The deterministic Mandate
105
+ * front-end needs no parseConfidence; the tool adapter injects the full
106
+ * confidence after synthesis so the orchestrator can compare. */
107
+ export const MandateSpecSchema = z
108
+ .object({
109
+ chain: z.literal('stellar'),
110
+ contract: z.string(),
111
+ method: z.string().optional(),
112
+ spendingLimit: z
113
+ .object({
114
+ token: z.string(),
115
+ limit: z.string().regex(/^[0-9]+$/),
116
+ windowSeconds: z.number().int().positive(),
117
+ })
118
+ .optional(),
119
+ // A threshold of 0 means "0 approvals", which is not a real M-of-N gate.
120
+ approvalThreshold: z.number().int().positive().optional(),
121
+ recipients: z.array(z.string()).optional(),
122
+ expiry: z
123
+ .object({
124
+ validUntilLedger: z.number().int().positive().max(U32_MAX).optional(),
125
+ validUntilUnixSeconds: z.number().int().positive().optional(),
126
+ })
127
+ .optional(),
128
+ })
129
+ .passthrough()
130
+
131
+ /** ComposeUserResponses mirrors the core. */
132
+ export const ComposeUserResponsesSchema = z
133
+ .object({
134
+ windowSeconds: z.number().int().positive().optional(),
135
+ validUntilLedger: z.number().int().positive().max(U32_MAX).optional(),
136
+ limitAmount: z
137
+ .string()
138
+ .regex(/^[0-9]+$/)
139
+ .optional(),
140
+ invocationLimit: z.number().int().positive().optional(),
141
+ })
142
+ .passthrough()
143
+
144
+ /** OzAdapterConfig - the per-network OZ built-in instance addresses. */
145
+ export const OzAdapterConfigSchema = z.object({
146
+ network: NetworkSchema,
147
+ instances: z.object({
148
+ spending_limit: z.string(),
149
+ simple_threshold: z.string(),
150
+ weighted_threshold: z.string(),
151
+ }),
152
+ })
153
+
154
+ // ===== record_transaction =====
155
+
156
+ export const RecordTransactionInputSchema = z
157
+ .object({
158
+ hash: z.string().min(1).optional(),
159
+ xdr: z.string().min(1).optional(),
160
+ network: NetworkSchema,
161
+ confidenceOverride: z.number().min(0).max(1).optional(),
162
+ })
163
+ .refine((v) => !(v.hash && v.xdr), {
164
+ message: 'provide exactly one of `hash` or `xdr`, not both',
165
+ })
166
+ .refine((v) => Boolean(v.hash) || Boolean(v.xdr), {
167
+ message: 'one of `hash` or `xdr` is required',
168
+ })
169
+ export type RecordTransactionInput = z.infer<typeof RecordTransactionInputSchema>
170
+
171
+ /** Flat ZodRawShape used for the MCP SDK tool registration. The body
172
+ * re-validates against `RecordTransactionInputSchema` so the mutual-exclusion
173
+ * rule still fires (the SDK does not invoke `.refine()` at registration time). */
174
+ export const RecordTransactionToolShape = {
175
+ hash: z.string().min(1).optional(),
176
+ xdr: z.string().min(1).optional(),
177
+ network: NetworkSchema,
178
+ confidenceOverride: z.number().min(0).max(1).optional(),
179
+ } as const
180
+
181
+ // ===== synthesize_policy =====
182
+ //
183
+ // Discriminated union on `source` exposes BOTH front-ends through ONE tool.
184
+ // - `source: 'mandate'` -> calls synthesizeFromMandate
185
+ // - `source: 'recording'` -> calls synthesizeFromRecording
186
+ //
187
+ // The MCP SDK's `tool()` API only accepts a flat ZodRawShape (named
188
+ // properties keyed by Zod schemas), so we ALSO export a flat shape used at
189
+ // the transport boundary. The discriminated union is the strict body-side
190
+ // validator; the tool handler runs BOTH and treats the flat shape as the
191
+ // friendly wire contract.
192
+
193
+ export const SynthesizePolicyMandateInputSchema = z.object({
194
+ source: z.literal('mandate'),
195
+ mandate: MandateSpecSchema,
196
+ ozConfig: OzAdapterConfigSchema.optional(),
197
+ })
198
+
199
+ export const SynthesizePolicyRecordingInputSchema = z.object({
200
+ source: z.literal('recording'),
201
+ recordedTx: RecordedTransactionSchema,
202
+ network: NetworkSchema,
203
+ userResponses: ComposeUserResponsesSchema.optional(),
204
+ confidenceOverride: z.object({ threshold: z.number().min(0).max(1) }).optional(),
205
+ ozConfig: OzAdapterConfigSchema.optional(),
206
+ })
207
+
208
+ export const SynthesizePolicyInputSchema = z.discriminatedUnion('source', [
209
+ SynthesizePolicyMandateInputSchema,
210
+ SynthesizePolicyRecordingInputSchema,
211
+ ])
212
+ export type SynthesizePolicyInput = z.infer<typeof SynthesizePolicyInputSchema>
213
+
214
+ /** Flat ZodRawShape used for MCP tool registration. Every field is optional
215
+ * so the JSON-Schema the SDK exposes to clients does not forbid either
216
+ * front-end; the body re-validates against the discriminated union. */
217
+ export const SynthesizePolicyToolShape = {
218
+ source: z.enum(['mandate', 'recording']).optional(),
219
+ mandate: MandateSpecSchema.optional(),
220
+ recordedTx: RecordedTransactionSchema.optional(),
221
+ network: NetworkSchema.optional(),
222
+ userResponses: ComposeUserResponsesSchema.optional(),
223
+ confidenceOverride: z.object({ threshold: z.number().min(0).max(1) }).optional(),
224
+ ozConfig: OzAdapterConfigSchema.optional(),
225
+ } as const
226
+
227
+ // ===== Error envelope (canonical) =====
228
+ //
229
+ // Mirrors ToolError from packages/policy-synth/src/errors.ts. We use a
230
+ // `z.string()` for `code` (not an enum) because the core's ErrorCode union
231
+ // evolves over time; the transport contract only promises a string code the
232
+ // caller can dispatch on. A drift test asserts the canonical codes still
233
+ // pass through unchanged.
234
+ export const ToolErrorSchema = z
235
+ .object({
236
+ code: z.string(),
237
+ message: z.string(),
238
+ severity: z.enum(['info', 'warning', 'error', 'fatal']),
239
+ retryable: z.boolean(),
240
+ remediation: z
241
+ .object({
242
+ toolCall: z.object({ name: z.string(), args: z.record(z.unknown()) }).optional(),
243
+ userQuestion: z.object({ code: z.string(), question: z.string() }).optional(),
244
+ docsUrl: z.string().optional(),
245
+ })
246
+ .optional(),
247
+ details: z.unknown().optional(),
248
+ })
249
+ .passthrough()
package/src/server.ts ADDED
@@ -0,0 +1,56 @@
1
+ // apps/policy-builder-mcp/src/server.ts
2
+ //
3
+ // Registers the T1 tool surface on a fresh McpServer instance. The
4
+ // registration uses the official MCP SDK's `tool()` API with ZodRawShape
5
+ // schemas (the SDK does not accept ZodEffects / discriminated unions at the
6
+ // tool registration boundary - the known gotcha). The body re-validates
7
+ // against the strict discriminated union in src/tools/run.ts so wire inputs
8
+ // still fail closed.
9
+ //
10
+ // Stateless: a fresh McpServer is constructed per transport (stdio/HTTP). No
11
+ // shared mutable state across calls; nothing here caches, queues, or holds
12
+ // key material.
13
+
14
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
15
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
16
+ import { RecordTransactionToolShape, SynthesizePolicyToolShape } from './schemas.ts'
17
+ import { mcpResultFromCore } from './tools/result.ts'
18
+ import { runRecordTransaction, runSynthesizePolicy } from './tools/run.ts'
19
+
20
+ /** Build a fresh, stateless MCP server. The caller owns the returned object
21
+ * and connects it to a single transport (stdio or Streamable HTTP). */
22
+ export function createMcpServer(): McpServer {
23
+ const server = new McpServer(
24
+ { name: 'policy-builder-mcp', version: '0.0.0' },
25
+ { capabilities: { tools: {} } }
26
+ )
27
+ registerTools(server)
28
+ return server
29
+ }
30
+
31
+ /** Idempotent registration of the T1 tool set on the given server. */
32
+ export function registerTools(server: McpServer): void {
33
+ server.tool(
34
+ 'record_transaction',
35
+ 'Decode a Soroban transaction (on-chain hash OR base64 envelope XDR) into a RecordedTransaction. Returns a machine-readable ToolError on validation failure.',
36
+ RecordTransactionToolShape,
37
+ async (args) => {
38
+ const res = await runRecordTransaction(args)
39
+ // Our envelope types `structuredContent` precisely (T / ToolError); the
40
+ // SDK's CallToolResult widens it to Record<string, unknown>, so the
41
+ // nominal types do not overlap. The runtime shapes match, so assert
42
+ // through `unknown` at this transport boundary.
43
+ return mcpResultFromCore(res) as unknown as CallToolResult
44
+ }
45
+ )
46
+
47
+ server.tool(
48
+ 'synthesize_policy',
49
+ 'Synthesize a ProposedPolicy from either a deterministic MandateSpec (`source: mandate`) or a RecordedTransaction (`source: recording`). The discriminated `source` field selects the front-end.',
50
+ SynthesizePolicyToolShape,
51
+ async (args) => {
52
+ const res = await runSynthesizePolicy(args)
53
+ return mcpResultFromCore(res) as unknown as CallToolResult
54
+ }
55
+ )
56
+ }
@@ -0,0 +1,53 @@
1
+ // apps/policy-builder-mcp/src/tools/result.ts
2
+ //
3
+ // Transport-layer mapping between the core's ToolResponse<T> envelope and the
4
+ // MCP result envelope. This is the ONLY place the two envelopes meet; no
5
+ // business logic lives here. The shapes follow the MCP spec for the
6
+ // `CallToolResult` type:
7
+ //
8
+ // success: { content: [{ type: 'text', text: JSON.stringify(data) }], isError: false }
9
+ // failure: { content: [{ type: 'text', text: JSON.stringify(error) }], isError: true }
10
+ //
11
+ // Both branches carry the structured content as a single JSON-encoded text
12
+ // block so clients that do not parse `structuredContent` still see a usable
13
+ // payload. The shape is intentionally tiny - any extra keys belong in the
14
+ // core, not here.
15
+
16
+ import type { ToolError, ToolResponse } from '@crediolabs/policy-synth'
17
+
18
+ export interface McpToolSuccess<T> {
19
+ isError: false
20
+ content: Array<{ type: 'text'; text: string }>
21
+ structuredContent: T
22
+ }
23
+
24
+ export interface McpToolError {
25
+ isError: true
26
+ content: Array<{ type: 'text'; text: string }>
27
+ structuredContent: ToolError
28
+ }
29
+
30
+ export type McpToolResult<T> = McpToolSuccess<T> | McpToolError
31
+
32
+ /** Map a core ToolResponse<T> to the MCP result envelope. The handler in
33
+ * src/server.ts wraps this in the SDK's `{ content, isError }` shape. */
34
+ export function mcpResultFromCore<T>(res: ToolResponse<T>): McpToolResult<T> {
35
+ if (res.ok) {
36
+ return {
37
+ isError: false,
38
+ content: [{ type: 'text', text: JSON.stringify(res.data) }],
39
+ structuredContent: res.data,
40
+ }
41
+ }
42
+ return mcpErrorFromCore(res.error)
43
+ }
44
+
45
+ /** Map a core ToolError directly (for inputs that already failed validation
46
+ * inside the handler). */
47
+ export function mcpErrorFromCore(err: ToolError): McpToolError {
48
+ return {
49
+ isError: true,
50
+ content: [{ type: 'text', text: JSON.stringify(err) }],
51
+ structuredContent: err,
52
+ }
53
+ }
@@ -0,0 +1,133 @@
1
+ // apps/policy-builder-mcp/src/tools/run.ts
2
+ //
3
+ // Tool bodies for `record_transaction` and `synthesize_policy`. Each body is a
4
+ // THIN adapter over the pure core:
5
+ //
6
+ // 1. Re-validate the parsed input via Zod. This is a defence-in-depth check -
7
+ // the SDK has already parsed it through the registered schema, but we never
8
+ // want a tool body to throw on garbage (the SDK treats uncaught throws as
9
+ // transport errors and the agent loses the machine-readable ToolError).
10
+ // 2. Dispatch to the matching core entry point with the minimum required
11
+ // inputs.
12
+ // 3. Return the core's ToolResponse<T> unchanged. The server layer maps it
13
+ // to the MCP envelope; nothing here knows about MCP.
14
+ //
15
+ // No business logic. No retries. No session state. The same call shape can
16
+ // drive the CLI (which calls into the same core directly without MCP).
17
+
18
+ import {
19
+ type ErrorCode,
20
+ type MandateSpec,
21
+ type OzAdapterConfig,
22
+ type ProposedPolicy,
23
+ placeholderOzConfig,
24
+ type RecordedTransaction,
25
+ recordTransaction,
26
+ type SynthesizeFromRecordingOptions,
27
+ synthesizeFromMandate,
28
+ synthesizeFromRecording,
29
+ type ToolError,
30
+ type ToolResponse,
31
+ } from '@crediolabs/policy-synth'
32
+ import {
33
+ type RecordTransactionInput,
34
+ RecordTransactionInputSchema,
35
+ type SynthesizePolicyInput,
36
+ SynthesizePolicyInputSchema,
37
+ } from '../schemas.ts'
38
+
39
+ export type RunRecordTransactionInput = RecordTransactionInput
40
+
41
+ export type RunSynthesizePolicyInput = SynthesizePolicyInput
42
+
43
+ /** `record_transaction` body - wraps `recordTransaction`. The tool input
44
+ * matches the core RecordInput minus the injected `fetcher` (the transport
45
+ * layer does not own the RPC). Returns the core ToolResponse unchanged. */
46
+ export async function runRecordTransaction(
47
+ raw: unknown
48
+ ): Promise<ToolResponse<RecordedTransaction>> {
49
+ const parsed = RecordTransactionInputSchema.safeParse(raw)
50
+ if (!parsed.success) {
51
+ return {
52
+ ok: false,
53
+ error: validationError('record_transaction', parsed.error.issues),
54
+ }
55
+ }
56
+ const input: RecordTransactionInput = parsed.data
57
+ // Strip the wire-only `confidenceOverride` and pass the rest straight through.
58
+ const coreInput = {
59
+ network: input.network,
60
+ ...(input.hash !== undefined ? { hash: input.hash } : {}),
61
+ ...(input.xdr !== undefined ? { xdr: input.xdr } : {}),
62
+ ...(input.confidenceOverride !== undefined
63
+ ? { confidenceOverride: input.confidenceOverride }
64
+ : {}),
65
+ }
66
+ return recordTransaction(coreInput)
67
+ }
68
+
69
+ /** `synthesize_policy` body - discriminated union on `source`:
70
+ * - `mandate` -> synthesizeFromMandate
71
+ * - `recording` -> synthesizeFromRecording
72
+ * Exposing BOTH front-ends through ONE tool keeps the MCP surface tiny while
73
+ * letting the agent pick the deterministic or the inferred path. The CLI
74
+ * routes the same way. */
75
+ export async function runSynthesizePolicy(raw: unknown): Promise<ToolResponse<ProposedPolicy>> {
76
+ const parsed = SynthesizePolicyInputSchema.safeParse(raw)
77
+ if (!parsed.success) {
78
+ return {
79
+ ok: false,
80
+ error: validationError('synthesize_policy', parsed.error.issues),
81
+ }
82
+ }
83
+ const input = parsed.data
84
+ const ozConfig: OzAdapterConfig = resolveOzConfig(input)
85
+
86
+ if (input.source === 'mandate') {
87
+ // Zod's optional fields widen to `T | undefined`, which the core's
88
+ // exact-optional MandateSpec rejects; the schema already validated the
89
+ // shape, so assert it (same pattern as the recordedTx cast below).
90
+ return synthesizeFromMandate(input.mandate as MandateSpec, ozConfig)
91
+ }
92
+ // recording source
93
+ const recorded: RecordedTransaction = input.recordedTx as RecordedTransaction
94
+ return synthesizeFromRecording(
95
+ recorded,
96
+ {
97
+ network: input.network,
98
+ ...(input.userResponses !== undefined ? { userResponses: input.userResponses } : {}),
99
+ ...(input.confidenceOverride !== undefined
100
+ ? { confidenceOverride: input.confidenceOverride }
101
+ : {}),
102
+ } as SynthesizeFromRecordingOptions,
103
+ ozConfig
104
+ )
105
+ }
106
+
107
+ function resolveOzConfig(input: SynthesizePolicyInput): OzAdapterConfig {
108
+ if (input.ozConfig) return input.ozConfig
109
+ // The mandate path is network-agnostic; fall back to mainnet so the
110
+ // placeholder OZ instance addresses are deterministic.
111
+ return placeholderOzConfig('mainnet')
112
+ }
113
+
114
+ /** Build a canonical ToolError for a Zod validation failure. The remediation
115
+ * hint points the agent back at the right tool with an empty arg bag - the
116
+ * tool name IS the machine-readable hint. */
117
+ function validationError(
118
+ toolName: 'record_transaction' | 'synthesize_policy',
119
+ issues: ReadonlyArray<{ path: ReadonlyArray<string | number>; message: string }>
120
+ ): ToolError {
121
+ const code: ErrorCode = toolName === 'record_transaction' ? 'RECORDING_FAILED' : 'SYNTHESIS_ERROR'
122
+ return {
123
+ code,
124
+ message: `${toolName}: invalid input: ${issues
125
+ .map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`)
126
+ .join('; ')}`,
127
+ severity: 'error',
128
+ retryable: false,
129
+ remediation: {
130
+ toolCall: { name: toolName, args: {} },
131
+ },
132
+ }
133
+ }
@@ -0,0 +1,155 @@
1
+ // apps/policy-builder-mcp/src/transports/http.ts
2
+ //
3
+ // Streamable HTTP transport (hosted). Uses the Node http module directly so
4
+ // the package stays thin - no express / hono dep. We run in STATELESS mode
5
+ // (sessionIdGenerator: undefined) so each POST /mcp is its own transaction:
6
+ // this matches the brief's "stateless across calls" invariant.
7
+ //
8
+ // Single endpoint: POST /mcp (the SDK also accepts GET for SSE streaming, but
9
+ // the T1 surface does not emit server-initiated messages so we omit it).
10
+ // Listens on 127.0.0.1 by default; pass `host: '0.0.0.0'` to expose.
11
+
12
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
13
+ import type { ToolError } from '@crediolabs/policy-synth'
14
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
15
+ import { createMcpServer } from '../server.ts'
16
+
17
+ export interface StartHttpServerOptions {
18
+ port: number
19
+ host?: string
20
+ /** Path the server mounts the MCP endpoint at. Default `/mcp`. */
21
+ path?: string
22
+ }
23
+
24
+ export interface RunningHttpServer {
25
+ port: number
26
+ host: string
27
+ path: string
28
+ close: () => Promise<void>
29
+ }
30
+
31
+ /** Stateless Streamable HTTP server. Resolves once the server is listening.
32
+ * The returned handle exposes `close()` for tests + clean shutdown. */
33
+ export async function startHttpServer(opts: StartHttpServerOptions): Promise<RunningHttpServer> {
34
+ const host = opts.host ?? '127.0.0.1'
35
+ const path = opts.path ?? '/mcp'
36
+ const server = createMcpServer()
37
+ // One transport per server (the SDK reuses the transport for every request
38
+ // in stateless mode). We connect it once at startup and reuse it.
39
+ const transport = new StreamableHTTPServerTransport({
40
+ sessionIdGenerator: undefined,
41
+ })
42
+ await server.connect(transport)
43
+
44
+ const httpServer: Server = createServer(async (req, res) => {
45
+ if (!req.url) {
46
+ sendJson(res, 400, { error: 'missing url' })
47
+ return
48
+ }
49
+ const url = new URL(req.url, `http://${host}`)
50
+ if (url.pathname !== path) {
51
+ sendJson(res, 404, { error: 'not found', path: url.pathname })
52
+ return
53
+ }
54
+ if (req.method !== 'POST') {
55
+ // The SDK ignores non-POST in stateless mode (no GET/SSE needed in T1).
56
+ sendJson(res, 405, { error: 'method not allowed', method: req.method ?? null })
57
+ return
58
+ }
59
+
60
+ // Reject an over-cap body fast via Content-Length; the streaming reader is
61
+ // the backstop for chunked/unknown-length requests.
62
+ const declaredLength = Number(req.headers['content-length'])
63
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_BODY_BYTES) {
64
+ sendJson(res, 413, { error: 'request body too large' })
65
+ return
66
+ }
67
+
68
+ // Read the JSON-RPC body. The SDK accepts a pre-parsed body, so we parse
69
+ // it here rather than the SDK trying to re-stream the raw req.
70
+ let body: unknown
71
+ try {
72
+ body = await readJsonBody(req)
73
+ } catch (e) {
74
+ if (e instanceof BodyTooLargeError) {
75
+ sendJson(res, 413, { error: 'request body too large' })
76
+ } else {
77
+ sendJson(res, 400, { error: 'invalid JSON body' })
78
+ }
79
+ return
80
+ }
81
+ // The T1 surface is one request per call. A JSON-RPC batch (array) is
82
+ // rejected explicitly rather than silently dropping the extra calls.
83
+ if (Array.isArray(body)) {
84
+ sendJson(res, 400, {
85
+ error: 'JSON-RPC batch requests are not supported; send one request per call',
86
+ })
87
+ return
88
+ }
89
+
90
+ try {
91
+ // `handleRequest` writes the response and returns once the message has
92
+ // been dispatched. No shared state across calls in stateless mode.
93
+ await transport.handleRequest(req as IncomingMessage & { auth?: never }, res, body)
94
+ } catch {
95
+ // The SDK normally writes structured errors itself; this is a belt +
96
+ // braces guard so a thrown error does not leave the socket hanging.
97
+ if (!res.headersSent) {
98
+ const error: ToolError = {
99
+ code: 'SYNTHESIS_ERROR',
100
+ message: 'internal server error',
101
+ severity: 'error',
102
+ retryable: false,
103
+ }
104
+ sendJson(res, 500, { error })
105
+ } else res.end()
106
+ }
107
+ })
108
+
109
+ await new Promise<void>((resolve, reject) => {
110
+ httpServer.once('error', reject)
111
+ httpServer.listen(opts.port, host, () => {
112
+ httpServer.off('error', reject)
113
+ resolve()
114
+ })
115
+ })
116
+
117
+ return {
118
+ port: opts.port,
119
+ host,
120
+ path,
121
+ close: async () => {
122
+ await new Promise<void>((resolve) => httpServer.close(() => resolve()))
123
+ await transport.close().catch(() => {})
124
+ await server.close().catch(() => {})
125
+ },
126
+ }
127
+ }
128
+
129
+ function sendJson(res: ServerResponse, status: number, body: unknown): void {
130
+ res.statusCode = status
131
+ res.setHeader('content-type', 'application/json')
132
+ res.end(JSON.stringify(body))
133
+ }
134
+
135
+ /** Reject bodies larger than this before buffering the whole payload - a
136
+ * recorded transaction is far smaller, so this only stops abusive requests. */
137
+ const MAX_BODY_BYTES = 1_048_576
138
+
139
+ /** Distinguishes an over-cap body from a malformed one so the handler can send
140
+ * a 413 rather than a misleading 400. */
141
+ class BodyTooLargeError extends Error {}
142
+
143
+ async function readJsonBody(req: IncomingMessage): Promise<unknown> {
144
+ const chunks: Buffer[] = []
145
+ let total = 0
146
+ for await (const chunk of req) {
147
+ total += (chunk as Buffer).length
148
+ if (total > MAX_BODY_BYTES) throw new BodyTooLargeError('request body too large')
149
+ chunks.push(chunk as Buffer)
150
+ }
151
+ if (chunks.length === 0) return {}
152
+ const raw = Buffer.concat(chunks).toString('utf8')
153
+ if (!raw) return {}
154
+ return JSON.parse(raw)
155
+ }
@@ -0,0 +1,17 @@
1
+ // apps/policy-builder-mcp/src/transports/stdio.ts
2
+ //
3
+ // stdio transport (Claude Desktop / local agents). The MCP SDK reads JSON-RPC
4
+ // from stdin and writes to stdout. Each process serves ONE client and exits
5
+ // when the client closes the stream. No key custody, no global state; the
6
+ // per-call state lives entirely in the McpServer instance.
7
+
8
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
9
+ import { createMcpServer } from '../server.ts'
10
+
11
+ export async function startStdioServer(): Promise<void> {
12
+ const server = createMcpServer()
13
+ const transport = new StdioServerTransport()
14
+ await server.connect(transport)
15
+ // The transport owns the process from here; no shutdown signal handling -
16
+ // SIGPIPE / EOF on stdin terminates the loop naturally.
17
+ }