toolrouter
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 โ€ข Public โ€ข Published

ToolRouter TypeScript SDK

A comprehensive TypeScript client for the ToolRouter API supporting both direct access and account-level operations with full async support and type safety.

๐Ÿ”— Quick Links:

โœจ ToolRouter Key Features

๐Ÿš€ Instant Integration - Deploy Model Control Panels (MCPs) in seconds and seamlessly integrate with your AI agents

๐Ÿ” Authentication Made Simple - Built-in credential management with secure authentication handling, no manual setup needed

๐Ÿ”„ Flexible Tool Composition - Mix and match tools across different MCPs to create powerful custom workflows

๐Ÿค– Universal Model Support - Compatible with OpenAI, Anthropic, Meta Llama, and all major AI models

๐Ÿ› ๏ธ Extensive Tool Library - Access to 450+ production-ready tools across 40+ MCPs, with bi-weekly updates

๐Ÿ’ช Enterprise-Grade Reliability - Production-tested infrastructure trusted by numerous companies, with continuous improvements

๐Ÿš€ SDK Features

  • Two Client Types: DirectAccessClient for MCP-style tool calling, APIClient for full account management
  • Full TypeScript Support: Complete type safety with comprehensive interfaces and error types
  • Modern Async/Await: Built with axios for reliable HTTP communications
  • Error Handling: Custom exception classes for different error types
  • Rate Limiting: Built-in client-side rate limiting with sliding window
  • Retry Logic: Automatic retry with exponential backoff
  • Schema Support: OpenAI, Anthropic, and default schema formats
  • Backward Compatibility: Maintains compatibility with existing ToolRouter class
  • Production Ready: Comprehensive error handling, logging, and testing

๐Ÿ“ฆ Installation

npm install toolrouter

๐Ÿƒ Quick Start

Direct Access (MCP-style)

import { DirectAccessClient } from 'toolrouter';

async function main() {
  const client = new DirectAccessClient(
    "your-client-id",
    "your-api-key",
    "https://api.toolrouter.ai/s", // optional
    "openai" // or "anthropic", "default"
  );
  
  try {
    // List available tools
    const tools = await client.listTools();
    console.log(`Available: ${tools.length} tools`);
    
    // Call a tool
    if (tools.length > 0) {
      const result = await client.callTool(
        tools[0].name,
        { location: "San Francisco" }
      );
      console.log('Result:', result);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

main();

Account Management

import { APIClient } from 'toolrouter';

async function main() {
  const client = new APIClient(
    "your-account-api-key",
    "https://api.toolrouter.ai/v1", // optional
    "openai"
  );
  
  try {
    // Create a stack with server
    const stack = await client.createStackWithServer(
      "my-ai-stack",
      "github-server",
      true, // enable all tools
      false, // analytics disabled
      { token: "ghp_your_token" }
    );
    
    // List tools in the stack
    const tools = await client.listStackTools(stack.stack_id);
    console.log(`Stack has ${tools.length} tools available`);
    
    // Invoke a tool
    const result = await client.invokeTool(
      stack.stack_id,
      "create_issue",
      { title: "Bug report", body: "Description" }
    );
    console.log('Tool result:', result);
  } catch (error) {
    console.error('Error:', error);
  }
}

main();

๐Ÿ“š API Documentation

Available Methods

DirectAccessClient (MCP-Style)

Method Description Parameters Returns
listTools() Get available tools from ToolRouter schema?: SchemaType Promise<Tool[]>
callTool() Call a tool using ToolRouter toolName: string, toolInput: Record<string, any> Promise<any>

APIClient (Account Level API)

Stack Management
Method Description Parameters Returns
listStacks() List all stacks None Promise<Stack[]>
createStack() Create a new stack stackName: string, analyticsEnabled?: boolean Promise<Stack>
updateStack() Update an existing stack stackId: string, stackName?: string, analyticsEnabled?: boolean Promise<Stack>
deleteStack() Delete a stack stackId: string Promise<boolean>
Server Management
Method Description Parameters Returns
listServers() List all available servers None Promise<Server[]>
addServerToStack() Add a server to a stack stackId: string, serverId: string, enableAllTools?: boolean, enabledTools?: string[] Promise<boolean>
removeServerFromStack() Remove a server from a stack stackId: string, serverId: string Promise<boolean>
updateServerTools() Update enabled tools for a server stackId: string, serverId: string, enabledTools: string[] Promise<boolean>
Credential Management
Method Description Parameters Returns
getCredentialsStatus() Get credentials status for a server stackId: string, serverId: string Promise<CredentialsStatus>
updateCredentials() Update credentials for a server stackId: string, serverId: string, credentials: Record<string, string> Promise<boolean>
Tool Operations
Method Description Parameters Returns
listStackTools() List tools available in a stack stackId: string, schema?: SchemaType Promise<Tool[]>
invokeTool() Invoke a tool in a stack stackId: string, toolId: string, toolInput: Record<string, any> Promise<any>
Convenience Methods
Method Description Parameters Returns
createStackWithServer() Create stack and add server in one call stackName: string, serverId: string, enableAllTools?: boolean, analyticsEnabled?: boolean, credentials?: Record<string, string> Promise<Stack>
getStackSummary() Get comprehensive stack summary stackId: string Promise<StackSummary>

Backward Compatibility Functions

Function Description Parameters Returns
setupDefaultRouter() Configure the default direct access client clientId: string, apiKey: string, baseUrl?: string, options?: BaseClientOptions DirectAccessClient
listTools() Async wrapper for list_tools (uses default client) schema?: SchemaType Promise<Tool[]>
callTool() Async wrapper for call_tool (uses default client) toolName: string, toolInput: Record<string, any> Promise<any>

Usage Examples

DirectAccessClient

For MCP-style direct tool access:

import { DirectAccessClient } from 'toolrouter';

const client = new DirectAccessClient(
  "your-client-id",
  "your-api-key",
  "https://api.toolrouter.ai/s", // optional
  "openai", // or "anthropic", "default"
  {
    timeout: 30000,
    maxRetries: 3,
    rateLimitRequests: 60,
    rateLimitWindow: 60000
  }
);

// List tools
const tools = await client.listTools("openai");

// Call tool
const result = await client.callTool("tool_name", { param: "value" });

APIClient

For full account and stack management:

import { APIClient } from 'toolrouter';

const client = new APIClient(
  "your-account-api-key",
  "https://api.toolrouter.ai/v1", // optional
  "openai",
  {
    timeout: 30000,
    maxRetries: 3
  }
);

// Stack operations
const stacks = await client.listStacks();
const stack = await client.createStack("My Stack", true);
await client.updateStack(stack.stack_id, "Updated Name");
await client.deleteStack(stack.stack_id);

// Server operations
const servers = await client.listServers();
await client.addServerToStack(stackId, serverId, true);
await client.removeServerFromStack(stackId, serverId);
await client.updateServerTools(stackId, serverId, ["tool1", "tool2"]);

// Credential management
const status = await client.getCredentialsStatus(stackId, serverId);
await client.updateCredentials(stackId, serverId, { api_key: "secret" });

// Tool operations
const tools = await client.listStackTools(stackId, "openai");
const result = await client.invokeTool(stackId, toolId, { param: "value" });

// Convenience methods
const stack = await client.createStackWithServer(
  "Stack Name", "server-id",
  true, // enable all tools
  false, // analytics disabled
  { token: "secret" }
);
const summary = await client.getStackSummary(stackId);

๐Ÿ”ง Configuration

Environment Variables

export TOOLROUTER_CLIENT_ID="your-client-id"
export TOOLROUTER_API_KEY="your-api-key"
export TOOLROUTER_ACCOUNT_API_KEY="your-account-api-key"

Client Configuration

import { BaseClientOptions } from 'toolrouter';

// Custom configuration
const options: BaseClientOptions = {
  timeout: 60000,           // Request timeout in ms
  maxRetries: 5,            // Retry attempts
  rateLimitRequests: 100,   // Requests per window
  rateLimitWindow: 60000    // Window in milliseconds
};

const client = new DirectAccessClient(
  "your-client-id",
  "your-api-key",
  "https://api.toolrouter.ai/s",
  "openai",
  options
);

๐Ÿšจ Error Handling

The SDK provides specific exception types:

import {
  ToolRouterError,        // Base exception
  AuthenticationError,    // Invalid credentials
  NotFoundError,         // Resource not found
  ValidationError,       // Invalid request
  ServerError,          // Server-side error
  RateLimitError        // Rate limit exceeded
} from 'toolrouter';

try {
  const result = await client.callTool("tool_name", {});
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log("Check your API key");
  } else if (error instanceof NotFoundError) {
    console.log("Tool or resource not found");
  } else if (error instanceof RateLimitError) {
    console.log("Rate limit exceeded, slow down");
  } else if (error instanceof ToolRouterError) {
    console.log(`General error: ${error.message} (Status: ${error.statusCode})`);
  }
}

๐Ÿ”„ Backward Compatibility

Existing code continues to work:

// Old API still works
import { ToolRouter, setupDefaultRouter, listTools, callTool } from 'toolrouter';

setupDefaultRouter("client-id", "api-key");
const tools = await listTools("openai");
const result = await callTool("tool_name", { param: "value" });

// ToolRouter class is now an alias for DirectAccessClient
const client = new ToolRouter("client-id", "api-key"); // Same as DirectAccessClient

๐Ÿ—๏ธ Architecture

src/
โ”œโ”€โ”€ index.ts              # Main SDK implementation
โ”‚   โ”œโ”€โ”€ BaseClient        # Shared functionality
โ”‚   โ”œโ”€โ”€ DirectAccessClient # MCP-style tool calling
โ”‚   โ”œโ”€โ”€ APIClient         # Account management
โ”‚   โ”œโ”€โ”€ Error classes     # Custom error types
โ”‚   โ””โ”€โ”€ TypeScript interfaces # Type safety
tests/
โ”œโ”€โ”€ toolrouter.test.ts    # Comprehensive test suite
package.json              # Package configuration
tsconfig.json            # TypeScript configuration
.eslintrc.js            # Linting configuration

๐Ÿงช Development

Running Tests

# Install dev dependencies
npm install

# Run tests
npm test

# Run tests with coverage
npm test -- --coverage

# Build the project
npm run build

# Lint the code
npm run lint

Code Quality

# Lint and fix issues
npm run lint -- --fix

# Build TypeScript
npm run build

# Run all checks
npm test && npm run build && npm run lint

๐Ÿ“‹ TypeScript Interfaces

The SDK provides comprehensive TypeScript interfaces:

// Core interfaces
interface Tool {
  tool_id?: string;
  name: string;
  description: string;
  parameters: Record<string, any>;
  input_schema?: Record<string, any>;
  server?: string;
}

interface Stack {
  stack_id: string;
  stack_name: string;
  configuration: StackConfiguration;
  servers: StackServer[];
  created_at: string;
  updated_at: string;
}

interface Server {
  server_id: string;
  name: string;
  description: string;
  tools: Tool[];
  required_credentials: Credential[];
  optional_credentials: Credential[];
}

// Schema types
type SchemaType = 'openai' | 'anthropic' | 'default';

// Configuration options
interface BaseClientOptions {
  timeout?: number;
  maxRetries?: number;
  rateLimitRequests?: number;
  rateLimitWindow?: number;
}

๐Ÿ“ Changelog

v0.2.0

  • โœจ Added APIClient for account-level operations
  • โœจ Full TypeScript support with comprehensive interfaces
  • โœจ Custom exception hierarchy with proper error handling
  • โœจ Built-in rate limiting and retry logic
  • โœจ Support for multiple schema formats (OpenAI, Anthropic, default)
  • โœจ Convenience methods for common workflows
  • โœจ Production-ready error handling and logging
  • ๐Ÿ”„ Maintained backward compatibility with ToolRouter class
  • ๐Ÿ“š Comprehensive test suite with 77%+ coverage

v0.1.0

  • ๐ŸŽ‰ Initial release with basic ToolRouter functionality

๐Ÿ“„ License

Apache 2.0 License - see LICENSE file for details.

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Add tests for new functionality
  4. Ensure all tests pass (npm test)
  5. Build successfully (npm run build)
  6. Lint your code (npm run lint)
  7. Commit your changes (git commit -m 'Add amazing feature')
  8. Push to the branch (git push origin feature/amazing-feature)
  9. Open a Pull Request

๐Ÿ“ž Support


Made with โค๏ธ by the ToolRouter team

Package Sidebar

Install

npm i toolrouter

Weekly Downloads

8

Version

1.1.0

License

Apache-2.0

Unpacked Size

62.3 kB

Total Files

5

Last publish

Collaborators

  • toolrouter-admin