MCP

Aegisv1

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.

bash
npx mcp-aegis init

What it does:

  • Creates aegis.config.json based on your package.json
  • Creates test directory structure (test/mcp/ or tests/mcp/)
  • Copies AGENTS.md guide to test directory
  • Handles existing directories gracefully

Directory Selection Logic:

  • Uses tests/mcp/ if tests/ directory exists
  • Uses test/mcp/ if test/ directory exists (and no tests/)
  • Prefers tests/ over test/ when both exist
  • Creates test/mcp/ by default when neither exists

query Command

Query MCP server tools directly for debugging without writing test files.

bash
# 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.json

Arguments:

  • [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:

bash
# 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.json

Use 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:

bash
# 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:

OptionDescription
--config, -c <path>Path to configuration file (default: ./aegis.config.json)
--verbose, -vDisplay individual test results with test suite hierarchy
--debug, -dEnable debug mode with detailed MCP communication logging
--timing, -tShow timing information for tests and operations
--json, -jOutput results in JSON format for CI/automation
--quiet, -qSuppress non-essential output (opposite of verbose)

Example Usage:

bash
# 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 --debug

Installation

NPM

bash
npm install mcp-aegis --save-dev

Yarn

bash
yarn add -D mcp-aegis

pnpm

bash
pnpm add -D mcp-aegis

Main Entry Points

createClient(config)

Creates a new MCPClient instance without connecting.

Parameters:

  • config (string | object): Configuration file path or configuration object

Returns: Promise<MCPClient>

javascript
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>

javascript
import { connect } from 'mcp-aegis';

// Using config from init command
const client = await connect('./aegis.config.json');
// Client is immediately ready for use

MCPClient Class

Direct class constructor for advanced usage.

javascript
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.

javascript
console.log('Connected:', client.connected);

config: object

The configuration object used for the connection.

javascript
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.

javascript
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:

  • Error if server fails to start
  • Error if handshake fails
  • Error if connection timeout is reached
javascript
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>

javascript
await client.disconnect();
console.log('Server disconnected');

async listTools()

Retrieves the list of available tools from the MCP server.

Returns: Promise<Tool[]>

Tool Interface:

typescript
interface Tool {
  name: string;
  description: string;
  inputSchema: {
    type: string;
    properties: Record<string, any>;
    required?: string[];
  };
}
javascript
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 execute
  • arguments (object): Arguments to pass to the tool

Returns: Promise<ToolResult>

ToolResult Interface:

typescript
interface ToolResult {
  content: Array<{
    type: string;
    text: string;
    [key: string]: any;
  }>;
  isError?: boolean;
  [key: string]: any;
}

Throws:

  • Error if tool execution fails
  • Error if tool is not found
  • Error if arguments are invalid
javascript
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:

typescript
interface JSONRPCMessage {
  jsonrpc: "2.0";
  id: string | number;
  method: string;
  params?: object;
}
javascript
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

javascript
const stderr = client.getStderr();
if (stderr.trim()) {
  console.warn('Server stderr:', stderr);
}

clearStderr()

Clears the stderr buffer.

Returns: void

javascript
client.clearStderr();
// Stderr buffer is now empty

isConnected()

Checks if the client is connected and the MCP handshake has been completed.

Returns: boolean

javascript
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

typescript
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

json
{
  "name": "Simple Server",
  "command": "node",
  "args": ["./server.js"]
}

Advanced Configuration

json
{
  "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:

javascript
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:

javascript
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

typescript
// 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

typescript
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