Skip to main content

Overview

This page provides comprehensive documentation for all Maikers SDK methods and interfaces. The SDK is built with TypeScript and provides full type safety for all operations.

Authentication

Manage API authentication and sessions

Agent Operations

Create, manage, and interact with AI agents

Type Definitions

TypeScript interfaces and types

Error Handling

Error types and handling patterns

SDK Initialization

Constructor

new MaikersSDK(config?: SDKConfig)
Initialize a new instance of the Maikers SDK. Parameters:
ParameterTypeRequiredDescription
configSDKConfigNoConfiguration options for the SDK
SDKConfig Interface:
interface SDKConfig {
  apiKey?: string; // Your Maikers API key
  baseUrl?: string; // API base URL (defaults to production)
  timeout?: number; // Request timeout in milliseconds
  retryAttempts?: number; // Number of retry attempts for failed requests
  retryDelay?: number; // Delay between retries in milliseconds
}
Example:
import { MaikersSDK } from "@maikers/mainframe-sdk";

// Initialize with API key
const sdk = new MaikersSDK({
  apiKey: "your-api-key",
  timeout: 30000,
  retryAttempts: 3,
});

// Initialize without config (uses environment variables)
const sdk = new MaikersSDK();

Authentication Methods

auth()

async auth(apiKey: string): Promise<AuthResponse>
Authenticate with the Maikers API using an API key. Parameters:
ParameterTypeRequiredDescription
apiKeystringYesYour Maikers API key
Returns: Promise<AuthResponse> AuthResponse Interface:
interface AuthResponse {
  success: boolean;
  message: string;
  user?: {
    id: string;
    email: string;
    plan: string;
  };
}
Example:
try {
  const response = await sdk.auth("your-api-key");
  if (response.success) {
    console.log("Authenticated successfully");
  }
} catch (error) {
  console.error("Authentication failed:", error.message);
}

isAuthenticated()

isAuthenticated(): boolean
Check if the SDK is currently authenticated. Returns: boolean Example:
if (sdk.isAuthenticated()) {
  console.log("SDK is authenticated");
} else {
  console.log("Authentication required");
}

logout()

logout(): void
Clear the current authentication session. Example:
sdk.logout();
console.log("Logged out successfully");

Agent Operations

agent.create()

async agent.create(config: AgentConfig): Promise<Agent>
Create a new AI agent with the specified configuration. Parameters:
ParameterTypeRequiredDescription
configAgentConfigYesAgent configuration object
AgentConfig Interface:
interface AgentConfig {
  id: string; // Unique identifier for the agent
  name: string; // Display name for the agent
  description?: string; // Description of the agent's purpose
  riskLevel: "low" | "medium" | "high"; // Risk tolerance level
  jobTypes: string[]; // Array of job types the agent can perform
  skills: string[]; // Array of skills the agent possesses
  personaId?: string; // Persona identifier for the agent
  settings?: AgentSettings; // Additional agent settings
}
AgentSettings Interface:
interface AgentSettings {
  maxCreditsPerTask?: number; // Maximum credits to use per task
  autoExecute?: boolean; // Whether to auto-execute tasks
  notifications?: boolean; // Enable/disable notifications
  timezone?: string; // Agent's timezone
}
Returns: Promise<Agent> Agent Interface:
interface Agent {
  id: string;
  name: string;
  description: string;
  riskLevel: string;
  jobTypes: string[];
  skills: string[];
  status: "active" | "inactive" | "error";
  createdAt: string;
  updatedAt: string;
  credits: number;
  settings: AgentSettings;
}
Example:
const agent = await sdk.agent.create({
  id: "trading-bot-1",
  name: "Advanced Trading Bot",
  description: "AI agent for automated cryptocurrency trading",
  riskLevel: "medium",
  jobTypes: ["trading", "analysis"],
  skills: ["sniper", "analyst", "strategist"],
  personaId: "professional-trader",
  settings: {
    maxCreditsPerTask: 10,
    autoExecute: true,
    notifications: true,
  },
});

console.log("Agent created:", agent.id);

agent.get()

async agent.get(agentId: string): Promise<Agent>
Retrieve information about a specific agent. Parameters:
ParameterTypeRequiredDescription
agentIdstringYesThe unique identifier of the agent
Returns: Promise<Agent> Example:
try {
  const agent = await sdk.agent.get("trading-bot-1");
  console.log("Agent details:", agent);
} catch (error) {
  console.error("Agent not found:", error.message);
}

agent.list()

async agent.list(options?: ListOptions): Promise<Agent[]>
List all agents associated with your account. Parameters:
ParameterTypeRequiredDescription
optionsListOptionsNoFiltering and pagination options
ListOptions Interface:
interface ListOptions {
  limit?: number; // Maximum number of agents to return
  offset?: number; // Number of agents to skip
  status?: string; // Filter by agent status
  skills?: string[]; // Filter by agent skills
  sortBy?: string; // Sort field
  sortOrder?: "asc" | "desc"; // Sort order
}
Returns: Promise<Agent[]> Example:
// List all agents
const allAgents = await sdk.agent.list();

// List active trading agents
const tradingAgents = await sdk.agent.list({
  status: "active",
  skills: ["sniper", "analyst"],
  limit: 10,
});

console.log("Found", tradingAgents.length, "trading agents");

agent.update()

async agent.update(agentId: string, updates: Partial<AgentConfig>): Promise<Agent>
Update an existing agent’s configuration. Parameters:
ParameterTypeRequiredDescription
agentIdstringYesThe unique identifier of the agent
updatesPartial<AgentConfig>YesFields to update
Returns: Promise<Agent> Example:
const updatedAgent = await sdk.agent.update("trading-bot-1", {
  name: "Advanced Trading Bot v2",
  riskLevel: "high",
  settings: {
    maxCreditsPerTask: 15,
    autoExecute: false,
  },
});

console.log("Agent updated:", updatedAgent.name);

agent.updateSettings()

async agent.updateSettings(agentId: string, settings: AgentSettings): Promise<Agent>
Update specific settings for an agent. Parameters:
ParameterTypeRequiredDescription
agentIdstringYesThe unique identifier of the agent
settingsAgentSettingsYesNew settings to apply
Returns: Promise<Agent> Example:
await sdk.agent.updateSettings("trading-bot-1", {
  persona: "aggressive trader",
  risks: ["medium", "high"],
  maxCreditsPerTask: 20,
});

agent.delete()

async agent.delete(agentId: string): Promise<void>
Delete an agent permanently. Parameters:
ParameterTypeRequiredDescription
agentIdstringYesThe unique identifier of the agent
Returns: Promise<void> Example:
try {
  await sdk.agent.delete("trading-bot-1");
  console.log("Agent deleted successfully");
} catch (error) {
  console.error("Failed to delete agent:", error.message);
}

Agent Interaction

agent.query()

async agent.query(agentId: string, query: QueryRequest): Promise<QueryResponse>
Send a query to an agent and receive a response. Parameters:
ParameterTypeRequiredDescription
agentIdstringYesThe unique identifier of the agent
queryQueryRequestYesThe query to send to the agent
QueryRequest Interface:
interface QueryRequest {
  message: string; // The message/question to send
  context?: any; // Additional context for the query
  maxCredits?: number; // Maximum credits to use for this query
  timeout?: number; // Query timeout in milliseconds
  stream?: boolean; // Whether to stream the response
}
Returns: Promise<QueryResponse> QueryResponse Interface:
interface QueryResponse {
  id: string; // Unique response ID
  agentId: string; // ID of the responding agent
  data: string; // The agent's response
  creditsUsed: number; // Credits consumed for this query
  timestamp: string; // Response timestamp
  responseTime: number; // Response time in milliseconds
  metadata?: {
    // Additional response metadata
    confidence?: number;
    sources?: string[];
    reasoning?: string;
  };
}
Example:
const response = await sdk.agent.query("trading-bot-1", {
  message:
    "Analyze the current market conditions for Bitcoin and provide trading recommendations",
  maxCredits: 5,
  timeout: 30000,
});

console.log("Agent response:", response.data);
console.log("Credits used:", response.creditsUsed);
console.log("Response time:", response.responseTime, "ms");

agent.chat()

async agent.chat(agentId: string, options?: ChatOptions): Promise<ChatSession>
Start an interactive chat session with an agent. Parameters:
ParameterTypeRequiredDescription
agentIdstringYesThe unique identifier of the agent
optionsChatOptionsNoChat session options
ChatOptions Interface:
interface ChatOptions {
  sessionId?: string; // Existing session ID to resume
  maxMessages?: number; // Maximum messages in session
  autoSave?: boolean; // Auto-save chat history
  context?: any; // Initial context for the chat
}
Returns: Promise<ChatSession> ChatSession Interface:
interface ChatSession {
  id: string; // Session ID
  agentId: string; // Agent ID
  messages: ChatMessage[]; // Chat history
  status: "active" | "ended"; // Session status
  createdAt: string; // Session creation time

  // Methods
  sendMessage(message: string): Promise<ChatMessage>;
  getHistory(): ChatMessage[];
  end(): Promise<void>;
}
ChatMessage Interface:
interface ChatMessage {
  id: string;
  role: "user" | "agent";
  content: string;
  timestamp: string;
  creditsUsed?: number;
}
Example:
const chatSession = await sdk.agent.chat("trading-bot-1", {
  maxMessages: 50,
  autoSave: true,
});

// Send a message
const response = await chatSession.sendMessage(
  "What are your thoughts on DeFi?",
);
console.log("Agent:", response.content);

// Get chat history
const history = chatSession.getHistory();
console.log("Chat history:", history.length, "messages");

// End the session
await chatSession.end();

Error Handling

Error Types

The SDK throws specific error types for different scenarios:
// Base error class
class MaikersError extends Error {
  code: string;
  statusCode?: number;
  details?: any;
}

// Authentication errors
class AuthenticationError extends MaikersError {
  code = "AUTHENTICATION_FAILED";
}

// Agent not found errors
class AgentNotFoundError extends MaikersError {
  code = "AGENT_NOT_FOUND";
}

// Rate limit errors
class RateLimitError extends MaikersError {
  code = "RATE_LIMIT_EXCEEDED";
  retryAfter?: number;
}

// Network errors
class NetworkError extends MaikersError {
  code = "NETWORK_ERROR";
}

// Validation errors
class ValidationError extends MaikersError {
  code = "VALIDATION_ERROR";
  field?: string;
}

Error Handling Examples

import {
  MaikersSDK,
  AuthenticationError,
  AgentNotFoundError,
  RateLimitError,
} from "@maikers/mainframe-sdk";

try {
  const response = await sdk.agent.query("agent-id", {
    message: "Hello",
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("Please check your API key");
  } else if (error instanceof AgentNotFoundError) {
    console.error("Agent does not exist");
  } else if (error instanceof RateLimitError) {
    console.error("Rate limit exceeded, retry after:", error.retryAfter);
  } else {
    console.error("Unexpected error:", error.message);
  }
}

Utility Methods

getCredits()

async getCredits(): Promise<CreditsInfo>
Get information about your current credit balance and usage. Returns: Promise<CreditsInfo> CreditsInfo Interface:
interface CreditsInfo {
  balance: number; // Current credit balance
  used: number; // Credits used this period
  limit: number; // Credit limit for current plan
  resetDate: string; // When credits reset
  plan: string; // Current subscription plan
}
Example:
const credits = await sdk.getCredits();
console.log("Credit balance:", credits.balance);
console.log("Credits used:", credits.used);
console.log("Plan:", credits.plan);

getUsage()

async getUsage(period?: 'day' | 'week' | 'month'): Promise<UsageStats>
Get usage statistics for your account. Parameters:
ParameterTypeRequiredDescription
period'day' | 'week' | 'month'NoTime period for stats (default: ‘month’)
Returns: Promise<UsageStats> UsageStats Interface:
interface UsageStats {
  period: string;
  totalQueries: number;
  totalCreditsUsed: number;
  agentCount: number;
  averageResponseTime: number;
  topAgents: Array<{
    agentId: string;
    name: string;
    queries: number;
    creditsUsed: number;
  }>;
}
Example:
const usage = await sdk.getUsage("week");
console.log("Weekly stats:", usage);
console.log("Total queries:", usage.totalQueries);
console.log("Top agent:", usage.topAgents[0]?.name);

Type Definitions

Complete Type Reference

// Main SDK class
export class MaikersSDK {
  constructor(config?: SDKConfig);
  auth(apiKey: string): Promise<AuthResponse>;
  isAuthenticated(): boolean;
  logout(): void;
  getCredits(): Promise<CreditsInfo>;
  getUsage(period?: "day" | "week" | "month"): Promise<UsageStats>;

  agent: {
    create(config: AgentConfig): Promise<Agent>;
    get(agentId: string): Promise<Agent>;
    list(options?: ListOptions): Promise<Agent[]>;
    update(agentId: string, updates: Partial<AgentConfig>): Promise<Agent>;
    updateSettings(agentId: string, settings: AgentSettings): Promise<Agent>;
    delete(agentId: string): Promise<void>;
    query(agentId: string, query: QueryRequest): Promise<QueryResponse>;
    chat(agentId: string, options?: ChatOptions): Promise<ChatSession>;
  };
}

// Export all interfaces
export {
  SDKConfig,
  AgentConfig,
  AgentSettings,
  Agent,
  QueryRequest,
  QueryResponse,
  ChatOptions,
  ChatSession,
  ChatMessage,
  AuthResponse,
  CreditsInfo,
  UsageStats,
  ListOptions,
};

// Export error classes
export {
  MaikersError,
  AuthenticationError,
  AgentNotFoundError,
  RateLimitError,
  NetworkError,
  ValidationError,
};

Next Steps