API Reference
Complete MCP Aegis Documentation
Comprehensive reference for MCP Aegis's CLI commands and programmatic JavaScript/TypeScript testing API for Model Context Protocol servers.
CLI Commands
init Command
Initialize MCP Aegis in a Node.js project.
npx mcp-aegis initWhat it does:
- Creates
aegis.config.jsonbased on yourpackage.json - Creates test directory structure (
test/mcp/ortests/mcp/) - Copies
AGENTS.mdguide to test directory - Handles existing directories gracefully
Directory Selection Logic:
- Uses
tests/mcp/iftests/directory exists - Uses
test/mcp/iftest/directory exists (and notests/) - Prefers
tests/overtest/when both exist - Creates
test/mcp/by default when neither exists
query Command
Query MCP server tools directly for debugging without writing test files.
# List all available tools
aegis query --config aegis.config.json
# Call a specific tool with no arguments
aegis query [tool-name] --config aegis.config.json
# Call a tool with arguments (JSON string)
aegis query [tool-name] [tool-args] --config aegis.config.jsonArguments:
[tool-name](optional) - Name of the tool to call. Omit to list all available tools[tool-args](optional) - JSON string of tool arguments (e.g.,{"path": "/tmp/file.txt"})
Options:
--config, -c <path>- Path to aegis.config.json file (default:./aegis.config.json)--json, -j- Output results in JSON format--quiet, -q- Suppress non-essential output
Example Usage:
# List all tools
aegis query
# Call read_file tool with arguments
aegis query read_file '{"path": "../shared-test-data/hello.txt"}'
# Call calculator tool with JSON arguments
aegis query calculator '{"operation": "add", "a": 5, "b": 3}'
# Get JSON output for scripting
aegis query hello '{"name": "World"}' --json
# Use custom config file
aegis query --config ./my-config.jsonUse Cases:
- Quick testing of tools without writing YAML test files
- Server validation during development
- Tool discovery and exploration
- Debugging tool responses and error conditions
- Integration with development workflows
Test Execution
Run YAML-based tests:
# Using specific pattern
aegis "test/mcp/*.test.mcp.yml" --config aegis.config.json
# Using npx (works with both test/ and tests/)
npx mcp-aegis "test*/mcp/**/*.test.mcp.yml"
# With custom config
npx mcp-aegis "test*.yml" --config "./custom-config.json"CLI Options:
| Option | Description |
|---|---|
--config, -c <path> | Path to configuration file (default: ./aegis.config.json) |
--verbose, -v | Display individual test results with test suite hierarchy |
--debug, -d | Enable debug mode with detailed MCP communication logging |
--timing, -t | Show timing information for tests and operations |
--json, -j | Output results in JSON format for CI/automation |
--quiet, -q | Suppress non-essential output (opposite of verbose) |
Example Usage:
# Basic usage
aegis "tests/*.yml" --config config.json
# Verbose output with test hierarchy
aegis "tests/*.yml" --config config.json --verbose
# Debug mode with MCP communication details
aegis "tests/*.yml" --config config.json --debug
# Performance analysis with timing
aegis "tests/*.yml" --config config.json --timing
# CI-friendly JSON output
aegis "tests/*.yml" --config config.json --json
# Minimal output for scripts
aegis "tests/*.yml" --config config.json --quiet
# Combine multiple options
aegis "tests/*.yml" --config config.json --verbose --timing --debugInstallation
NPM
npm install mcp-aegis --save-devYarn
yarn add -D mcp-aegispnpm
pnpm add -D mcp-aegisMain Entry Points
createClient(config)
Creates a new MCPClient instance without connecting.
Parameters:
config(string | object): Configuration file path or configuration object
Returns: Promise<MCPClient>
import { createClient } from 'mcp-aegis';
// From configuration file (generated by init command)
const client = await createClient('./aegis.config.json');
// From configuration object
const client = await createClient({
name: 'Test Server',
command: 'node',
args: ['./server.js']
});connect(config)
Creates and automatically connects a client.
Parameters:
config(string | object): Configuration file path or configuration object
Returns: Promise<MCPClient>
import { connect } from 'mcp-aegis';
// Using config from init command
const client = await connect('./aegis.config.json');
// Client is immediately ready for useMCPClient Class
Direct class constructor for advanced usage.
import { MCPClient } from 'mcp-aegis';
const config = { /* config object */ };
const client = new MCPClient(config);
await client.connect();MCPClient Class
Properties
connected: boolean
Indicates whether the client is connected to the MCP server.
console.log('Connected:', client.connected);config: object
The configuration object used for the connection.
console.log('Server name:', client.config.name);
console.log('Command:', client.config.command);
console.log('Arguments:', client.config.args);handshakeCompleted: boolean
Indicates whether the MCP handshake has been completed successfully.
if (client.handshakeCompleted) {
console.log('Ready to execute tools');
}Core Methods
async connect()
Starts the MCP server process and performs the MCP handshake.
Returns: Promise<void>
Throws:
Errorif server fails to startErrorif handshake failsErrorif connection timeout is reached
try {
await client.connect();
console.log('Server connected and ready');
} catch (error) {
console.error('Connection failed:', error.message);
}async disconnect()
Gracefully shuts down the server connection.
Returns: Promise<void>
await client.disconnect();
console.log('Server disconnected');async listTools()
Retrieves the list of available tools from the MCP server.
Returns: Promise<Tool[]>
Tool Interface:
interface Tool {
name: string;
description: string;
inputSchema: {
type: string;
properties: Record<string, any>;
required?: string[];
};
}const tools = await client.listTools();
tools.forEach(tool => {
console.log(`Tool: ${tool.name}`);
console.log(`Description: ${tool.description}`);
console.log(`Required params: ${tool.inputSchema.required?.join(', ')}`);
});async callTool(name, arguments)
Executes a specific tool with the provided arguments.
Parameters:
name(string): Name of the tool to executearguments(object): Arguments to pass to the tool
Returns: Promise<ToolResult>
ToolResult Interface:
interface ToolResult {
content: Array<{
type: string;
text: string;
[key: string]: any;
}>;
isError?: boolean;
[key: string]: any;
}Throws:
Errorif tool execution failsErrorif tool is not foundErrorif arguments are invalid
try {
const result = await client.callTool('calculator', {
operation: 'add',
a: 15,
b: 27
});
console.log('Result:', result.content[0].text);
console.log('Error status:', result.isError);
} catch (error) {
console.error('Tool execution failed:', error.message);
}async sendMessage(message)
Sends a raw JSON-RPC message to the MCP server.
Parameters:
message(object): JSON-RPC 2.0 message object
Returns: Promise<object>
Message Format:
interface JSONRPCMessage {
jsonrpc: "2.0";
id: string | number;
method: string;
params?: object;
}const response = await client.sendMessage({
jsonrpc: "2.0",
id: "custom-1",
method: "tools/list",
params: {}
});
console.log('Raw response:', response);Utility Methods
getStderr()
Returns the current contents of the stderr buffer.
Returns: string
const stderr = client.getStderr();
if (stderr.trim()) {
console.warn('Server stderr:', stderr);
}clearStderr()
Clears the stderr buffer.
Returns: void
client.clearStderr();
// Stderr buffer is now emptyisConnected()
Checks if the client is connected and the MCP handshake has been completed.
Returns: boolean
if (client.isConnected()) {
console.log('Client is ready to execute tools');
} else {
console.log('Client is not ready - call connect() first');
}Configuration
Configuration Object Schema
interface MCPConfig {
name: string; // Display name for the server
command: string; // Executable command
args: string[]; // Command arguments
cwd?: string; // Working directory (optional)
env?: Record<string, string>; // Environment variables (optional)
startupTimeout?: number; // Startup timeout in ms (default: 5000)
readyPattern?: string; // Regex pattern for server ready signal (optional)
}Basic Configuration
{
"name": "Simple Server",
"command": "node",
"args": ["./server.js"]
}Advanced Configuration
{
"name": "Production API Server",
"command": "python",
"args": ["./api_server.py", "--port", "8080"],
"cwd": "./server",
"env": {
"API_KEY": "test-key",
"DEBUG": "true",
"DATABASE_URL": "sqlite:///test.db"
},
"startupTimeout": 15000,
"readyPattern": "Server listening on port \\d+"
}Error Handling
Connection Errors
Thrown when server fails to start or connect:
try {
await client.connect();
} catch (error) {
if (error.message.includes('Failed to start server')) {
console.error('Server startup failed:', error.message);
} else if (error.message.includes('Connection timeout')) {
console.error('Server took too long to start:', error.message);
} else if (error.message.includes('Handshake failed')) {
console.error('MCP handshake failed:', error.message);
}
}Tool Execution Errors
Thrown when tool calls fail:
try {
const result = await client.callTool('unknown_tool', {});
} catch (error) {
if (error.message.includes('Failed to call tool')) {
console.error('Tool execution failed:', error.message);
} else if (error.message.includes('Tool not found')) {
console.error('Unknown tool:', error.message);
}
}TypeScript Support
MCP Aegis includes full TypeScript type definitions.
Type Definitions
// Main exports
export declare function createClient(config: string | MCPConfig): Promise<MCPClient>;
export declare function connect(config: string | MCPConfig): Promise<MCPClient>;
export declare class MCPClient {
constructor(config: MCPConfig);
readonly connected: boolean;
readonly config: MCPConfig;
readonly handshakeCompleted: boolean;
connect(): Promise<void>;
disconnect(): Promise<void>;
listTools(): Promise<Tool[]>;
callTool(name: string, arguments: Record<string, any>): Promise<ToolResult>;
sendMessage(message: JSONRPCMessage): Promise<any>;
getStderr(): string;
clearStderr(): void;
isConnected(): boolean;
}TypeScript Usage Examples
import { createClient, MCPClient, Tool, ToolResult, MCPConfig } from 'mcp-aegis';
// Typed configuration
const config: MCPConfig = {
name: 'My Server',
command: 'node',
args: ['./server.js'],
startupTimeout: 5000
};
// Typed client
const client: MCPClient = await createClient(config);
await client.connect();
// Typed tool listing
const tools: Tool[] = await client.listTools();
tools.forEach((tool: Tool) => {
console.log(`${tool.name}: ${tool.description}`);
});
// Typed tool execution
const result: ToolResult = await client.callTool('calculator', {
operation: 'add',
a: 10,
b: 5
});
console.log('Result:', result.content[0].text);
console.log('Is error:', result.isError);
await client.disconnect();Related Documentation
- Programmatic Testing - Complete testing guide
- Examples - Real-world usage examples
- Troubleshooting - Debug common issues