Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Midnight MCP

This note explains Midnight MCP, an MCP server that gives AI coding assistants accurate, compiler-validated knowledge of Compact and the Midnight ecosystem.

Docs: Midnight MCP Source: github.com/Olanetsoft/midnight-mcp · npm: midnight-mcp


Intuition First

AI coding assistants, Claude, Cursor, GitHub Copilot, are trained on billions of lines of code. Compact isn’t in that training data. When you ask an AI to write a Compact contract without context, it hallucinates: it invents syntax that looks plausible, references functions that don’t exist, and produces code that fails immediately at compile time.

Midnight MCP solves this by connecting AI assistants to live Midnight knowledge at query time. Instead of guessing, the assistant calls Midnight MCP, gets the current syntax and examples, generates code, validates it against the real Compact compiler, fixes any errors, and gives you working code.

The compile-validate-fix loop runs automatically. You never see the broken intermediate versions.


Mental Model

MCP stands for Model Context Protocol, an open standard that lets AI assistants call external tools during a conversation, rather than relying solely on training data.

Without Midnight MCPWith Midnight MCP
AI guesses Compact syntax from training dataAI queries live Midnight documentation
Generates plausible-but-wrong codeGenerates code from current syntax reference
No validation before showing outputValidates against real Compact compiler
You debug hallucinated errorsCompiler errors are fixed before you see the code
One-shot generationCompile → fix → retry loop

Midnight MCP runs as a local server on your machine. Your AI assistant calls it during a conversation the same way it calls a web search tool.


The Problem It Solves

Here’s what an AI assistant produces without Midnight MCP when you ask for a simple counter contract:

// ❌ AI hallucination, not valid Compact
contract Counter {
    state count: Int = 0;

    function increment(): Void {
        count = count + 1;
    }
}

Every part of this is wrong:

HallucinatedCorrect
state countledger count
IntUint<32>, Field, or another bounded type
Void[] (unit type)
functionexport circuit
Direct mutationVia ZK proof

This looks like Solidity. It’s not Compact. With Midnight MCP, the same prompt produces code that compiles.


Installation

Midnight MCP installs in under 60 seconds and requires no API key. Add the configuration for whichever AI tool you use.

Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "midnight": {
      "command": "npx",
      "args": ["-y", "midnight-mcp@latest"]
    }
  }
}

Cursor

Create or edit .cursor/mcp.json in your project root, or ~/.cursor/mcp.json globally:

{
  "mcpServers": {
    "midnight": {
      "command": "npx",
      "args": ["-y", "midnight-mcp@latest"]
    }
  }
}

VS Code with GitHub Copilot

Create or edit .vscode/mcp.json in your project:

{
  "servers": {
    "midnight": {
      "command": "npx",
      "args": ["-y", "midnight-mcp@latest"]
    }
  }
}

Restart your AI assistant after adding the configuration. Midnight MCP starts on demand, it only runs when you’re in a Compact-related conversation.


How It Works

When you ask for a Compact contract, here’s what happens behind the scenes:

You ask: "Write a token contract in Compact"
        │
        ▼
AI calls midnight-get-latest-syntax
        │ gets current Compact syntax reference
        ▼
AI generates contract code
        │
        ▼
AI calls midnight-compile-contract
        │ real Compact compiler validates the code
        ▼
 ┌──────────────────┐
 │ Compilation OK?  │
 └──────────────────┘
      │         │
     Yes        No
      │         │
      │         ▼
      │  AI reads error (line + column)
      │  fixes the code
      │  retries compilation
      │         │
      └────►────┘
      ▼
You see working, compiler-validated code

The loop runs silently. You never see the failed intermediate attempts.

Graceful fallback

If the hosted compiler is temporarily unavailable, Midnight MCP falls back to static analysis and tells you which validation method was used:

validationType: "compiler"                  // real compiler
validationType: "static-analysis-fallback"  // compiler unavailable

The 29 Tools

Midnight MCP provides 29 tools across five categories. You don’t call these directly, the AI assistant uses them during your conversation.

Search tools

ToolWhat it does
midnight-search-compactSearch Compact code across indexed repos
midnight-search-docsSearch official Midnight documentation
midnight-search-typescriptSearch TypeScript SDK implementations
midnight-fetch-docsFetch live documentation site content

Analysis tools

ToolWhat it does
midnight-compile-contractValidate code against the real Compact compiler
midnight-analyze-contractRun 15 static security checks
midnight-review-contractAI-powered security review
midnight-extract-contract-structureParse contract structure and exports

midnight-analyze-contract is particularly relevant for auditing workflows, it runs 15 automated security checks including disclosure patterns, sealed field usage, and nullifier correctness.

Generation tools

ToolWhat it does
midnight-generate-contractGenerate contracts from natural language descriptions
midnight-document-contractGenerate documentation in Markdown or JSDoc format

Repository tools

ToolWhat it does
midnight-get-fileRetrieve any file from 102 indexed Midnight repos
midnight-get-file-at-versionGet file content at a specific version
midnight-compare-syntaxCompare syntax between Compact versions
midnight-get-latest-syntaxCurrent Compact syntax reference
midnight-get-repo-contextEverything needed to start coding (compound tool)
midnight-list-examplesList available example contracts

Version management tools

ToolWhat it does
midnight-upgrade-checkFull upgrade analysis (compound tool)
midnight-check-breaking-changesIdentify breaking changes between versions
midnight-get-migration-guideStep-by-step migration instructions

Built-In Resources and Prompts

Beyond tools, Midnight MCP exposes resources (always-available references) and prompts (task templates).

Resources, available any time without a search:

midnight://syntax/latest      Current Compact syntax
midnight://examples/counter   Counter contract example
midnight://examples/token     Token contract example
midnight://docs/compact       Compact language reference

Prompts, guided templates for common tasks:

PromptWhat it guides you through
create-compact-contractStarting a new contract from scratch
debug-compact-errorFixing compilation errors step by step
security-reviewFull security audit of a contract
compare-compact-versionsMigrating between Compact versions

The security-review prompt is the same one relevant to the auditing workflow described in the note on Midnight Skills, it provides structured AI analysis of a contract using the same knowledge base.


What It Indexes

Midnight MCP indexes every non-archived repository in the Midnight ecosystem, 88 from midnightntwrk and 14 community and partner repos including OpenZeppelin contracts and hackathon winners. The search is semantic, not keyword-based.

Prompt: "How do I implement a token with transfer limits?"

midnight-search-compact returns:
  - Token contract examples from midnight-examples
  - Rate limiting patterns from community repos
  - Relevant documentation sections

Effective Prompt Patterns

Midnight MCP works with your normal prompts, it activates when you’re asking about Compact. A few patterns that work especially well:

Contract generation:

Write a Compact contract that tracks voter eligibility
using a Merkle tree. The owner address should be set
at deployment and sealed.

Error debugging:

I'm getting this Compact compile error. What's wrong
and how do I fix it?

[paste error message]
[paste relevant contract excerpt]

Security review:

Review this Compact contract for security issues,
focus on disclosure patterns and authorization checks.

[paste contract]

Migration:

This contract was written for Compact v0.20. What
needs to change for the current version?

Common Mistakes

  1. Expecting Midnight MCP to work without restarting the AI assistant. After adding the configuration, you must restart Claude Desktop, Cursor, or VS Code. The MCP server connection is established at startup.

  2. Treating the output as unreviewed. Midnight MCP provides compiler validation, not correctness guarantees. A contract that compiles may still have security flaws or incorrect business logic. Review the generated code.

  3. Not using the security-review prompt for new contracts. The midnight-analyze-contract tool runs 15 automated checks. Using it as a first pass before manual review catches common patterns automatically.

  4. Using Midnight MCP as a substitute for understanding Compact. The tool accelerates development but doesn’t replace understanding the privacy model, witness trust boundaries, and circuit constraints. Build the mental model first (this book), then use MCP to move faster.

  5. Ignoring the validationType field in responses. If it says static-analysis-fallback, the real compiler was unavailable. The code has not been fully validated, test it before trusting it.


Comparison Layer

ToolWhat it gives AI assistantsValidation
No toolTraining data (stale, no Compact)None
Midnight Skills (midnight-skills.netlify.app)Skill files for context injectionNone (knowledge only)
Midnight MCPLive docs + 102 repos + compilerReal Compact compiler

Midnight Skills and Midnight MCP serve different layers of the same problem. Midnight Skills injects curated knowledge into any agent via context files. Midnight MCP provides a richer toolset for interactive development sessions where the AI is actively generating and validating code.


Quick Recap

  • Midnight MCP is an MCP server that gives AI assistants accurate Compact knowledge at query time, not from stale training data.
  • It runs a compile-validate-fix loop automatically, you receive compiler-validated code.
  • Install by adding one JSON config block to your AI assistant and restarting.
  • 29 tools cover search, analysis, generation, repo access, and version management.
  • midnight-analyze-contract runs 15 automated security checks, useful as a first pass in auditing workflows.
  • The security-review prompt provides guided AI contract analysis.
  • Output is compiler-validated, not correctness-guaranteed. Always review generated contracts.
  • Midnight Skills and Midnight MCP are complementary, skills for context injection, MCP for interactive generation.