npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@toolplex/ai-engine

v0.1.3

Published

Core AI chat engine for ToolPlex - powers desktop, cloud, and CLI

Downloads

384

Readme

@toolplex/ai-engine

The core AI chat engine for ToolPlex. A TypeScript SDK that provides a unified interface for building AI-powered applications with tool calling via the Model Context Protocol (MCP).

Features

  • Multi-provider support - Anthropic, OpenAI, Google Gemini, OpenRouter
  • MCP integration - Connect to ToolPlex's MCP server for powerful tool calling
  • Transport abstraction - Works in CLI, desktop (Electron), or cloud environments
  • AI SDK wrapper - Built on Vercel AI SDK with ToolPlex-specific enhancements

Installation

npm install @toolplex/ai-engine

Quick Start

Basic Chat (No Tools)

import { streamText, createAnthropic } from '@toolplex/ai-engine';

const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

const result = await streamText({
  model: anthropic('claude-sonnet-4-20250514'),
  messages: [{ role: 'user', content: 'Hello!' }],
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}

With ToolPlex MCP Tools

import {
  MCPClient,
  defaultStdioTransportFactory,
  streamText,
  createAnthropic
} from '@toolplex/ai-engine';

// Create MCP client (connects to @toolplex/client)
const mcpClient = new MCPClient({
  transportFactory: defaultStdioTransportFactory,
});

// Create a session
await mcpClient.createSession('my-session', process.env.TOOLPLEX_API_KEY);

// List available tools
const { tools } = await mcpClient.listTools('my-session');
console.log('Available tools:', tools.map(t => t.name));

// Call a tool
const result = await mcpClient.callTool('my-session', 'search_servers', {
  query: 'weather',
});

// Clean up
await mcpClient.destroySession('my-session');

API Reference

Providers

import {
  createAnthropic,
  createOpenAI,
  createGoogleGenerativeAI,
  createOpenRouter,
  getProvider,
  getModel,
} from '@toolplex/ai-engine';

// Direct provider creation
const anthropic = createAnthropic({ apiKey: '...' });
const openai = createOpenAI({ apiKey: '...' });

// Or use the unified getProvider helper
const model = getModel('anthropic/claude-sonnet-4-20250514', {
  anthropicApiKey: '...',
});

MCP Client

import { MCPClient, TransportFactory } from '@toolplex/ai-engine';

const client = new MCPClient({
  transportFactory: myTransportFactory,
  logger: console, // optional
});

// Session management
await client.createSession(sessionId, apiKey, resumeHistory?);
await client.destroySession(sessionId);
client.getActiveSessions();
client.hasSession(sessionId);

// Tool operations
await client.listTools(sessionId);
await client.callTool(sessionId, toolName, args);

Transport Factory

The TransportFactory interface allows you to customize how the MCP server is spawned:

import { TransportFactory, MCPSession } from '@toolplex/ai-engine';

class MyCustomTransportFactory implements TransportFactory {
  async createTransport(apiKey: string, resumeHistory?: string): Promise<MCPSession> {
    // Spawn @toolplex/client with custom configuration
    // Return { client, transport }
  }

  async closeTransport(session: MCPSession): Promise<void> {
    await session.client.close();
  }
}

Built-in transports:

  • defaultStdioTransportFactory - Uses system Node.js (for CLI apps)

Utilities

import {
  // Schema utilities
  deepSanitizeParams,
  resolveSchemaRefs,
  sanitizeSchemaForGemini,

  // Model detection
  isChatGPTModel,
  isGoogleGeminiModel,
  isAnthropicModel,
  parseModelId,

  // Path utilities
  getToolplexClientPath,
} from '@toolplex/ai-engine';

AI SDK Re-exports

For convenience, common AI SDK exports are re-exported:

import {
  streamText,
  tool,
  jsonSchema,
  stepCountIs,
  type CoreMessage,
  type ToolResultPart,
  type ToolCallPart,
} from '@toolplex/ai-engine';

Custom Transport Example (Electron)

For Electron apps with bundled Node.js:

import {
  MCPClient,
  MCPSDKClient as Client,
  StdioClientTransport,
  getToolplexClientPath,
  type TransportFactory,
  type MCPSession,
} from '@toolplex/ai-engine';

class ElectronTransportFactory implements TransportFactory {
  async createTransport(apiKey: string): Promise<MCPSession> {
    const toolplexPath = getToolplexClientPath();

    const transport = new StdioClientTransport({
      command: '/path/to/bundled/node', // Use bundled Node.js
      args: [toolplexPath],
      env: {
        ...process.env,
        TOOLPLEX_API_KEY: apiKey,
      },
    });

    const client = new Client({ name: 'my-app', version: '1.0.0' });
    await client.connect(transport);

    return { transport, client };
  }

  async closeTransport(session: MCPSession): Promise<void> {
    await session.client.close();
  }
}

const mcpClient = new MCPClient({
  transportFactory: new ElectronTransportFactory(),
});

Environment Variables

When using defaultStdioTransportFactory, these environment variables are passed to the MCP server:

  • TOOLPLEX_API_KEY - Your ToolPlex API key (required)
  • TOOLPLEX_SESSION_RESUME_HISTORY - JSON string containing historical tool usage for resumed sessions

Session Resume History

When restoring a chat session from a database, the MCP server needs context about what tools were previously used. This allows the enforcement layer to validate operations like save_playbook and submit_feedback which depend on historical tool usage.

The resumeHistory parameter is a JSON string with the following structure:

interface SessionResumeHistory {
  tool_calls: Array<{ server_id: string; tool_name: string }>;
  installs: Array<{ server_id: string }>;
  uninstalls: Array<{ server_id: string }>;
}

Example usage:

// When creating a session with history (e.g., restoring from database)
const resumeHistory = JSON.stringify({
  tool_calls: [
    { server_id: 'weather-server', tool_name: 'get_forecast' },
    { server_id: 'calendar-server', tool_name: 'create_event' },
  ],
  installs: [
    { server_id: 'weather-server' },
  ],
  uninstalls: [],
});

await mcpClient.createSession('my-session', apiKey, resumeHistory);

In a custom transport factory:

class MyTransportFactory implements TransportFactory {
  async createTransport(apiKey: string, sessionResumeHistory?: string): Promise<MCPSession> {
    const transport = new StdioClientTransport({
      command: 'node',
      args: [toolplexPath],
      env: {
        ...process.env,
        TOOLPLEX_API_KEY: apiKey,
        // Pass resume history to the MCP server process
        ...(sessionResumeHistory && { TOOLPLEX_SESSION_RESUME_HISTORY: sessionResumeHistory }),
      },
    });

    const client = new Client({ name: 'my-app', version: '1.0.0' });
    await client.connect(transport);
    return { transport, client };
  }
}

This is particularly useful in desktop applications where chat sessions are persisted and can be restored later.

Requirements

License

BSL 1.1

Links