How to secure Midnight Nextjs →

Midnight Nextjs MCP Policy

Enforce policies on every tool call to the Midnight Nextjs MCP Server. 35 tools with suggested default rules ready to customise.

Last updated:

14 can modify or destroy data
21 read-only
35 tools total
Read (21) Write / Execute (9) Destructive / Financial (5)

This policy includes sensible default rules. Download it, adjust the limits to match your use case, and run with Intercept.

terminal

# Download policy with default rules

curl -o midnight-next-js-mcp.yaml https://raw.githubusercontent.com/policylayer/intercept/main/policies/midnight-next-js-mcp.yaml

# Run with Intercept

intercept --policy midnight-next-js-mcp.yaml -- npx -y @midnight-nextjs-mcp

This policy includes suggested default rules for common use cases. Adjust rate limits, add argument validation, or remove rules you don't need.

midnight-next-js-mcp.yaml
version: "1"
description: "Policy for midnight-nextjs-mcp"
# Set to "deny" to reject tool calls not listed below
default: "allow"

tools:
    # -- Financial Tools ----------------------------------------
    # midnight_transfer_tokens: Transfer tDUST tokens to another address.

**Transfer Types:**
- **Standard:** Public transfer visible on-chain
- **Shielded:** Private transfer using ZK proofs

**Requirements:**
- Wallet with sufficient balance
- Network connectivity
- Gas for transaction fees

**Fees:**
- Standard transfer: ~0.001 tDUST
- Shielded transfer: ~0.005 tDUST (proof generation)

**Security:** Use `MIDNIGHT_WALLET_SEED` environment variable.
    midnight_transfer_tokens:
        rules:
          - action: deny
            on_deny: "Financial operation requires approval"

    # -- Destructive Tools ----------------------------------------
    # browser_eval: Automate and test web applications using Playwright browser automation.
This tool connects to playwright-mcp server and provides access to all Playwright capabilities.

CRITICAL FOR PAGE VERIFICATION:
When verifying pages in Next.js projects (especially during upgrades or testing), you MUST use browser automation to load pages
in a real browser instead of curl or simple HTTP requests. This is because:
- Browser automation actually renders the page and executes JavaScript (curl only fetches HTML)
- Detects runtime errors, hydration issues, and client-side problems that curl cannot catch
- Verifies the full user experience, not just HTTP status codes
- Captures browser console errors and warnings via console_messages action

IMPORTANT FOR NEXT.JS PROJECTS:
If working with a Next.js application, PRIORITIZE using the 'nextjs_index' and 'nextjs_call' tools instead of browser console log forwarding.
Next.js has built-in MCP integration that provides superior error reporting, build diagnostics, and runtime information
directly from the Next.js dev server. Only use browser_eval's console_messages action as a fallback when these Next.js tools
are not available or when you specifically need to test client-side browser behavior that Next.js runtime cannot capture.

Available actions:
- start: Start browser automation (automatically installs if needed). Verbose logging is always enabled.
- navigate: Navigate to a URL
- click: Click on an element
- type: Type text into an element
- fill_form: Fill multiple form fields at once
- evaluate: Execute JavaScript in browser context
- screenshot: Take a screenshot of the page
- console_messages: Get browser console messages (for Next.js, prefer nextjs_index/nextjs_call tools instead)
- close: Close the browser
- drag: Perform drag and drop
- upload_file: Upload files
- list_tools: List all available browser automation tools from the server

Note: The playwright-mcp server will be automatically installed if not present.
    browser_eval:
        rules:
          - action: deny
            on_deny: "Destructive operation blocked by policy"
    # init: ⚠️ CALL THIS FIRST - Initialize Next.js DevTools MCP context and establish MANDATORY documentation requirements.

**IMPORTANT: This tool MUST be called at the START of every Next.js development session.**

This tool:
- Establishes MANDATORY requirement to use nextjs_docs for ALL Next.js-related queries
- Instructs AI to forget any prior Next.js knowledge and always query docs
- Documents all available MCP tools (nextjs_docs, nextjs_index, nextjs_call, browser_eval, upgrade_nextjs_16, enable_cache_components)

Use this tool at the beginning of a Next.js session to:
- Reset AI's Next.js knowledge baseline
- Ensure 100% documentation-first approach with no exceptions
- Understand available tools and their use cases
- Follow best practices for Next.js development
    init:
        rules:
          - action: deny
            on_deny: "Destructive operation blocked by policy"
    # nextjs_call: Call a specific MCP tool on a running Next.js development server.

REQUIREMENTS:
- Port number of the target Next.js dev server
- Tool name to execute
- Optional arguments object (if the tool requires parameters)

Use 'nextjs_index' first to discover available servers, tools, and their input schemas.
If 'nextjs_index' auto-discovery fails, ask the user for the port and call 'nextjs_index' again with the 'port' parameter.

IMPORTANT: When calling tools:
- The 'args' parameter MUST be an object (e.g., {key: "value"}), NOT a string
- If a tool doesn't require arguments, OMIT the 'args' parameter entirely - do NOT pass {} or "{}"
- Check the tool's inputSchema from 'nextjs_index' to see what arguments are required

Common Next.js MCP tools include:
- Error diagnostics (get compilation/runtime errors)
- Route information (list all routes)
- Build status (check compilation state)
- Cache management (clear caches)
- And more (varies by Next.js version)

Example usage:
1. Call 'nextjs_index' to see servers and tools
2. Call 'nextjs_call' with port=3000, toolName="get_errors" to get errors from server on port 3000
    nextjs_call:
        rules:
          - action: deny
            on_deny: "Destructive operation blocked by policy"
    # nextjs_index: Discover all running Next.js development servers and list their available MCP tools.

WHEN TO USE THIS TOOL - Use proactively in these scenarios:

1. **Before implementing ANY changes to the app**: When asked to add, modify, or fix anything in the application:
   - "Add a loading state" → Check current component structure and routes first
   - "Fix the navigation" → Inspect existing routes and components
   - "Update the API endpoint" → Query current routes and data flows
   - "Add error handling" → Check runtime errors and component hierarchy
   - "Refactor the auth logic" → Inspect current auth implementation and routes
   - "Optimize performance" → Check runtime diagnostics and component tree
   Use this to understand where changes should be made and what currently exists.

2. **For diagnostic and investigation questions**:
   - "What's happening?" / "What's going on?" / "Why isn't this working?"
   - "Check the errors" / "See what's wrong"
   - "What routes are available?" / "Show me the routes"
   - "Clear the cache" / "Reset everything"
   - Questions about build status, compilation errors, or runtime diagnostics

3. **For agentic codebase search**: Use this as FIRST CHOICE for searching the currently running app. If not found, fallback to static codebase search tools.

KEY PRINCIPLE: If the request involves the running Next.js application (whether to investigate OR modify it), query the runtime FIRST to understand current state before proceeding.

REQUIREMENTS:
- Next.js 16 or later (MCP support was added in v16)
- If you're on Next.js 15 or earlier, use the 'upgrade-nextjs-16' MCP prompt to upgrade first

Next.js 16+ exposes an MCP (Model Context Protocol) endpoint at /_next/mcp automatically when the dev server starts.
No configuration needed - MCP is enabled by default in Next.js 16 and later.

This tool discovers all running Next.js servers and returns:
- Server port, PID, and URL
- Complete list of available MCP tools for each server
- Tool descriptions and input schemas

After calling this tool, use 'nextjs_call' to execute specific tools.

[IMPORTANT] If auto-discovery returns no servers:
1. Ask the user which port their Next.js dev server is running on
2. Call this tool again with the 'port' parameter set to the user-provided port

If the MCP endpoint is not available:
1. Ensure you're running Next.js 16 or later (use the 'upgrade-nextjs-16' prompt to upgrade)
2. Verify the dev server is running (npm run dev)
3. Check that the dev server started successfully without errors
    nextjs_index:
        rules:
          - action: deny
            on_deny: "Destructive operation blocked by policy"

    # -- Execute Tools ----------------------------------------
    # midnight_call_contract: Execute a circuit call on a deployed Midnight smart contract.

**Circuit Types:**
- **Public circuits:** Read-only operations that don't modify state
- **Private circuits:** Operations with private witnesses and ZK proofs
- **State-changing circuits:** Modify ledger state (requires wallet)

**Call Process:**
1. Load contract at specified address
2. Prepare circuit arguments
3. Generate ZK proof (if required)
4. Submit transaction
5. Return result or state changes

**Privacy Features:**
- Private inputs are never revealed on-chain
- ZK proofs validate computation without exposing data
- Private state is stored locally with `private_state_id`

**Example:**
```
midnight_call_contract({
  contract_address: "0x123...",
  circuit_name: "transfer",
  arguments: {
    to: "0xabc...",
    amount: 100
  }
})
```
    midnight_call_contract:
        rules:
          - action: allow
            rate_limit: 10/hour
            validate:
              required_args: true
    # midnight_compile_contract: Compile a Compact smart contract to TypeScript bindings and ZK artifacts.

Generates:
- TypeScript type definitions
- Contract interaction code
- Circuit metadata
- ZK proving/verifying keys (references)

Use this tool to:
- Compile Compact source code
- Generate TypeScript bindings for SDK
- Prepare contracts for deployment

**Note:** Full compilation requires the `compactc` compiler installed locally.
    midnight_compile_contract:
        rules:
          - action: allow
            rate_limit: 10/hour
            validate:
              required_args: true
    # midnight_deploy_contract: Deploy a compiled Compact smart contract to the Midnight Network.

**Prerequisites:**
1. Contract must be compiled first using `midnight_compile_contract`
2. Wallet with sufficient tDUST balance for deployment
3. Network connectivity to target environment

**Deployment Process:**
1. Load compiled contract artifacts
2. Initialize contract private state (if any)
3. Create deployment transaction
4. Generate ZK proof for deployment
5. Submit transaction to the network
6. Wait for confirmation

**Returns:**
- Contract address
- Transaction hash
- Block height
- Deployment cost

**Security:** Use `MIDNIGHT_WALLET_SEED` environment variable for wallet credentials.

**Testnet Faucet:** Get free tDUST at https://faucet.testnet.midnight.network
    midnight_deploy_contract:
        rules:
          - action: allow
            rate_limit: 10/hour
            validate:
              required_args: true
    # midnight_init: ⚠️ CALL THIS FIRST - Initialize Midnight Network development context.

**IMPORTANT: This tool MUST be called at the START of every Midnight development session.**

This tool:
- Establishes network configuration (testnet, devnet, or mainnet)
- Documents all available Midnight MCP tools
- Provides guidance on Compact smart contract development
- Sets up provider connections for blockchain queries

Use this tool to:
- Configure which Midnight network to connect to
- Understand available tools for contract development
- Learn about Compact language basics
- Get started with Midnight dApp development
    midnight_init:
        rules:
          - action: allow
            rate_limit: 10/hour
            validate:
              required_args: true
    # midnight_scaffold_project: Scaffold a new Midnight dApp project from a template.

Templates available:
- **counter**: Simple counter contract (great for learning)
- **token**: Private token with transfers and balances
- **voting**: Privacy-preserving voting system
- **blank**: Empty project structure

Generates:
- Compact contract files
- TypeScript SDK integration
- React UI (optional)
- Build and test configuration

Use this tool to:
- Start a new Midnight project quickly
- Learn from example contracts
- Set up proper project structure
    midnight_scaffold_project:
        rules:
          - action: allow
            rate_limit: 10/hour
            validate:
              required_args: true

    # -- Write Tools ----------------------------------------
    # disable_toolset: Disable a toolset that was previously enabled. The tools in this toolset will no longer be available.
    disable_toolset:
        rules:
          - action: allow
            rate_limit: 30/hour
    # enable_cache_components: Migrate Next.js applications to Cache Components mode and complete setup for Next.js 16.

Use this tool when you need to:
- Migrate to Cache Components mode
- Migrate to cache components
- Enable Cache Components
- Set up Cache Components
- Convert to Cache Components

This tool handles ALL steps for migrating and enabling Cache Components:
- Configuration: Updates cacheComponents flag (experimental in 16.0.0, stable in canary > 16), removes incompatible flags
- Dev Server: Starts dev server (MCP is enabled by default in Next.js 16+)
- Error Detection: Loads all routes via browser automation, collects errors using Next.js MCP
- Automated Fixing: Adds Suspense boundaries, "use cache" directives, generateStaticParams, cacheLife profiles, cache tags
- Verification: Validates all routes work with zero errors

Key Features:
- One-time dev server start (no restarts needed)
- Automated error detection using Next.js MCP tools
- Browser-based testing with browser automation
- Fast Refresh applies fixes instantly
- Comprehensive fix strategies for all error types
- Support for "use cache", "use cache: private", Suspense boundaries
- Cache invalidation with cacheTag() and cacheLife() configuration

Requires:
- Next.js 16.0.0+ (stable or canary only - beta versions are NOT supported)
- Clean working directory preferred
- Browser automation installed (auto-installed if needed)

This tool embeds complete knowledge base for:
- Cache Components mechanics
- Error patterns and solutions
- Caching strategies (static vs dynamic)
- Advanced patterns (cacheLife, cacheTag, draft mode)
- Build behavior and prefetching
- Test-driven patterns from 125+ fixtures
    enable_cache_components:
        rules:
          - action: allow
            rate_limit: 30/hour
    # enable_toolset: Enable one of the sets of tools the MCP server provides. Use get_toolset_tools and list_available_toolsets first to see what this will enable.
    enable_toolset:
        rules:
          - action: allow
            rate_limit: 30/hour
    # midnight_create_wallet: Create a new Midnight wallet with a fresh seed phrase.

**Security Warning:**
- The seed phrase will be displayed ONCE
- Store it securely offline
- Never share your seed phrase
- Loss of seed phrase = loss of funds

**Wallet Features:**
- Native tDUST balance management
- Private and shielded transactions
- Contract interaction support
- Multiple address derivation

**After Creation:**
1. Save your seed phrase securely
2. Get testnet tDUST from the faucet
3. Use wallet for contract deployment

**Faucet:** https://faucet.testnet.midnight.network
    midnight_create_wallet:
        rules:
          - action: allow
            rate_limit: 30/hour

    # -- Read Tools ----------------------------------------
    # get_environment_info: Get information about the runtime environment including Node.js version, platform, and system resources.
    get_environment_info:
        rules:
          - action: allow
            rate_limit: 60/minute
    # get_server_status: Get the current server status including health, active connections, and resource usage. Use this to diagnose server issues.
    get_server_status:
        rules:
          - action: allow
            rate_limit: 60/minute
    # get_session_info: Get information about the current MCP session including server version, enabled toolsets, and environment. Use this to understand the current context.
    get_session_info:
        rules:
          - action: allow
            rate_limit: 60/minute
    # get_toolset_tools: Lists all the capabilities that are enabled with the specified toolset. Use this to get clarity on whether enabling a toolset would help you to complete a task.
    get_toolset_tools:
        rules:
          - action: allow
            rate_limit: 60/minute
    # list_available_toolsets: List all available toolsets this MCP server can offer, providing the enabled status of each. Use this when a task could be achieved with a tool and the currently available tools aren't enough. Call get_toolset_tools with these toolset names to discover specific tools you can call.
    list_available_toolsets:
        rules:
          - action: allow
            rate_limit: 60/minute
    # list_enabled_features: List all currently enabled features and feature flags. Use this to understand what capabilities are available.
    list_enabled_features:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_analyze_contract: Perform static analysis on a Compact smart contract.

Analyzes:
- Contract structure and patterns
- Potential security issues
- Gas/complexity estimates
- Best practice violations
- Privacy considerations

Use this tool to:
- Review contracts before deployment
- Identify potential issues
- Learn Compact best practices
- Optimize contract design
    midnight_analyze_contract:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_check_versions: Check for updates to @midnight-ntwrk npm packages.

Compares installed versions against the latest available on npm.
Supports both stable and alpha/beta version tracking.

Use this tool to:
- Check if dependencies are outdated
- Find available updates for Midnight SDK
- Get upgrade commands
- Track alpha/beta releases for early testing
    midnight_check_versions:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_get_balance: Query token balance for a Midnight Network address.

Returns:
- tDUST (native token) balance
- Address information

Use this tool to:
- Check wallet balances
- Verify transaction results
- Monitor account funds

**Note:** For testnet, you can get free tDUST from the faucet.
    midnight_get_balance:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_get_block: Query block information from the Midnight blockchain.

Returns:
- Block height
- Block hash
- Timestamp
- Transaction count

Use this tool to:
- Get current block height (omit height parameter)
- Inspect specific blocks
- Monitor chain progress
    midnight_get_block:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_get_transaction: Query transaction details from the Midnight blockchain.

Returns:
- Transaction hash
- Block height
- Status (pending/confirmed/failed)
- Contract address (if applicable)
- Circuit name (if contract call)

Use this tool to:
- Check transaction status
- Debug failed transactions
- Inspect contract interactions
    midnight_get_transaction:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_network_status: Check the health status of Midnight Network services.

Returns the status of:
- Indexer (GraphQL API for blockchain data)
- Proof Server (ZK proof generation)
- Node RPC (transaction submission)
- Current block height
- Network ID

Use this tool to:
- Verify network connectivity before operations
- Debug connection issues
- Check service latency
    midnight_network_status:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_search_docs: Search Midnight Network official documentation.

Searches across:
- Compact language reference
- SDK/API documentation
- Tutorials and guides
- Example code

Use this tool to:
- Find how to use specific features
- Look up Compact syntax
- Find code examples
- Learn Midnight concepts
    midnight_search_docs:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight_wallet_state: Get detailed wallet state including balances, coins, and sync status.

**Returns:**
- tDUST balance (total and available)
- Individual coin details
- Pending transactions
- Sync status with network

**Coin Types:**
- **Unshielded:** Publicly visible balance
- **Shielded:** Private balance (ZK protected)
- **Pending:** Awaiting confirmation

**Use for:**
- Checking available funds before operations
- Debugging transaction issues
- Monitoring wallet health
    midnight_wallet_state:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight-docs-status: Get the current status of documentation sync, including cache age and available updates.
    midnight-docs-status:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight-fetch-docs: Fetch documentation directly from the official Midnight docs. Use when you know the specific path or need the full content of a documentation page.
    midnight-fetch-docs:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight-list-docs: List all available documentation sources with their sync status.
    midnight-list-docs:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight-search-docs: Search Midnight documentation content. Use for finding guides, API docs, and conceptual explanations about the Midnight blockchain and Compact language.
    midnight-search-docs:
        rules:
          - action: allow
            rate_limit: 60/minute
    # midnight-sync-docs: Sync documentation from the official Midnight repository. Use to ensure documentation is up to date.
    midnight-sync-docs:
        rules:
          - action: allow
            rate_limit: 60/minute
    # nextjs_docs: Fetch Next.js official documentation by path.

IMPORTANT: You MUST first read the `nextjs-docs://llms-index` MCP resource to get the correct path. Do NOT guess paths.

Workflow:
1. Read the `nextjs-docs://llms-index` resource to get the documentation index
2. Find the relevant path in the index for what you're looking for
3. Call this tool with that exact path

Example:
  nextjs_docs({ path: "/docs/app/api-reference/functions/refresh" })
    nextjs_docs:
        rules:
          - action: allow
            rate_limit: 60/minute
    # upgrade_nextjs_16: Guide through upgrading Next.js to version 16.

CRITICAL: Runs the official codemod FIRST (requires clean git state) for automatic upgrades and fixes, then handles remaining issues manually. The codemod upgrades Next.js, React, and React DOM automatically.

Covers:
- Next.js version upgrade to 16
- Async API changes (params, searchParams, cookies, headers)
- Config migration (next.config changes)
- Image defaults and optimization
- Parallel routes and dynamic segments
- Deprecated API removals
- React 19 compatibility

The codemod requires:
- Clean git working directory (commit or stash changes first)
- Node.js 18+
- npm/pnpm/yarn/bun installed

After codemod runs, provides manual guidance for any remaining issues not covered by the codemod.
    upgrade_nextjs_16:
        rules:
          - action: allow
            rate_limit: 60/minute
Can an AI agent move money through the Midnight Nextjs MCP server? +

Yes. The Midnight Nextjs server exposes 1 financial tools including midnight_transfer_tokens. Without a policy, an autonomous agent can call these with no spend caps, no rate limits, and no approval flow. Intercept lets you block financial tools by default or set per-tool rate limits.

Can an AI agent delete data through the Midnight Nextjs MCP server? +

Yes. The Midnight Nextjs server exposes 4 destructive tools including browser_eval, init, nextjs_call. These permanently remove resources with no undo. Intercept blocks destructive tools by default so they never reach the upstream server.

How do I prevent bulk modifications through Midnight Nextjs? +

The Midnight Nextjs server has 4 write tools including disable_toolset, enable_cache_components, enable_toolset. Set rate limits in your policy file -- for example, rate_limit: 10/hour prevents an agent from making more than 10 modifications per hour. Intercept enforces this at the transport layer.

How many tools does the Midnight Nextjs MCP server expose? +

35 tools across 5 categories: Destructive, Execute, Financial, Read, Write. 21 are read-only. 14 can modify, create, or delete data.

How do I add Intercept to my Midnight Nextjs setup? +

One line change. Instead of running the Midnight Nextjs server directly, prefix it with Intercept: intercept -c midnight-next-js-mcp.yaml -- npx -y @midnight-nextjs-mcp. Download a pre-built policy from policylayer.com/policies/midnight-next-js-mcp and adjust the limits to match your use case.

Enforce policies on Midnight Nextjs

Open source. One binary. Zero dependencies.

npx -y @policylayer/intercept
github.com/policylayer/intercept →
// GET IN TOUCH

Have a question or want to learn more? Send us a message.

Message sent.

We'll get back to you soon.