midnight-mcp 0.0.9 → 0.1.1

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.
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Sampling service for agentic workflows
3
+ *
4
+ * Enables the MCP server to request LLM completions from the client,
5
+ * allowing for sophisticated multi-step workflows like:
6
+ * - Auto-generating contracts from examples
7
+ * - Code review with suggested fixes
8
+ * - Documentation generation
9
+ */
10
+ import { logger } from "../utils/index.js";
11
+ // Store for the sampling callback
12
+ let samplingCallback = null;
13
+ /**
14
+ * Check if sampling is available
15
+ */
16
+ export function isSamplingAvailable() {
17
+ return samplingCallback !== null;
18
+ }
19
+ /**
20
+ * Register the sampling callback from the client
21
+ * This is called during server initialization when client supports sampling
22
+ */
23
+ export function registerSamplingCallback(callback) {
24
+ samplingCallback = callback;
25
+ logger.info("Sampling capability registered");
26
+ }
27
+ /**
28
+ * Request a completion from the LLM via the client
29
+ */
30
+ export async function requestCompletion(messages, options = {}) {
31
+ if (!samplingCallback) {
32
+ throw new Error("Sampling not available - client does not support this capability");
33
+ }
34
+ const request = {
35
+ messages: messages.map((m) => ({
36
+ role: m.role,
37
+ content: { type: "text", text: m.content },
38
+ })),
39
+ systemPrompt: options.systemPrompt,
40
+ maxTokens: options.maxTokens ?? 2048,
41
+ temperature: options.temperature ?? 0.7,
42
+ modelPreferences: options.modelPreferences ?? {
43
+ hints: [{ name: "claude-3-sonnet" }, { name: "gpt-4" }],
44
+ intelligencePriority: 0.8,
45
+ speedPriority: 0.5,
46
+ },
47
+ };
48
+ logger.debug("Requesting LLM completion", {
49
+ messageCount: messages.length,
50
+ maxTokens: request.maxTokens,
51
+ });
52
+ const response = await samplingCallback(request);
53
+ if (response.content.type !== "text") {
54
+ throw new Error("Unexpected response content type");
55
+ }
56
+ return response.content.text;
57
+ }
58
+ /**
59
+ * Generate a Compact contract based on requirements
60
+ */
61
+ export async function generateContract(requirements, options = {}) {
62
+ if (!isSamplingAvailable()) {
63
+ return {
64
+ code: "",
65
+ explanation: "Sampling not available - this feature requires a client that supports the sampling capability (like Claude Desktop)",
66
+ warnings: ["Feature unavailable without sampling support"],
67
+ };
68
+ }
69
+ const systemPrompt = `You are an expert Compact smart contract developer for the Midnight blockchain.
70
+ Your task is to generate secure, well-documented Compact contracts based on user requirements.
71
+
72
+ Key Compact concepts:
73
+ - \`ledger { }\` - Defines on-chain state (public and private)
74
+ - \`@private\` - Marks state as private/shielded
75
+ - \`export circuit\` - Public functions that generate ZK proofs
76
+ - \`witness\` - Off-chain computation functions
77
+ - \`assert()\` - Creates ZK constraints
78
+ - \`Counter\`, \`Map<K,V>\`, \`Set<T>\` - Built-in collection types
79
+ - \`Field\`, \`Boolean\`, \`Uint<N>\`, \`Bytes<N>\` - Primitive types
80
+
81
+ Always include:
82
+ 1. Proper imports (include "std")
83
+ 2. Clear ledger state definitions
84
+ 3. Access control where appropriate
85
+ 4. Comprehensive inline comments
86
+
87
+ Return ONLY the Compact code, no explanations.`;
88
+ const userPrompt = options.baseExample
89
+ ? `Based on this example contract:
90
+ \`\`\`compact
91
+ ${options.baseExample}
92
+ \`\`\`
93
+
94
+ Generate a new contract with these requirements:
95
+ ${requirements}`
96
+ : `Generate a Compact smart contract with these requirements:
97
+ ${requirements}
98
+
99
+ Contract type: ${options.contractType || "custom"}`;
100
+ try {
101
+ const code = await requestCompletion([{ role: "user", content: userPrompt }], {
102
+ systemPrompt,
103
+ maxTokens: 4096,
104
+ temperature: 0.3, // Lower temperature for code generation
105
+ modelPreferences: {
106
+ hints: [{ name: "claude-3-sonnet" }],
107
+ intelligencePriority: 0.9,
108
+ speedPriority: 0.3,
109
+ },
110
+ });
111
+ // Extract code from markdown if wrapped
112
+ const extractedCode = code.includes("```")
113
+ ? code
114
+ .replace(/```compact?\n?/g, "")
115
+ .replace(/```/g, "")
116
+ .trim()
117
+ : code.trim();
118
+ // Generate explanation
119
+ const explanation = await requestCompletion([
120
+ {
121
+ role: "user",
122
+ content: `Briefly explain what this Compact contract does (2-3 sentences):
123
+ \`\`\`compact
124
+ ${extractedCode}
125
+ \`\`\``,
126
+ },
127
+ ], {
128
+ systemPrompt: "You are a Compact contract documentation expert. Be concise.",
129
+ maxTokens: 256,
130
+ temperature: 0.5,
131
+ });
132
+ return {
133
+ code: extractedCode,
134
+ explanation: explanation.trim(),
135
+ warnings: [],
136
+ };
137
+ }
138
+ catch (error) {
139
+ logger.error("Contract generation failed", { error: String(error) });
140
+ return {
141
+ code: "",
142
+ explanation: `Contract generation failed: ${String(error)}`,
143
+ warnings: ["Generation failed - check logs for details"],
144
+ };
145
+ }
146
+ }
147
+ /**
148
+ * Review contract code and suggest improvements
149
+ */
150
+ export async function reviewContract(code) {
151
+ if (!isSamplingAvailable()) {
152
+ return {
153
+ summary: "Code review requires sampling capability",
154
+ issues: [
155
+ {
156
+ severity: "info",
157
+ message: "This feature requires a client that supports the sampling capability",
158
+ },
159
+ ],
160
+ };
161
+ }
162
+ const systemPrompt = `You are a Compact smart contract security auditor.
163
+ Review the provided contract for:
164
+ 1. Security vulnerabilities
165
+ 2. Privacy concerns (improper handling of shielded state)
166
+ 3. Logic errors
167
+ 4. Best practice violations
168
+ 5. Gas/performance issues
169
+
170
+ Respond in JSON format:
171
+ {
172
+ "summary": "Brief summary of the contract and overall quality",
173
+ "issues": [
174
+ {
175
+ "severity": "error|warning|info",
176
+ "line": optional_line_number,
177
+ "message": "Description of the issue",
178
+ "suggestion": "How to fix it"
179
+ }
180
+ ],
181
+ "improvedCode": "Full improved contract code if changes are needed"
182
+ }`;
183
+ try {
184
+ const response = await requestCompletion([
185
+ {
186
+ role: "user",
187
+ content: `Review this Compact contract:\n\`\`\`compact\n${code}\n\`\`\``,
188
+ },
189
+ ], {
190
+ systemPrompt,
191
+ maxTokens: 4096,
192
+ temperature: 0.2,
193
+ });
194
+ // Parse JSON response with error handling
195
+ const jsonMatch = response.match(/\{[\s\S]*\}/);
196
+ if (jsonMatch) {
197
+ try {
198
+ const parsed = JSON.parse(jsonMatch[0]);
199
+ // Validate expected structure
200
+ return {
201
+ summary: typeof parsed.summary === "string"
202
+ ? parsed.summary
203
+ : "Review complete",
204
+ issues: Array.isArray(parsed.issues) ? parsed.issues : [],
205
+ improvedCode: typeof parsed.improvedCode === "string"
206
+ ? parsed.improvedCode
207
+ : undefined,
208
+ };
209
+ }
210
+ catch (parseError) {
211
+ logger.warn("Failed to parse JSON from LLM response", {
212
+ error: String(parseError),
213
+ });
214
+ return {
215
+ summary: response,
216
+ issues: [],
217
+ };
218
+ }
219
+ }
220
+ return {
221
+ summary: response,
222
+ issues: [],
223
+ };
224
+ }
225
+ catch (error) {
226
+ logger.error("Contract review failed", { error: String(error) });
227
+ return {
228
+ summary: `Review failed: ${String(error)}`,
229
+ issues: [
230
+ {
231
+ severity: "error",
232
+ message: "Review failed - check logs for details",
233
+ },
234
+ ],
235
+ };
236
+ }
237
+ }
238
+ /**
239
+ * Generate documentation for a contract
240
+ */
241
+ export async function generateDocumentation(code, format = "markdown") {
242
+ if (!isSamplingAvailable()) {
243
+ return "Documentation generation requires sampling capability";
244
+ }
245
+ const systemPrompt = format === "markdown"
246
+ ? `Generate comprehensive Markdown documentation for this Compact contract.
247
+ Include:
248
+ - Overview and purpose
249
+ - State variables (with privacy annotations)
250
+ - Circuit functions with parameters and effects
251
+ - Witness functions
252
+ - Usage examples
253
+ - Security considerations`
254
+ : `Generate JSDoc-style documentation comments for this Compact contract.
255
+ Add documentation comments above each:
256
+ - Ledger field
257
+ - Circuit function
258
+ - Witness function
259
+ - Type definition`;
260
+ try {
261
+ return await requestCompletion([
262
+ {
263
+ role: "user",
264
+ content: `Generate ${format} documentation for:\n\`\`\`compact\n${code}\n\`\`\``,
265
+ },
266
+ ], {
267
+ systemPrompt,
268
+ maxTokens: 4096,
269
+ temperature: 0.5,
270
+ });
271
+ }
272
+ catch (error) {
273
+ logger.error("Documentation generation failed", { error: String(error) });
274
+ return `Documentation generation failed: ${String(error)}`;
275
+ }
276
+ }
277
+ //# sourceMappingURL=sampling.js.map
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import type { ExtendedToolDefinition } from "../types/index.js";
2
3
  export declare const AnalyzeContractInputSchema: z.ZodObject<{
3
4
  code: z.ZodString;
4
5
  checkSecurity: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
@@ -100,41 +101,6 @@ export declare function explainCircuit(input: ExplainCircuitInput): Promise<{
100
101
  error?: undefined;
101
102
  suggestion?: undefined;
102
103
  }>;
103
- export declare const analyzeTools: ({
104
- name: string;
105
- description: string;
106
- inputSchema: {
107
- type: "object";
108
- properties: {
109
- code: {
110
- type: string;
111
- description: string;
112
- };
113
- checkSecurity: {
114
- type: string;
115
- description: string;
116
- };
117
- circuitCode?: undefined;
118
- };
119
- required: string[];
120
- };
121
- handler: typeof analyzeContract;
122
- } | {
123
- name: string;
124
- description: string;
125
- inputSchema: {
126
- type: "object";
127
- properties: {
128
- circuitCode: {
129
- type: string;
130
- description: string;
131
- };
132
- code?: undefined;
133
- checkSecurity?: undefined;
134
- };
135
- required: string[];
136
- };
137
- handler: typeof explainCircuit;
138
- })[];
104
+ export declare const analyzeTools: ExtendedToolDefinition[];
139
105
  export {};
140
106
  //# sourceMappingURL=analyze.d.ts.map
@@ -230,6 +230,149 @@ function getPrivacyConsiderations(circuit) {
230
230
  }
231
231
  return considerations;
232
232
  }
233
+ // Output schemas for analysis tools - aligned with actual function return types
234
+ const analyzeContractOutputSchema = {
235
+ type: "object",
236
+ properties: {
237
+ summary: {
238
+ type: "object",
239
+ description: "Summary statistics of the contract",
240
+ properties: {
241
+ hasLedger: { type: "boolean" },
242
+ hasCircuits: { type: "boolean" },
243
+ hasWitnesses: { type: "boolean" },
244
+ totalLines: { type: "number" },
245
+ publicCircuits: { type: "number" },
246
+ privateCircuits: { type: "number" },
247
+ publicState: { type: "number" },
248
+ privateState: { type: "number" },
249
+ },
250
+ },
251
+ structure: {
252
+ type: "object",
253
+ description: "Contract structure breakdown",
254
+ properties: {
255
+ imports: { type: "array", items: { type: "string" } },
256
+ exports: { type: "array", items: { type: "string" } },
257
+ ledger: {
258
+ type: "array",
259
+ description: "Ledger state fields",
260
+ items: {
261
+ type: "object",
262
+ properties: {
263
+ name: { type: "string" },
264
+ type: { type: "string" },
265
+ isPrivate: { type: "boolean" },
266
+ },
267
+ },
268
+ },
269
+ circuits: {
270
+ type: "array",
271
+ description: "Circuit definitions",
272
+ items: {
273
+ type: "object",
274
+ properties: {
275
+ name: { type: "string" },
276
+ isPublic: { type: "boolean" },
277
+ parameters: { type: "array", items: { type: "object" } },
278
+ returnType: { type: "string" },
279
+ },
280
+ },
281
+ },
282
+ witnesses: {
283
+ type: "array",
284
+ description: "Witness functions",
285
+ items: {
286
+ type: "object",
287
+ properties: {
288
+ name: { type: "string" },
289
+ parameters: { type: "array", items: { type: "object" } },
290
+ returnType: { type: "string" },
291
+ },
292
+ },
293
+ },
294
+ types: {
295
+ type: "array",
296
+ description: "Type definitions",
297
+ items: {
298
+ type: "object",
299
+ properties: {
300
+ name: { type: "string" },
301
+ definition: { type: "string" },
302
+ },
303
+ },
304
+ },
305
+ },
306
+ },
307
+ securityFindings: {
308
+ type: "array",
309
+ description: "Security analysis findings",
310
+ items: {
311
+ type: "object",
312
+ properties: {
313
+ severity: {
314
+ type: "string",
315
+ enum: ["info", "warning", "error"],
316
+ },
317
+ message: { type: "string" },
318
+ suggestion: { type: "string" },
319
+ },
320
+ },
321
+ },
322
+ recommendations: {
323
+ type: "array",
324
+ items: { type: "string" },
325
+ description: "Recommendations for improvement",
326
+ },
327
+ },
328
+ required: ["summary", "structure", "securityFindings", "recommendations"],
329
+ description: "Detailed contract analysis with security findings",
330
+ };
331
+ const explainCircuitOutputSchema = {
332
+ type: "object",
333
+ properties: {
334
+ circuitName: { type: "string", description: "Circuit name" },
335
+ isPublic: { type: "boolean", description: "Whether it's exported" },
336
+ parameters: {
337
+ type: "array",
338
+ items: {
339
+ type: "object",
340
+ properties: {
341
+ name: { type: "string" },
342
+ type: { type: "string" },
343
+ },
344
+ },
345
+ description: "Circuit parameters",
346
+ },
347
+ returnType: { type: "string", description: "Return type" },
348
+ explanation: {
349
+ type: "string",
350
+ description: "Plain language explanation",
351
+ },
352
+ operations: {
353
+ type: "array",
354
+ items: { type: "string" },
355
+ description: "Operations performed by the circuit",
356
+ },
357
+ zkImplications: {
358
+ type: "array",
359
+ items: { type: "string" },
360
+ description: "Zero-knowledge proof implications",
361
+ },
362
+ privacyConsiderations: {
363
+ type: "array",
364
+ items: { type: "string" },
365
+ description: "Privacy-related considerations",
366
+ },
367
+ },
368
+ required: [
369
+ "circuitName",
370
+ "explanation",
371
+ "zkImplications",
372
+ "privacyConsiderations",
373
+ ],
374
+ description: "Detailed circuit explanation with privacy analysis",
375
+ };
233
376
  // Tool definitions for MCP
234
377
  export const analyzeTools = [
235
378
  {
@@ -249,6 +392,12 @@ export const analyzeTools = [
249
392
  },
250
393
  required: ["code"],
251
394
  },
395
+ outputSchema: analyzeContractOutputSchema,
396
+ annotations: {
397
+ readOnlyHint: true,
398
+ idempotentHint: true,
399
+ title: "Analyze Compact Contract",
400
+ },
252
401
  handler: analyzeContract,
253
402
  },
254
403
  {
@@ -264,6 +413,12 @@ export const analyzeTools = [
264
413
  },
265
414
  required: ["circuitCode"],
266
415
  },
416
+ outputSchema: explainCircuitOutputSchema,
417
+ annotations: {
418
+ readOnlyHint: true,
419
+ idempotentHint: true,
420
+ title: "Explain Circuit",
421
+ },
267
422
  handler: explainCircuit,
268
423
  },
269
424
  ];
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Contract generation tool using sampling capability
3
+ *
4
+ * Enables AI-assisted generation and review of Compact smart contracts
5
+ */
6
+ import type { ExtendedToolDefinition } from "../types/index.js";
7
+ export declare const generationTools: ExtendedToolDefinition[];
8
+ export declare const generationHandlers: Record<string, (args: any) => Promise<any>>;
9
+ //# sourceMappingURL=generation.d.ts.map