Ninja CLI Tutorial
The Ninja CLI is a powerful command-line tool that enables you to:
- Create and manage MCP servers
- Develop and deploy custom tools
- Manage context vaults for document storage and retrieval
- Test tools directly from the command line
- Integrate with the ninja.ai cloud platform
Installation
Installing the Ninja CLI is quick and easy. Simply run the following command in your terminal:
This script will:
- Download the latest version of the Ninja CLI
- Install it to your system
- Add it to your PATH for easy access
ninja version
Authentication
Getting Your API Token
Before using the Ninja CLI, you need to authenticate with your ninja.ai account:
- Log in to your ninja.ai account
- Visit https://ninja.ai/api_tokens
- Create a new token or copy an existing one
Logging In
Once you have your API token, run:
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
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
Step 3: Push to Ninja.ai
This uploads your server and tools to the ninja.ai platform.
Step 4: Install for Your Account
This makes the server available through your MCP gateway.
Step 5: Test Your Tool
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
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:
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:
What Happens During Push
- Reads
mcp_server.json
in the current directory - Creates or updates the server on ninja.ai
- Scans for tools in the current directory and
tools/
subdirectory - Creates or updates each tool found
- Updates local files with server and tool IDs
Listing Available Tools
To see all tools available through your gateway:
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
Examples
Call without arguments:
Call with arguments:
Complex arguments:
Adding New Tools
Add new tools to an existing MCP server project:
This creates:
tools/weather_forecast/mcp_tool.json
- Tool configurationtools/weather_forecast/mcp_tool.js
- Tool implementation
Tool Naming
Tool names are automatically converted to snake_case:
- "Weather Forecast" → "weather_forecast"
- "my-cool-tool" → "my_cool_tool"
- "CalculatorTool" → "calculatortool"
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
Add -v
flag to see email addresses and webhook URLs:
Create a New Vault
Get Vault Details
Delete a Vault
Add -f
to skip confirmation:
Uploading Files to Vaults
Upload a Single File
Specify a custom display name:
Upload an Entire Directory
Include subdirectories:
Preview what will be uploaded:
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 |
Searching Vaults
Search vault contents using natural language queries:
Limit the number of results:
List Files in a Vault
Sync Vault with Vector Store
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
- Always define types: Use "type" field for all properties
- Add descriptions: Help users understand each parameter
- Mark required fields: Use "required" array for mandatory parameters
- Provide defaults: Include sensible defaults where applicable
- 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
- Use descriptive, action-oriented names (e.g., "get_weather", "calculate_tax")
- Keep names concise but clear
- Use snake_case for consistency
2. Input Validation
- Always validate required parameters
- Check data types before processing
- Provide clear error messages
- Handle edge cases gracefully
3. Response Format
- Return consistent response structures
- Include relevant metadata
- Use meaningful field names
- Keep responses focused and relevant
4. Security
- Never hardcode API keys or secrets
- Use environment variables for sensitive data
- Validate and sanitize all inputs
- Handle API errors gracefully
5. Performance
- Minimize external API calls
- Implement appropriate timeouts
- Cache results when appropriate
- Keep tool execution time reasonable
Troubleshooting
Common Issues and Solutions
Solution: Run
ninja login
and enter your API token
Solution: Make sure you're in the project directory created by
ninja create
Solution: Check that both
mcp_tool.json
and mcp_tool.js
exist in the tool directory
Solution: Your token may have expired. Run
ninja login
again with a fresh token
Debug Tips
- Check your current directory: Many commands expect to be run from a project root
- Verify file structure: Ensure all required files are present and properly named
- Test tools locally: Use
ninja call
to test before deploying - Check JSON syntax: Invalid JSON in config files will cause errors
- Review server logs: Error messages often contain helpful details
Getting Help
If you encounter issues not covered here:
- Check the official documentation
- Visit the community forums
- Contact support at support@ninja.ai
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.