Ninja CLI Tutorial

Welcome! This tutorial will guide you through using the Ninja CLI to create and manage MCP (Model Context Protocol) servers and tools on the ninja.ai platform.

The Ninja CLI is a powerful command-line tool that enables you to:

Installation

Installing the Ninja CLI is quick and easy. Simply run the following command in your terminal:

curl -sSL https://ninja.ai/cli_install.sh | bash

This script will:

  1. Download the latest version of the Ninja CLI
  2. Install it to your system
  3. Add it to your PATH for easy access
Tip: After installation, you can verify it worked by running ninja version

Authentication

Getting Your API Token

Before using the Ninja CLI, you need to authenticate with your ninja.ai account:

  1. Log in to your ninja.ai account
  2. Visit https://ninja.ai/api_tokens
  3. Create a new token or copy an existing one

Logging In

Once you have your API token, run:

ninja login

When prompted, paste your API token. The token will be securely saved to ~/.ninja/config.json.

Example Output:
To get your API token:
  1. Log in to your ninja.ai account
  2. Visit: https://ninja.ai/api_tokens
  3. Create a new token or copy an existing one

Enter your ninja.ai API token:
Successfully logged in as John Doe
Cloud MCP Gateway: https://ninja.ai/gateway/abc123

Quick Start Guide

Let's create your first MCP server with a custom tool:

Step 1: Create a New Project

ninja create my_first_server

This creates a new directory with the following structure:

my_first_server/
├── mcp_server.json
└── tools/
    └── example_tool/
        ├── mcp_tool.json
        └── mcp_tool.js

Step 2: Navigate to Your Project

cd my_first_server

Step 3: Push to Ninja.ai

ninja push

This uploads your server and tools to the ninja.ai platform.

Step 4: Install for Your Account

ninja install

This makes the server available through your MCP gateway.

Step 5: Test Your Tool

ninja call example_tool '{"message": "Hello, World!"}'

Working with Your Gateway

Your Cloud MCP Gateway is a unique URL that provides access to all your installed MCP servers and tools.

View Your Gateway URL

ninja gateway

This displays your gateway URL, which you can use in any MCP-compatible application.

Creating MCP Servers

The ninja create command scaffolds a new MCP server project:

ninja create weather_server

What Gets Created

File Purpose
mcp_server.json Server configuration and metadata
tools/example_tool/mcp_tool.json Tool configuration and input schema
tools/example_tool/mcp_tool.js Tool implementation in JavaScript

Pushing Changes

The ninja push command uploads your server and all tools to ninja.ai:

ninja push

What Happens During Push

  1. Reads mcp_server.json in the current directory
  2. Creates or updates the server on ninja.ai
  3. Scans for tools in the current directory and tools/ subdirectory
  4. Creates or updates each tool found
  5. Updates local files with server and tool IDs
Note: The push command is idempotent - you can run it multiple times safely. It will create new resources or update existing ones as needed.

Listing Available Tools

To see all tools available through your gateway:

ninja list tools
Example Output:
Connecting to MCP gateway...
Connected successfully!

Available tools (3):

• weather - Get current weather for a location
• calculator - Perform basic arithmetic operations
• example_tool - An example tool that demonstrates the MCP tool structure

Calling Tools

Test your tools directly from the command line:

Basic Usage

ninja call <tool_name> '<json_arguments>'

Examples

Call without arguments:
ninja call hello
Call with arguments:
ninja call weather '{"location": "San Francisco"}'
Complex arguments:
ninja call calculator '{"operation": "multiply", "a": 12, "b": 7}'

Adding New Tools

Add new tools to an existing MCP server project:

ninja add tool weather_forecast

This creates:

Tool Naming

Tool names are automatically converted to snake_case:

Context Vaults

Context Vaults are secure document storage systems that can be searched and accessed by your MCP tools.

📁 Document Storage

Store and organize documents, code files, and text content

🔍 Semantic Search

Search vault contents using natural language queries

📧 Email Integration

Add content by sending emails to your vault's unique address

🔗 Webhook API

Programmatically add content via HTTP webhooks

Vault Commands

List All Vaults

ninja vault list

Add -v flag to see email addresses and webhook URLs:

ninja vault list -v

Create a New Vault

ninja vault create "Project Documentation" -d "Documentation for my project"

Get Vault Details

ninja vault info <vault_id>

Delete a Vault

ninja vault delete <vault_id>

Add -f to skip confirmation:

ninja vault delete <vault_id> -f

Uploading Files to Vaults

Upload a Single File

ninja vault upload <vault_id> document.pdf

Specify a custom display name:

ninja vault upload <vault_id> document.pdf -n "Q4 Report 2024"

Upload an Entire Directory

ninja vault upload-dir <vault_id> ./project-docs

Include subdirectories:

ninja vault upload-dir <vault_id> ./project-docs -r

Preview what will be uploaded:

ninja vault upload-dir <vault_id> ./project-docs --dry-run

Supported File Types

Category Extensions
Documents .txt, .md, .pdf, .doc, .docx, .pptx
Code .js, .ts, .py, .go, .java, .c, .cpp, .cs, .rb, .php, .sh
Web .html, .css, .json
Other .tex

Search vault contents using natural language queries:

ninja vault search <vault_id> "authentication flow"

Limit the number of results:

ninja vault search <vault_id> "API endpoints" -l 20

List Files in a Vault

ninja vault files <vault_id>

Sync Vault with Vector Store

ninja vault sync <vault_id>

MCP Project Structure

Server Configuration (mcp_server.json)

{
  "name": "Weather Server",
  "description": "An MCP server for weather information",
  "id": 12345  // Added automatically after first push
}

Tool Configuration (mcp_tool.json)

{
  "name": "get_weather",
  "description": "Get current weather for a location",
  "input_schema": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "City name or coordinates"
      },
      "units": {
        "type": "string",
        "enum": ["celsius", "fahrenheit"],
        "default": "celsius",
        "description": "Temperature units"
      }
    },
    "required": ["location"]
  }
}

Tool Implementation (mcp_tool.js)

// get_weather.js — Ninja entry point for weather tool

Ninja.serve(async (req) => {
  const body = await req.json();

  // Accept both { params: { … } } and raw { … }
  const params = body.params ?? body;

  try {
    const { location, units = 'celsius' } = params;

    if (!location) {
      return Ninja.errEnvelope("location is required");
    }

    // Your API calls and logic here
    const weather = await fetchWeatherData(location, units);

    return Ninja.okEnvelope({
      location: location,
      temperature: weather.temp,
      conditions: weather.conditions,
      units: units
    });
  } catch (err) {
    return Ninja.errEnvelope(`Failed to get weather: ${err.message}`);
  }
});

Tool Development Guide

Input Schema Best Practices

  1. Always define types: Use "type" field for all properties
  2. Add descriptions: Help users understand each parameter
  3. Mark required fields: Use "required" array for mandatory parameters
  4. Provide defaults: Include sensible defaults where applicable
  5. Use enums: Constrain values when there are limited options

Error Handling

Ninja.serve(async (req) => {
  try {
    // Validate input
    if (!params.required_field) {
      return Ninja.errEnvelope("required_field is missing");
    }

    // Validate types
    if (typeof params.number !== 'number') {
      return Ninja.errEnvelope("number must be a numeric value");
    }

    // Your logic here
    const result = await processData(params);

    return Ninja.okEnvelope(result);
  } catch (err) {
    // Provide helpful error messages
    return Ninja.errEnvelope(`Operation failed: ${err.message}`);
  }
});

Working with External APIs

// Making HTTP requests in your tool
Ninja.serve(async (req) => {
  const { apiKey, query } = await req.json();

  try {
    const response = await fetch('https://api.example.com/data', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ query })
    });

    if (!response.ok) {
      return Ninja.errEnvelope(`API error: ${response.status}`);
    }

    const data = await response.json();
    return Ninja.okEnvelope(data);
  } catch (err) {
    return Ninja.errEnvelope(`Request failed: ${err.message}`);
  }
});

Best Practices

1. Tool Naming

2. Input Validation

3. Response Format

4. Security

5. Performance

Troubleshooting

Common Issues and Solutions

Issue: "not logged in. Run 'ninja login' first"
Solution: Run ninja login and enter your API token
Issue: "mcp_server.json not found in current directory"
Solution: Make sure you're in the project directory created by ninja create
Issue: Tool not appearing after push
Solution: Check that both mcp_tool.json and mcp_tool.js exist in the tool directory
Issue: "API error: 401 Unauthorized"
Solution: Your token may have expired. Run ninja login again with a fresh token

Debug Tips

  1. Check your current directory: Many commands expect to be run from a project root
  2. Verify file structure: Ensure all required files are present and properly named
  3. Test tools locally: Use ninja call to test before deploying
  4. Check JSON syntax: Invalid JSON in config files will cause errors
  5. Review server logs: Error messages often contain helpful details

Getting Help

If you encounter issues not covered here:

Next Steps

Congratulations! You now have a solid understanding of the Ninja CLI. Here are some suggestions for what to do next:

🚀 Build Your First Real Tool

Create a tool that solves a real problem you face. Start simple and iterate.

📚 Explore Advanced Features

Dive deeper into context vaults, webhook integration, and advanced tool patterns.

🤝 Share with the Community

Share your tools and learn from others in the ninja.ai community.

🔗 Integrate with Your Workflow

Connect your MCP tools with other services and automate your workflows.

Happy building! We can't wait to see what you create with the Ninja CLI